path
stringlengths
5
300
repo_name
stringlengths
6
76
content
stringlengths
26
1.05M
kitchensink/ios/index.js
junewinds/jmui
import { hashHistory } from 'react-router' import getRoutes from './routes' import Root from './Root' import React from 'react' import ReactDOM from 'react-dom' const routes = getRoutes() ReactDOM.render( <Root history={hashHistory} routes={routes} />, document.getElementById('root') )
files/firebuglite/1.4.0/firebug-lite-debug.js
EragonJ/jsdelivr
(function(){ /*!************************************************************* * * Firebug Lite 1.4.0 * * Copyright (c) 2007, Parakey Inc. * Released under BSD license. * More information: http://getfirebug.com/firebuglite * **************************************************************/ /*! * CSS selectors powered by: * * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ /** @namespace describe lib */ // FIXME: xxxpedro if we use "var FBL = {}" the FBL won't appear in the DOM Panel in IE var FBL = {}; ( /** @scope s_lib @this FBL */ function() { // ************************************************************************************************ // ************************************************************************************************ // Constants var productionDir = "http://getfirebug.com/releases/lite/"; var bookmarkletVersion = 4; // ************************************************************************************************ var reNotWhitespace = /[^\s]/; var reSplitFile = /:\/{1,3}(.*?)\/([^\/]*?)\/?($|\?.*)/; // Globals this.reJavascript = /\s*javascript:\s*(.*)/; this.reChrome = /chrome:\/\/([^\/]*)\//; this.reFile = /file:\/\/([^\/]*)\//; // ************************************************************************************************ // properties var userAgent = navigator.userAgent.toLowerCase(); this.isFirefox = /firefox/.test(userAgent); this.isOpera = /opera/.test(userAgent); this.isSafari = /webkit/.test(userAgent); this.isIE = /msie/.test(userAgent) && !/opera/.test(userAgent); this.isIE6 = /msie 6/i.test(navigator.appVersion); this.browserVersion = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]; this.isIElt8 = this.isIE && (this.browserVersion-0 < 8); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.NS = null; this.pixelsPerInch = null; // ************************************************************************************************ // Namespaces var namespaces = []; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.ns = function(fn) { var ns = {}; namespaces.push(fn, ns); return ns; }; var FBTrace = null; this.initialize = function() { // Firebug Lite is already running in persistent mode so we just quit if (window.firebug && firebug.firebuglite || window.console && console.firebuglite) return; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // initialize environment // point the FBTrace object to the local variable if (FBL.FBTrace) FBTrace = FBL.FBTrace; else FBTrace = FBL.FBTrace = {}; // check if the actual window is a persisted chrome context var isChromeContext = window.Firebug && typeof window.Firebug.SharedEnv == "object"; // chrome context of the persistent application if (isChromeContext) { // TODO: xxxpedro persist - make a better synchronization sharedEnv = window.Firebug.SharedEnv; delete window.Firebug.SharedEnv; FBL.Env = sharedEnv; FBL.Env.isChromeContext = true; FBTrace.messageQueue = FBL.Env.traceMessageQueue; } // non-persistent application else { FBL.NS = document.documentElement.namespaceURI; FBL.Env.browser = window; FBL.Env.destroy = destroyEnvironment; if (document.documentElement.getAttribute("debug") == "true") FBL.Env.Options.startOpened = true; // find the URL location of the loaded application findLocation(); // TODO: get preferences here... // The problem is that we don't have the Firebug object yet, so we can't use // Firebug.loadPrefs. We're using the Store module directly instead. var prefs = FBL.Store.get("FirebugLite") || {}; FBL.Env.DefaultOptions = FBL.Env.Options; FBL.Env.Options = FBL.extend(FBL.Env.Options, prefs.options || {}); if (FBL.isFirefox && typeof FBL.Env.browser.console == "object" && FBL.Env.browser.console.firebug && FBL.Env.Options.disableWhenFirebugActive) return; } // exposes the FBL to the global namespace when in debug mode if (FBL.Env.isDebugMode) { FBL.Env.browser.FBL = FBL; } // check browser compatibilities this.isQuiksMode = FBL.Env.browser.document.compatMode == "BackCompat"; this.isIEQuiksMode = this.isIE && this.isQuiksMode; this.isIEStantandMode = this.isIE && !this.isQuiksMode; this.noFixedPosition = this.isIE6 || this.isIEQuiksMode; // after creating/synchronizing the environment, initialize the FBTrace module if (FBL.Env.Options.enableTrace) FBTrace.initialize(); if (FBTrace.DBG_INITIALIZE && isChromeContext) FBTrace.sysout("FBL.initialize - persistent application", "initialize chrome context"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // initialize namespaces if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("FBL.initialize", namespaces.length/2+" namespaces BEGIN"); for (var i = 0; i < namespaces.length; i += 2) { var fn = namespaces[i]; var ns = namespaces[i+1]; fn.apply(ns); } if (FBTrace.DBG_INITIALIZE) { FBTrace.sysout("FBL.initialize", namespaces.length/2+" namespaces END"); FBTrace.sysout("FBL waitForDocument", "waiting document load"); } FBL.Ajax.initialize(); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // finish environment initialization FBL.Firebug.loadPrefs(); if (FBL.Env.Options.enablePersistent) { // TODO: xxxpedro persist - make a better synchronization if (isChromeContext) { FBL.FirebugChrome.clone(FBL.Env.FirebugChrome); } else { FBL.Env.FirebugChrome = FBL.FirebugChrome; FBL.Env.traceMessageQueue = FBTrace.messageQueue; } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // wait document load waitForDocument(); }; var waitForDocument = function waitForDocument() { // document.body not available in XML+XSL documents in Firefox var doc = FBL.Env.browser.document; var body = doc.getElementsByTagName("body")[0]; if (body) { calculatePixelsPerInch(doc, body); onDocumentLoad(); } else setTimeout(waitForDocument, 50); }; var onDocumentLoad = function onDocumentLoad() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("FBL onDocumentLoad", "document loaded"); // fix IE6 problem with cache of background images, causing a lot of flickering if (FBL.isIE6) fixIE6BackgroundImageCache(); // chrome context of the persistent application if (FBL.Env.Options.enablePersistent && FBL.Env.isChromeContext) { // finally, start the application in the chrome context FBL.Firebug.initialize(); // if is not development mode, remove the shared environment cache object // used to synchronize the both persistent contexts if (!FBL.Env.isDevelopmentMode) { sharedEnv.destroy(); sharedEnv = null; } } // non-persistent application else { FBL.FirebugChrome.create(); } }; // ************************************************************************************************ // Env var sharedEnv; this.Env = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Env Options (will be transported to Firebug options) Options: { saveCookies: true, saveWindowPosition: false, saveCommandLineHistory: false, startOpened: false, startInNewWindow: false, showIconWhenHidden: true, overrideConsole: true, ignoreFirebugElements: true, disableWhenFirebugActive: true, disableXHRListener: false, disableResourceFetching: false, enableTrace: false, enablePersistent: false }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Library location Location: { sourceDir: null, baseDir: null, skinDir: null, skin: null, app: null }, skin: "xp", useLocalSkin: false, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Env states isDevelopmentMode: false, isDebugMode: false, isChromeContext: false, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Env references browser: null, chrome: null }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var destroyEnvironment = function destroyEnvironment() { setTimeout(function() { FBL = null; }, 100); }; // ************************************************************************************************ // Library location var findLocation = function findLocation() { var reFirebugFile = /(firebug-lite(?:-\w+)?(?:\.js|\.jgz))(?:#(.+))?$/; var reGetFirebugSite = /(?:http|https):\/\/getfirebug.com\//; var isGetFirebugSite; var rePath = /^(.*\/)/; var reProtocol = /^\w+:\/\//; var path = null; var doc = document; // Firebug Lite 1.3.0 bookmarklet identification var script = doc.getElementById("FirebugLite"); var scriptSrc; var hasSrcAttribute = true; // If the script was loaded via bookmarklet, we already have the script tag if (script) { scriptSrc = script.src; file = reFirebugFile.exec(scriptSrc); var version = script.getAttribute("FirebugLite"); var number = version ? parseInt(version) : 0; if (!version || !number || number < bookmarkletVersion) { FBL.Env.bookmarkletOutdated = true; } } // otherwise we must search for the correct script tag else { for(var i=0, s=doc.getElementsByTagName("script"), si; si=s[i]; i++) { var file = null; if ( si.nodeName.toLowerCase() == "script" ) { if (file = reFirebugFile.exec(si.getAttribute("firebugSrc"))) { scriptSrc = si.getAttribute("firebugSrc"); hasSrcAttribute = false; } else if (file = reFirebugFile.exec(si.src)) { scriptSrc = si.src; } else continue; script = si; break; } } } // mark the script tag to be ignored by Firebug Lite if (script) script.firebugIgnore = true; if (file) { var fileName = file[1]; var fileOptions = file[2]; // absolute path if (reProtocol.test(scriptSrc)) { path = rePath.exec(scriptSrc)[1]; } // relative path else { var r = rePath.exec(scriptSrc); var src = r ? r[1] : scriptSrc; var backDir = /^((?:\.\.\/)+)(.*)/.exec(src); var reLastDir = /^(.*\/)[^\/]+\/$/; path = rePath.exec(location.href)[1]; // "../some/path" if (backDir) { var j = backDir[1].length/3; var p; while (j-- > 0) path = reLastDir.exec(path)[1]; path += backDir[2]; } else if(src.indexOf("/") != -1) { // "./some/path" if(/^\.\/./.test(src)) { path += src.substring(2); } // "/some/path" else if(/^\/./.test(src)) { var domain = /^(\w+:\/\/[^\/]+)/.exec(path); path = domain[1] + src; } // "some/path" else { path += src; } } } } FBL.Env.isChromeExtension = script && script.getAttribute("extension") == "Chrome"; if (FBL.Env.isChromeExtension) { path = productionDir; FBL.Env.bookmarkletOutdated = false; script = {innerHTML: "{showIconWhenHidden:false}"}; } isGetFirebugSite = reGetFirebugSite.test(path); if (isGetFirebugSite && path.indexOf("/releases/lite/") == -1) { // See Issue 4587 - If we are loading the script from getfirebug.com shortcut, like // https://getfirebug.com/firebug-lite.js, then we must manually add the full path, // otherwise the Env.Location will hold the wrong path, which will in turn lead to // undesirable effects like the problem in Issue 4587 path += "releases/lite/" + (fileName == "firebug-lite-beta.js" ? "beta/" : "latest/"); } var m = path && path.match(/([^\/]+)\/$/) || null; if (path && m) { var Env = FBL.Env; // Always use the local skin when running in the same domain // See Issue 3554: Firebug Lite should use local images when loaded locally Env.useLocalSkin = path.indexOf(location.protocol + "//" + location.host + "/") == 0 && // but we cannot use the locan skin when loaded from getfirebug.com, otherwise // the bookmarklet won't work when visiting getfirebug.com !isGetFirebugSite; // detecting development and debug modes via file name if (fileName == "firebug-lite-dev.js") { Env.isDevelopmentMode = true; Env.isDebugMode = true; } else if (fileName == "firebug-lite-debug.js") { Env.isDebugMode = true; } // process the <html debug="true"> if (Env.browser.document.documentElement.getAttribute("debug") == "true") { Env.Options.startOpened = true; } // process the Script URL Options if (fileOptions) { var options = fileOptions.split(","); for (var i = 0, length = options.length; i < length; i++) { var option = options[i]; var name, value; if (option.indexOf("=") != -1) { var parts = option.split("="); name = parts[0]; value = eval(unescape(parts[1])); } else { name = option; value = true; } if (name == "debug") { Env.isDebugMode = !!value; } else if (name in Env.Options) { Env.Options[name] = value; } else { Env[name] = value; } } } // process the Script JSON Options if (hasSrcAttribute) { var innerOptions = FBL.trim(script.innerHTML); if (innerOptions) { var innerOptionsObject = eval("(" + innerOptions + ")"); for (var name in innerOptionsObject) { var value = innerOptionsObject[name]; if (name == "debug") { Env.isDebugMode = !!value; } else if (name in Env.Options) { Env.Options[name] = value; } else { Env[name] = value; } } } } if (!Env.Options.saveCookies) FBL.Store.remove("FirebugLite"); // process the Debug Mode if (Env.isDebugMode) { Env.Options.startOpened = true; Env.Options.enableTrace = true; Env.Options.disableWhenFirebugActive = false; } var loc = Env.Location; var isProductionRelease = path.indexOf(productionDir) != -1; loc.sourceDir = path; loc.baseDir = path.substr(0, path.length - m[1].length - 1); loc.skinDir = (isProductionRelease ? path : loc.baseDir) + "skin/" + Env.skin + "/"; loc.skin = loc.skinDir + "firebug.html"; loc.app = path + fileName; } else { throw new Error("Firebug Error: Library path not found"); } }; // ************************************************************************************************ // Basics this.bind = function() // fn, thisObject, args => thisObject.fn(args, arguments); { var args = cloneArray(arguments), fn = args.shift(), object = args.shift(); return function() { return fn.apply(object, arrayInsert(cloneArray(args), 0, arguments)); }; }; this.bindFixed = function() // fn, thisObject, args => thisObject.fn(args); { var args = cloneArray(arguments), fn = args.shift(), object = args.shift(); return function() { return fn.apply(object, args); }; }; this.extend = function(l, r) { var newOb = {}; for (var n in l) newOb[n] = l[n]; for (var n in r) newOb[n] = r[n]; return newOb; }; this.descend = function(prototypeParent, childProperties) { function protoSetter() {}; protoSetter.prototype = prototypeParent; var newOb = new protoSetter(); for (var n in childProperties) newOb[n] = childProperties[n]; return newOb; }; this.append = function(l, r) { for (var n in r) l[n] = r[n]; return l; }; this.keys = function(map) // At least sometimes the keys will be on user-level window objects { var keys = []; try { for (var name in map) // enumeration is safe keys.push(name); // name is string, safe } catch (exc) { // Sometimes we get exceptions trying to iterate properties } return keys; // return is safe }; this.values = function(map) { var values = []; try { for (var name in map) { try { values.push(map[name]); } catch (exc) { // Sometimes we get exceptions trying to access properties if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.values FAILED ", exc); } } } catch (exc) { // Sometimes we get exceptions trying to iterate properties if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.values FAILED ", exc); } return values; }; this.remove = function(list, item) { for (var i = 0; i < list.length; ++i) { if (list[i] == item) { list.splice(i, 1); break; } } }; this.sliceArray = function(array, index) { var slice = []; for (var i = index; i < array.length; ++i) slice.push(array[i]); return slice; }; function cloneArray(array, fn) { var newArray = []; if (fn) for (var i = 0; i < array.length; ++i) newArray.push(fn(array[i])); else for (var i = 0; i < array.length; ++i) newArray.push(array[i]); return newArray; } function extendArray(array, array2) { var newArray = []; newArray.push.apply(newArray, array); newArray.push.apply(newArray, array2); return newArray; } this.extendArray = extendArray; this.cloneArray = cloneArray; function arrayInsert(array, index, other) { for (var i = 0; i < other.length; ++i) array.splice(i+index, 0, other[i]); return array; } // ************************************************************************************************ this.createStyleSheet = function(doc, url) { //TODO: xxxpedro //var style = doc.createElementNS("http://www.w3.org/1999/xhtml", "style"); var style = this.createElement("link"); style.setAttribute("charset","utf-8"); style.firebugIgnore = true; style.setAttribute("rel", "stylesheet"); style.setAttribute("type", "text/css"); style.setAttribute("href", url); //TODO: xxxpedro //style.innerHTML = this.getResource(url); return style; }; this.addStyleSheet = function(doc, style) { var heads = doc.getElementsByTagName("head"); if (heads.length) heads[0].appendChild(style); else doc.documentElement.appendChild(style); }; this.appendStylesheet = function(doc, uri) { // Make sure the stylesheet is not appended twice. if (this.$(uri, doc)) return; var styleSheet = this.createStyleSheet(doc, uri); styleSheet.setAttribute("id", uri); this.addStyleSheet(doc, styleSheet); }; this.addScript = function(doc, id, src) { var element = doc.createElementNS("http://www.w3.org/1999/xhtml", "html:script"); element.setAttribute("type", "text/javascript"); element.setAttribute("id", id); if (!FBTrace.DBG_CONSOLE) FBL.unwrapObject(element).firebugIgnore = true; element.innerHTML = src; if (doc.documentElement) doc.documentElement.appendChild(element); else { // See issue 1079, the svg test case gives this error if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.addScript doc has no documentElement:", doc); } return element; }; // ************************************************************************************************ this.getStyle = this.isIE ? function(el, name) { return el.currentStyle[name] || el.style[name] || undefined; } : function(el, name) { return el.ownerDocument.defaultView.getComputedStyle(el,null)[name] || el.style[name] || undefined; }; // ************************************************************************************************ // Whitespace and Entity conversions var entityConversionLists = this.entityConversionLists = { normal : { whitespace : { '\t' : '\u200c\u2192', '\n' : '\u200c\u00b6', '\r' : '\u200c\u00ac', ' ' : '\u200c\u00b7' } }, reverse : { whitespace : { '&Tab;' : '\t', '&NewLine;' : '\n', '\u200c\u2192' : '\t', '\u200c\u00b6' : '\n', '\u200c\u00ac' : '\r', '\u200c\u00b7' : ' ' } } }; var normal = entityConversionLists.normal, reverse = entityConversionLists.reverse; function addEntityMapToList(ccode, entity) { var lists = Array.prototype.slice.call(arguments, 2), len = lists.length, ch = String.fromCharCode(ccode); for (var i = 0; i < len; i++) { var list = lists[i]; normal[list]=normal[list] || {}; normal[list][ch] = '&' + entity + ';'; reverse[list]=reverse[list] || {}; reverse[list]['&' + entity + ';'] = ch; } }; var e = addEntityMapToList, white = 'whitespace', text = 'text', attr = 'attributes', css = 'css', editor = 'editor'; e(0x0022, 'quot', attr, css); e(0x0026, 'amp', attr, text, css); e(0x0027, 'apos', css); e(0x003c, 'lt', attr, text, css); e(0x003e, 'gt', attr, text, css); e(0xa9, 'copy', text, editor); e(0xae, 'reg', text, editor); e(0x2122, 'trade', text, editor); // See http://en.wikipedia.org/wiki/Dash e(0x2012, '#8210', attr, text, editor); // figure dash e(0x2013, 'ndash', attr, text, editor); // en dash e(0x2014, 'mdash', attr, text, editor); // em dash e(0x2015, '#8213', attr, text, editor); // horizontal bar e(0x00a0, 'nbsp', attr, text, white, editor); e(0x2002, 'ensp', attr, text, white, editor); e(0x2003, 'emsp', attr, text, white, editor); e(0x2009, 'thinsp', attr, text, white, editor); e(0x200c, 'zwnj', attr, text, white, editor); e(0x200d, 'zwj', attr, text, white, editor); e(0x200e, 'lrm', attr, text, white, editor); e(0x200f, 'rlm', attr, text, white, editor); e(0x200b, '#8203', attr, text, white, editor); // zero-width space (ZWSP) //************************************************************************************************ // Entity escaping var entityConversionRegexes = { normal : {}, reverse : {} }; var escapeEntitiesRegEx = { normal : function(list) { var chars = []; for ( var ch in list) { chars.push(ch); } return new RegExp('([' + chars.join('') + '])', 'gm'); }, reverse : function(list) { var chars = []; for ( var ch in list) { chars.push(ch); } return new RegExp('(' + chars.join('|') + ')', 'gm'); } }; function getEscapeRegexp(direction, lists) { var name = '', re; var groups = [].concat(lists); for (i = 0; i < groups.length; i++) { name += groups[i].group; } re = entityConversionRegexes[direction][name]; if (!re) { var list = {}; if (groups.length > 1) { for ( var i = 0; i < groups.length; i++) { var aList = entityConversionLists[direction][groups[i].group]; for ( var item in aList) list[item] = aList[item]; } } else if (groups.length==1) { list = entityConversionLists[direction][groups[0].group]; // faster for special case } else { list = {}; // perhaps should print out an error here? } re = entityConversionRegexes[direction][name] = escapeEntitiesRegEx[direction](list); } return re; }; function createSimpleEscape(name, direction) { return function(value) { var list = entityConversionLists[direction][name]; return String(value).replace( getEscapeRegexp(direction, { group : name, list : list }), function(ch) { return list[ch]; } ); }; }; function escapeGroupsForEntities(str, lists) { lists = [].concat(lists); var re = getEscapeRegexp('normal', lists), split = String(str).split(re), len = split.length, results = [], cur, r, i, ri = 0, l, list, last = ''; if (!len) return [ { str : String(str), group : '', name : '' } ]; for (i = 0; i < len; i++) { cur = split[i]; if (cur == '') continue; for (l = 0; l < lists.length; l++) { list = lists[l]; r = entityConversionLists.normal[list.group][cur]; // if (cur == ' ' && list.group == 'whitespace' && last == ' ') // only show for runs of more than one space // r = ' '; if (r) { results[ri] = { 'str' : r, 'class' : list['class'], 'extra' : list.extra[cur] ? list['class'] + list.extra[cur] : '' }; break; } } // last=cur; if (!r) results[ri] = { 'str' : cur, 'class' : '', 'extra' : '' }; ri++; } return results; }; this.escapeGroupsForEntities = escapeGroupsForEntities; function unescapeEntities(str, lists) { var re = getEscapeRegexp('reverse', lists), split = String(str).split(re), len = split.length, results = [], cur, r, i, ri = 0, l, list; if (!len) return str; lists = [].concat(lists); for (i = 0; i < len; i++) { cur = split[i]; if (cur == '') continue; for (l = 0; l < lists.length; l++) { list = lists[l]; r = entityConversionLists.reverse[list.group][cur]; if (r) { results[ri] = r; break; } } if (!r) results[ri] = cur; ri++; } return results.join('') || ''; }; // ************************************************************************************************ // String escaping var escapeForTextNode = this.escapeForTextNode = createSimpleEscape('text', 'normal'); var escapeForHtmlEditor = this.escapeForHtmlEditor = createSimpleEscape('editor', 'normal'); var escapeForElementAttribute = this.escapeForElementAttribute = createSimpleEscape('attributes', 'normal'); var escapeForCss = this.escapeForCss = createSimpleEscape('css', 'normal'); // deprecated compatibility functions //this.deprecateEscapeHTML = createSimpleEscape('text', 'normal'); //this.deprecatedUnescapeHTML = createSimpleEscape('text', 'reverse'); //this.escapeHTML = deprecated("use appropriate escapeFor... function", this.deprecateEscapeHTML); //this.unescapeHTML = deprecated("use appropriate unescapeFor... function", this.deprecatedUnescapeHTML); var escapeForSourceLine = this.escapeForSourceLine = createSimpleEscape('text', 'normal'); var unescapeWhitespace = createSimpleEscape('whitespace', 'reverse'); this.unescapeForTextNode = function(str) { if (Firebug.showTextNodesWithWhitespace) str = unescapeWhitespace(str); if (!Firebug.showTextNodesWithEntities) str = escapeForElementAttribute(str); return str; }; this.escapeNewLines = function(value) { return value.replace(/\r/g, "\\r").replace(/\n/g, "\\n"); }; this.stripNewLines = function(value) { return typeof(value) == "string" ? value.replace(/[\r\n]/g, " ") : value; }; this.escapeJS = function(value) { return value.replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace('"', '\\"', "g"); }; function escapeHTMLAttribute(value) { function replaceChars(ch) { switch (ch) { case "&": return "&amp;"; case "'": return apos; case '"': return quot; } return "?"; }; var apos = "&#39;", quot = "&quot;", around = '"'; if( value.indexOf('"') == -1 ) { quot = '"'; apos = "'"; } else if( value.indexOf("'") == -1 ) { quot = '"'; around = "'"; } return around + (String(value).replace(/[&'"]/g, replaceChars)) + around; } function escapeHTML(value) { function replaceChars(ch) { switch (ch) { case "<": return "&lt;"; case ">": return "&gt;"; case "&": return "&amp;"; case "'": return "&#39;"; case '"': return "&quot;"; } return "?"; }; return String(value).replace(/[<>&"']/g, replaceChars); } this.escapeHTML = escapeHTML; this.cropString = function(text, limit) { text = text + ""; if (!limit) var halfLimit = 50; else var halfLimit = limit / 2; if (text.length > limit) return this.escapeNewLines(text.substr(0, halfLimit) + "..." + text.substr(text.length-halfLimit)); else return this.escapeNewLines(text); }; this.isWhitespace = function(text) { return !reNotWhitespace.exec(text); }; this.splitLines = function(text) { var reSplitLines2 = /.*(:?\r\n|\n|\r)?/mg; var lines; if (text.match) { lines = text.match(reSplitLines2); } else { var str = text+""; lines = str.match(reSplitLines2); } lines.pop(); return lines; }; // ************************************************************************************************ this.safeToString = function(ob) { if (this.isIE) { try { // FIXME: xxxpedro this is failing in IE for the global "external" object return ob + ""; } catch(E) { FBTrace.sysout("Lib.safeToString() failed for ", ob); return ""; } } try { if (ob && "toString" in ob && typeof ob.toString == "function") return ob.toString(); } catch (exc) { // xxxpedro it is not safe to use ob+""? return ob + ""; ///return "[an object with no toString() function]"; } }; // ************************************************************************************************ this.hasProperties = function(ob) { try { for (var name in ob) return true; } catch (exc) {} return false; }; // ************************************************************************************************ // String Util var reTrim = /^\s+|\s+$/g; this.trim = function(s) { return s.replace(reTrim, ""); }; // ************************************************************************************************ // Empty this.emptyFn = function(){}; // ************************************************************************************************ // Visibility this.isVisible = function(elt) { /* if (elt instanceof XULElement) { //FBTrace.sysout("isVisible elt.offsetWidth: "+elt.offsetWidth+" offsetHeight:"+ elt.offsetHeight+" localName:"+ elt.localName+" nameSpace:"+elt.nameSpaceURI+"\n"); return (!elt.hidden && !elt.collapsed); } /**/ return this.getStyle(elt, "visibility") != "hidden" && ( elt.offsetWidth > 0 || elt.offsetHeight > 0 || elt.tagName in invisibleTags || elt.namespaceURI == "http://www.w3.org/2000/svg" || elt.namespaceURI == "http://www.w3.org/1998/Math/MathML" ); }; this.collapse = function(elt, collapsed) { // IE6 doesn't support the [collapsed] CSS selector. IE7 does support the selector, // but it is causing a bug (the element disappears when you set the "collapsed" // attribute, but it doesn't appear when you remove the attribute. So, for those // cases, we need to use the class attribute. if (this.isIElt8) { if (collapsed) this.setClass(elt, "collapsed"); else this.removeClass(elt, "collapsed"); } else elt.setAttribute("collapsed", collapsed ? "true" : "false"); }; this.obscure = function(elt, obscured) { if (obscured) this.setClass(elt, "obscured"); else this.removeClass(elt, "obscured"); }; this.hide = function(elt, hidden) { elt.style.visibility = hidden ? "hidden" : "visible"; }; this.clearNode = function(node) { var nodeName = " " + node.nodeName.toLowerCase() + " "; var ignoreTags = " table tbody thead tfoot th tr td "; // IE can't use innerHTML of table elements if (this.isIE && ignoreTags.indexOf(nodeName) != -1) this.eraseNode(node); else node.innerHTML = ""; }; this.eraseNode = function(node) { while (node.lastChild) node.removeChild(node.lastChild); }; // ************************************************************************************************ // Window iteration this.iterateWindows = function(win, handler) { if (!win || !win.document) return; handler(win); if (win == top || !win.frames) return; // XXXjjb hack for chromeBug for (var i = 0; i < win.frames.length; ++i) { var subWin = win.frames[i]; if (subWin != win) this.iterateWindows(subWin, handler); } }; this.getRootWindow = function(win) { for (; win; win = win.parent) { if (!win.parent || win == win.parent || !this.instanceOf(win.parent, "Window")) return win; } return null; }; // ************************************************************************************************ // Graphics this.getClientOffset = function(elt) { var addOffset = function addOffset(elt, coords, view) { var p = elt.offsetParent; ///var style = isIE ? elt.currentStyle : view.getComputedStyle(elt, ""); var chrome = Firebug.chrome; if (elt.offsetLeft) ///coords.x += elt.offsetLeft + parseInt(style.borderLeftWidth); coords.x += elt.offsetLeft + chrome.getMeasurementInPixels(elt, "borderLeft"); if (elt.offsetTop) ///coords.y += elt.offsetTop + parseInt(style.borderTopWidth); coords.y += elt.offsetTop + chrome.getMeasurementInPixels(elt, "borderTop"); if (p) { if (p.nodeType == 1) addOffset(p, coords, view); } else { var otherView = isIE ? elt.ownerDocument.parentWindow : elt.ownerDocument.defaultView; // IE will fail when reading the frameElement property of a popup window. // We don't need it anyway once it is outside the (popup) viewport, so we're // ignoring the frameElement check when the window is a popup if (!otherView.opener && otherView.frameElement) addOffset(otherView.frameElement, coords, otherView); } }; var isIE = this.isIE; var coords = {x: 0, y: 0}; if (elt) { var view = isIE ? elt.ownerDocument.parentWindow : elt.ownerDocument.defaultView; addOffset(elt, coords, view); } return coords; }; this.getViewOffset = function(elt, singleFrame) { function addOffset(elt, coords, view) { var p = elt.offsetParent; coords.x += elt.offsetLeft - (p ? p.scrollLeft : 0); coords.y += elt.offsetTop - (p ? p.scrollTop : 0); if (p) { if (p.nodeType == 1) { var parentStyle = view.getComputedStyle(p, ""); if (parentStyle.position != "static") { coords.x += parseInt(parentStyle.borderLeftWidth); coords.y += parseInt(parentStyle.borderTopWidth); if (p.localName == "TABLE") { coords.x += parseInt(parentStyle.paddingLeft); coords.y += parseInt(parentStyle.paddingTop); } else if (p.localName == "BODY") { var style = view.getComputedStyle(elt, ""); coords.x += parseInt(style.marginLeft); coords.y += parseInt(style.marginTop); } } else if (p.localName == "BODY") { coords.x += parseInt(parentStyle.borderLeftWidth); coords.y += parseInt(parentStyle.borderTopWidth); } var parent = elt.parentNode; while (p != parent) { coords.x -= parent.scrollLeft; coords.y -= parent.scrollTop; parent = parent.parentNode; } addOffset(p, coords, view); } } else { if (elt.localName == "BODY") { var style = view.getComputedStyle(elt, ""); coords.x += parseInt(style.borderLeftWidth); coords.y += parseInt(style.borderTopWidth); var htmlStyle = view.getComputedStyle(elt.parentNode, ""); coords.x -= parseInt(htmlStyle.paddingLeft); coords.y -= parseInt(htmlStyle.paddingTop); } if (elt.scrollLeft) coords.x += elt.scrollLeft; if (elt.scrollTop) coords.y += elt.scrollTop; var win = elt.ownerDocument.defaultView; if (win && (!singleFrame && win.frameElement)) addOffset(win.frameElement, coords, win); } } var coords = {x: 0, y: 0}; if (elt) addOffset(elt, coords, elt.ownerDocument.defaultView); return coords; }; this.getLTRBWH = function(elt) { var bcrect, dims = {"left": 0, "top": 0, "right": 0, "bottom": 0, "width": 0, "height": 0}; if (elt) { bcrect = elt.getBoundingClientRect(); dims.left = bcrect.left; dims.top = bcrect.top; dims.right = bcrect.right; dims.bottom = bcrect.bottom; if(bcrect.width) { dims.width = bcrect.width; dims.height = bcrect.height; } else { dims.width = dims.right - dims.left; dims.height = dims.bottom - dims.top; } } return dims; }; this.applyBodyOffsets = function(elt, clientRect) { var od = elt.ownerDocument; if (!od.body) return clientRect; var style = od.defaultView.getComputedStyle(od.body, null); var pos = style.getPropertyValue('position'); if(pos === 'absolute' || pos === 'relative') { var borderLeft = parseInt(style.getPropertyValue('border-left-width').replace('px', ''),10) || 0; var borderTop = parseInt(style.getPropertyValue('border-top-width').replace('px', ''),10) || 0; var paddingLeft = parseInt(style.getPropertyValue('padding-left').replace('px', ''),10) || 0; var paddingTop = parseInt(style.getPropertyValue('padding-top').replace('px', ''),10) || 0; var marginLeft = parseInt(style.getPropertyValue('margin-left').replace('px', ''),10) || 0; var marginTop = parseInt(style.getPropertyValue('margin-top').replace('px', ''),10) || 0; var offsetX = borderLeft + paddingLeft + marginLeft; var offsetY = borderTop + paddingTop + marginTop; clientRect.left -= offsetX; clientRect.top -= offsetY; clientRect.right -= offsetX; clientRect.bottom -= offsetY; } return clientRect; }; this.getOffsetSize = function(elt) { return {width: elt.offsetWidth, height: elt.offsetHeight}; }; this.getOverflowParent = function(element) { for (var scrollParent = element.parentNode; scrollParent; scrollParent = scrollParent.offsetParent) { if (scrollParent.scrollHeight > scrollParent.offsetHeight) return scrollParent; } }; this.isScrolledToBottom = function(element) { var onBottom = (element.scrollTop + element.offsetHeight) == element.scrollHeight; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("isScrolledToBottom offsetHeight: "+element.offsetHeight +" onBottom:"+onBottom); return onBottom; }; this.scrollToBottom = function(element) { element.scrollTop = element.scrollHeight; if (FBTrace.DBG_CONSOLE) { FBTrace.sysout("scrollToBottom reset scrollTop "+element.scrollTop+" = "+element.scrollHeight); if (element.scrollHeight == element.offsetHeight) FBTrace.sysout("scrollToBottom attempt to scroll non-scrollable element "+element, element); } return (element.scrollTop == element.scrollHeight); }; this.move = function(element, x, y) { element.style.left = x + "px"; element.style.top = y + "px"; }; this.resize = function(element, w, h) { element.style.width = w + "px"; element.style.height = h + "px"; }; this.linesIntoCenterView = function(element, scrollBox) // {before: int, after: int} { if (!scrollBox) scrollBox = this.getOverflowParent(element); if (!scrollBox) return; var offset = this.getClientOffset(element); var topSpace = offset.y - scrollBox.scrollTop; var bottomSpace = (scrollBox.scrollTop + scrollBox.clientHeight) - (offset.y + element.offsetHeight); if (topSpace < 0 || bottomSpace < 0) { var split = (scrollBox.clientHeight/2); var centerY = offset.y - split; scrollBox.scrollTop = centerY; topSpace = split; bottomSpace = split - element.offsetHeight; } return {before: Math.round((topSpace/element.offsetHeight) + 0.5), after: Math.round((bottomSpace/element.offsetHeight) + 0.5) }; }; this.scrollIntoCenterView = function(element, scrollBox, notX, notY) { if (!element) return; if (!scrollBox) scrollBox = this.getOverflowParent(element); if (!scrollBox) return; var offset = this.getClientOffset(element); if (!notY) { var topSpace = offset.y - scrollBox.scrollTop; var bottomSpace = (scrollBox.scrollTop + scrollBox.clientHeight) - (offset.y + element.offsetHeight); if (topSpace < 0 || bottomSpace < 0) { var centerY = offset.y - (scrollBox.clientHeight/2); scrollBox.scrollTop = centerY; } } if (!notX) { var leftSpace = offset.x - scrollBox.scrollLeft; var rightSpace = (scrollBox.scrollLeft + scrollBox.clientWidth) - (offset.x + element.clientWidth); if (leftSpace < 0 || rightSpace < 0) { var centerX = offset.x - (scrollBox.clientWidth/2); scrollBox.scrollLeft = centerX; } } if (FBTrace.DBG_SOURCEFILES) FBTrace.sysout("lib.scrollIntoCenterView ","Element:"+element.innerHTML); }; // ************************************************************************************************ // CSS var cssKeywordMap = null; var cssPropNames = null; var cssColorNames = null; var imageRules = null; this.getCSSKeywordsByProperty = function(propName) { if (!cssKeywordMap) { cssKeywordMap = {}; for (var name in this.cssInfo) { var list = []; var types = this.cssInfo[name]; for (var i = 0; i < types.length; ++i) { var keywords = this.cssKeywords[types[i]]; if (keywords) list.push.apply(list, keywords); } cssKeywordMap[name] = list; } } return propName in cssKeywordMap ? cssKeywordMap[propName] : []; }; this.getCSSPropertyNames = function() { if (!cssPropNames) { cssPropNames = []; for (var name in this.cssInfo) cssPropNames.push(name); } return cssPropNames; }; this.isColorKeyword = function(keyword) { if (keyword == "transparent") return false; if (!cssColorNames) { cssColorNames = []; var colors = this.cssKeywords["color"]; for (var i = 0; i < colors.length; ++i) cssColorNames.push(colors[i].toLowerCase()); var systemColors = this.cssKeywords["systemColor"]; for (var i = 0; i < systemColors.length; ++i) cssColorNames.push(systemColors[i].toLowerCase()); } return cssColorNames.indexOf ? // Array.indexOf is not available in IE cssColorNames.indexOf(keyword.toLowerCase()) != -1 : (" " + cssColorNames.join(" ") + " ").indexOf(" " + keyword.toLowerCase() + " ") != -1; }; this.isImageRule = function(rule) { if (!imageRules) { imageRules = []; for (var i in this.cssInfo) { var r = i.toLowerCase(); var suffix = "image"; if (r.match(suffix + "$") == suffix || r == "background") imageRules.push(r); } } return imageRules.indexOf ? // Array.indexOf is not available in IE imageRules.indexOf(rule.toLowerCase()) != -1 : (" " + imageRules.join(" ") + " ").indexOf(" " + rule.toLowerCase() + " ") != -1; }; this.copyTextStyles = function(fromNode, toNode, style) { var view = this.isIE ? fromNode.ownerDocument.parentWindow : fromNode.ownerDocument.defaultView; if (view) { if (!style) style = this.isIE ? fromNode.currentStyle : view.getComputedStyle(fromNode, ""); toNode.style.fontFamily = style.fontFamily; // TODO: xxxpedro need to create a FBL.getComputedStyle() because IE // returns wrong computed styles for inherited properties (like font-*) // // Also would be good to create a FBL.getStyle() toNode.style.fontSize = style.fontSize; toNode.style.fontWeight = style.fontWeight; toNode.style.fontStyle = style.fontStyle; return style; } }; this.copyBoxStyles = function(fromNode, toNode, style) { var view = this.isIE ? fromNode.ownerDocument.parentWindow : fromNode.ownerDocument.defaultView; if (view) { if (!style) style = this.isIE ? fromNode.currentStyle : view.getComputedStyle(fromNode, ""); toNode.style.marginTop = style.marginTop; toNode.style.marginRight = style.marginRight; toNode.style.marginBottom = style.marginBottom; toNode.style.marginLeft = style.marginLeft; toNode.style.borderTopWidth = style.borderTopWidth; toNode.style.borderRightWidth = style.borderRightWidth; toNode.style.borderBottomWidth = style.borderBottomWidth; toNode.style.borderLeftWidth = style.borderLeftWidth; return style; } }; this.readBoxStyles = function(style) { var styleNames = { "margin-top": "marginTop", "margin-right": "marginRight", "margin-left": "marginLeft", "margin-bottom": "marginBottom", "border-top-width": "borderTop", "border-right-width": "borderRight", "border-left-width": "borderLeft", "border-bottom-width": "borderBottom", "padding-top": "paddingTop", "padding-right": "paddingRight", "padding-left": "paddingLeft", "padding-bottom": "paddingBottom", "z-index": "zIndex" }; var styles = {}; for (var styleName in styleNames) styles[styleNames[styleName]] = parseInt(style.getPropertyCSSValue(styleName).cssText) || 0; if (FBTrace.DBG_INSPECT) FBTrace.sysout("readBoxStyles ", styles); return styles; }; this.getBoxFromStyles = function(style, element) { var args = this.readBoxStyles(style); args.width = element.offsetWidth - (args.paddingLeft+args.paddingRight+args.borderLeft+args.borderRight); args.height = element.offsetHeight - (args.paddingTop+args.paddingBottom+args.borderTop+args.borderBottom); return args; }; this.getElementCSSSelector = function(element) { var label = element.localName.toLowerCase(); if (element.id) label += "#" + element.id; if (element.hasAttribute("class")) label += "." + element.getAttribute("class").split(" ")[0]; return label; }; this.getURLForStyleSheet= function(styleSheet) { //http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-StyleSheet. For inline style sheets, the value of this attribute is null. return (styleSheet.href ? styleSheet.href : styleSheet.ownerNode.ownerDocument.URL); }; this.getDocumentForStyleSheet = function(styleSheet) { while (styleSheet.parentStyleSheet && !styleSheet.ownerNode) { styleSheet = styleSheet.parentStyleSheet; } if (styleSheet.ownerNode) return styleSheet.ownerNode.ownerDocument; }; /** * Retrieves the instance number for a given style sheet. The instance number * is sheet's index within the set of all other sheets whose URL is the same. */ this.getInstanceForStyleSheet = function(styleSheet, ownerDocument) { // System URLs are always unique (or at least we are making this assumption) if (FBL.isSystemStyleSheet(styleSheet)) return 0; // ownerDocument is an optional hint for performance if (FBTrace.DBG_CSS) FBTrace.sysout("getInstanceForStyleSheet: " + styleSheet.href + " " + styleSheet.media.mediaText + " " + (styleSheet.ownerNode && FBL.getElementXPath(styleSheet.ownerNode)), ownerDocument); ownerDocument = ownerDocument || FBL.getDocumentForStyleSheet(styleSheet); var ret = 0, styleSheets = ownerDocument.styleSheets, href = styleSheet.href; for (var i = 0; i < styleSheets.length; i++) { var curSheet = styleSheets[i]; if (FBTrace.DBG_CSS) FBTrace.sysout("getInstanceForStyleSheet: compare href " + i + " " + curSheet.href + " " + curSheet.media.mediaText + " " + (curSheet.ownerNode && FBL.getElementXPath(curSheet.ownerNode))); if (curSheet == styleSheet) break; if (curSheet.href == href) ret++; } return ret; }; // ************************************************************************************************ // HTML and XML Serialization var getElementType = this.getElementType = function(node) { if (isElementXUL(node)) return 'xul'; else if (isElementSVG(node)) return 'svg'; else if (isElementMathML(node)) return 'mathml'; else if (isElementXHTML(node)) return 'xhtml'; else if (isElementHTML(node)) return 'html'; }; var getElementSimpleType = this.getElementSimpleType = function(node) { if (isElementSVG(node)) return 'svg'; else if (isElementMathML(node)) return 'mathml'; else return 'html'; }; var isElementHTML = this.isElementHTML = function(node) { return node.nodeName == node.nodeName.toUpperCase(); }; var isElementXHTML = this.isElementXHTML = function(node) { return node.nodeName == node.nodeName.toLowerCase(); }; var isElementMathML = this.isElementMathML = function(node) { return node.namespaceURI == 'http://www.w3.org/1998/Math/MathML'; }; var isElementSVG = this.isElementSVG = function(node) { return node.namespaceURI == 'http://www.w3.org/2000/svg'; }; var isElementXUL = this.isElementXUL = function(node) { return node instanceof XULElement; }; this.isSelfClosing = function(element) { if (isElementSVG(element) || isElementMathML(element)) return true; var tag = element.localName.toLowerCase(); return (this.selfClosingTags.hasOwnProperty(tag)); }; this.getElementHTML = function(element) { var self=this; function toHTML(elt) { if (elt.nodeType == Node.ELEMENT_NODE) { if (unwrapObject(elt).firebugIgnore) return; html.push('<', elt.nodeName.toLowerCase()); for (var i = 0; i < elt.attributes.length; ++i) { var attr = elt.attributes[i]; // Hide attributes set by Firebug if (attr.localName.indexOf("firebug-") == 0) continue; // MathML if (attr.localName.indexOf("-moz-math") == 0) { // just hide for now continue; } html.push(' ', attr.nodeName, '="', escapeForElementAttribute(attr.nodeValue),'"'); } if (elt.firstChild) { html.push('>'); var pureText=true; for (var child = element.firstChild; child; child = child.nextSibling) pureText=pureText && (child.nodeType == Node.TEXT_NODE); if (pureText) html.push(escapeForHtmlEditor(elt.textContent)); else { for (var child = elt.firstChild; child; child = child.nextSibling) toHTML(child); } html.push('</', elt.nodeName.toLowerCase(), '>'); } else if (isElementSVG(elt) || isElementMathML(elt)) { html.push('/>'); } else if (self.isSelfClosing(elt)) { html.push((isElementXHTML(elt))?'/>':'>'); } else { html.push('></', elt.nodeName.toLowerCase(), '>'); } } else if (elt.nodeType == Node.TEXT_NODE) html.push(escapeForTextNode(elt.textContent)); else if (elt.nodeType == Node.CDATA_SECTION_NODE) html.push('<![CDATA[', elt.nodeValue, ']]>'); else if (elt.nodeType == Node.COMMENT_NODE) html.push('<!--', elt.nodeValue, '-->'); } var html = []; toHTML(element); return html.join(""); }; this.getElementXML = function(element) { function toXML(elt) { if (elt.nodeType == Node.ELEMENT_NODE) { if (unwrapObject(elt).firebugIgnore) return; xml.push('<', elt.nodeName.toLowerCase()); for (var i = 0; i < elt.attributes.length; ++i) { var attr = elt.attributes[i]; // Hide attributes set by Firebug if (attr.localName.indexOf("firebug-") == 0) continue; // MathML if (attr.localName.indexOf("-moz-math") == 0) { // just hide for now continue; } xml.push(' ', attr.nodeName, '="', escapeForElementAttribute(attr.nodeValue),'"'); } if (elt.firstChild) { xml.push('>'); for (var child = elt.firstChild; child; child = child.nextSibling) toXML(child); xml.push('</', elt.nodeName.toLowerCase(), '>'); } else xml.push('/>'); } else if (elt.nodeType == Node.TEXT_NODE) xml.push(elt.nodeValue); else if (elt.nodeType == Node.CDATA_SECTION_NODE) xml.push('<![CDATA[', elt.nodeValue, ']]>'); else if (elt.nodeType == Node.COMMENT_NODE) xml.push('<!--', elt.nodeValue, '-->'); } var xml = []; toXML(element); return xml.join(""); }; // ************************************************************************************************ // CSS classes this.hasClass = function(node, name) // className, className, ... { // TODO: xxxpedro when lib.hasClass is called with more than 2 arguments? // this function can be optimized a lot if assumed 2 arguments only, // which seems to be what happens 99% of the time if (arguments.length == 2) return (' '+node.className+' ').indexOf(' '+name+' ') != -1; if (!node || node.nodeType != 1) return false; else { for (var i=1; i<arguments.length; ++i) { var name = arguments[i]; var re = new RegExp("(^|\\s)"+name+"($|\\s)"); if (!re.exec(node.className)) return false; } return true; } }; this.old_hasClass = function(node, name) // className, className, ... { if (!node || node.nodeType != 1) return false; else { for (var i=1; i<arguments.length; ++i) { var name = arguments[i]; var re = new RegExp("(^|\\s)"+name+"($|\\s)"); if (!re.exec(node.className)) return false; } return true; } }; this.setClass = function(node, name) { if (node && (' '+node.className+' ').indexOf(' '+name+' ') == -1) ///if (node && !this.hasClass(node, name)) node.className += " " + name; }; this.getClassValue = function(node, name) { var re = new RegExp(name+"-([^ ]+)"); var m = re.exec(node.className); return m ? m[1] : ""; }; this.removeClass = function(node, name) { if (node && node.className) { var index = node.className.indexOf(name); if (index >= 0) { var size = name.length; node.className = node.className.substr(0,index-1) + node.className.substr(index+size); } } }; this.toggleClass = function(elt, name) { if ((' '+elt.className+' ').indexOf(' '+name+' ') != -1) ///if (this.hasClass(elt, name)) this.removeClass(elt, name); else this.setClass(elt, name); }; this.setClassTimed = function(elt, name, context, timeout) { if (!timeout) timeout = 1300; if (elt.__setClassTimeout) context.clearTimeout(elt.__setClassTimeout); else this.setClass(elt, name); elt.__setClassTimeout = context.setTimeout(function() { delete elt.__setClassTimeout; FBL.removeClass(elt, name); }, timeout); }; this.cancelClassTimed = function(elt, name, context) { if (elt.__setClassTimeout) { FBL.removeClass(elt, name); context.clearTimeout(elt.__setClassTimeout); delete elt.__setClassTimeout; } }; // ************************************************************************************************ // DOM queries this.$ = function(id, doc) { if (doc) return doc.getElementById(id); else { return FBL.Firebug.chrome.document.getElementById(id); } }; this.$$ = function(selector, doc) { if (doc || !FBL.Firebug.chrome) return FBL.Firebug.Selector(selector, doc); else { return FBL.Firebug.Selector(selector, FBL.Firebug.chrome.document); } }; this.getChildByClass = function(node) // ,classname, classname, classname... { for (var i = 1; i < arguments.length; ++i) { var className = arguments[i]; var child = node.firstChild; node = null; for (; child; child = child.nextSibling) { if (this.hasClass(child, className)) { node = child; break; } } } return node; }; this.getAncestorByClass = function(node, className) { for (var parent = node; parent; parent = parent.parentNode) { if (this.hasClass(parent, className)) return parent; } return null; }; this.getElementsByClass = function(node, className) { var result = []; for (var child = node.firstChild; child; child = child.nextSibling) { if (this.hasClass(child, className)) result.push(child); } return result; }; this.getElementByClass = function(node, className) // className, className, ... { var args = cloneArray(arguments); args.splice(0, 1); for (var child = node.firstChild; child; child = child.nextSibling) { var args1 = cloneArray(args); args1.unshift(child); if (FBL.hasClass.apply(null, args1)) return child; else { var found = FBL.getElementByClass.apply(null, args1); if (found) return found; } } return null; }; this.isAncestor = function(node, potentialAncestor) { for (var parent = node; parent; parent = parent.parentNode) { if (parent == potentialAncestor) return true; } return false; }; this.getNextElement = function(node) { while (node && node.nodeType != 1) node = node.nextSibling; return node; }; this.getPreviousElement = function(node) { while (node && node.nodeType != 1) node = node.previousSibling; return node; }; this.getBody = function(doc) { if (doc.body) return doc.body; var body = doc.getElementsByTagName("body")[0]; if (body) return body; return doc.firstChild; // For non-HTML docs }; this.findNextDown = function(node, criteria) { if (!node) return null; for (var child = node.firstChild; child; child = child.nextSibling) { if (criteria(child)) return child; var next = this.findNextDown(child, criteria); if (next) return next; } }; this.findPreviousUp = function(node, criteria) { if (!node) return null; for (var child = node.lastChild; child; child = child.previousSibling) { var next = this.findPreviousUp(child, criteria); if (next) return next; if (criteria(child)) return child; } }; this.findNext = function(node, criteria, upOnly, maxRoot) { if (!node) return null; if (!upOnly) { var next = this.findNextDown(node, criteria); if (next) return next; } for (var sib = node.nextSibling; sib; sib = sib.nextSibling) { if (criteria(sib)) return sib; var next = this.findNextDown(sib, criteria); if (next) return next; } if (node.parentNode && node.parentNode != maxRoot) return this.findNext(node.parentNode, criteria, true); }; this.findPrevious = function(node, criteria, downOnly, maxRoot) { if (!node) return null; for (var sib = node.previousSibling; sib; sib = sib.previousSibling) { var prev = this.findPreviousUp(sib, criteria); if (prev) return prev; if (criteria(sib)) return sib; } if (!downOnly) { var next = this.findPreviousUp(node, criteria); if (next) return next; } if (node.parentNode && node.parentNode != maxRoot) { if (criteria(node.parentNode)) return node.parentNode; return this.findPrevious(node.parentNode, criteria, true); } }; this.getNextByClass = function(root, state) { var iter = function iter(node) { return node.nodeType == 1 && FBL.hasClass(node, state); }; return this.findNext(root, iter); }; this.getPreviousByClass = function(root, state) { var iter = function iter(node) { return node.nodeType == 1 && FBL.hasClass(node, state); }; return this.findPrevious(root, iter); }; this.isElement = function(o) { try { return o && this.instanceOf(o, "Element"); } catch (ex) { return false; } }; // ************************************************************************************************ // DOM Modification // TODO: xxxpedro use doc fragments in Context API var appendFragment = null; this.appendInnerHTML = function(element, html, referenceElement) { // if undefined, we must convert it to null otherwise it will throw an error in IE // when executing element.insertBefore(firstChild, referenceElement) referenceElement = referenceElement || null; var doc = element.ownerDocument; // doc.createRange not available in IE if (doc.createRange) { var range = doc.createRange(); // a helper object range.selectNodeContents(element); // the environment to interpret the html var fragment = range.createContextualFragment(html); // parse var firstChild = fragment.firstChild; element.insertBefore(fragment, referenceElement); } else { if (!appendFragment || appendFragment.ownerDocument != doc) appendFragment = doc.createDocumentFragment(); var div = doc.createElement("div"); div.innerHTML = html; var firstChild = div.firstChild; while (div.firstChild) appendFragment.appendChild(div.firstChild); element.insertBefore(appendFragment, referenceElement); div = null; } return firstChild; }; // ************************************************************************************************ // DOM creation this.createElement = function(tagName, properties) { properties = properties || {}; var doc = properties.document || FBL.Firebug.chrome.document; var element = doc.createElement(tagName); for(var name in properties) { if (name != "document") { element[name] = properties[name]; } } return element; }; this.createGlobalElement = function(tagName, properties) { properties = properties || {}; var doc = FBL.Env.browser.document; var element = this.NS && doc.createElementNS ? doc.createElementNS(FBL.NS, tagName) : doc.createElement(tagName); for(var name in properties) { var propname = name; if (FBL.isIE && name == "class") propname = "className"; if (name != "document") { element.setAttribute(propname, properties[name]); } } return element; }; //************************************************************************************************ this.safeGetWindowLocation = function(window) { try { if (window) { if (window.closed) return "(window.closed)"; if ("location" in window) return window.location+""; else return "(no window.location)"; } else return "(no context.window)"; } catch(exc) { if (FBTrace.DBG_WINDOWS || FBTrace.DBG_ERRORS) FBTrace.sysout("TabContext.getWindowLocation failed "+exc, exc); FBTrace.sysout("TabContext.getWindowLocation failed window:", window); return "(getWindowLocation: "+exc+")"; } }; // ************************************************************************************************ // Events this.isLeftClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 1 : // IE "click" and "dblclick" button model event.button == 0) && // others this.noKeyModifiers(event); }; this.isMiddleClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 4 : // IE "click" and "dblclick" button model event.button == 1) && this.noKeyModifiers(event); }; this.isRightClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 2 : // IE "click" and "dblclick" button model event.button == 2) && this.noKeyModifiers(event); }; this.noKeyModifiers = function(event) { return !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey; }; this.isControlClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 1 : // IE "click" and "dblclick" button model event.button == 0) && this.isControl(event); }; this.isShiftClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 1 : // IE "click" and "dblclick" button model event.button == 0) && this.isShift(event); }; this.isControl = function(event) { return (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey; }; this.isAlt = function(event) { return event.altKey && !event.ctrlKey && !event.shiftKey && !event.metaKey; }; this.isAltClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 1 : // IE "click" and "dblclick" button model event.button == 0) && this.isAlt(event); }; this.isControlShift = function(event) { return (event.metaKey || event.ctrlKey) && event.shiftKey && !event.altKey; }; this.isShift = function(event) { return event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey; }; this.addEvent = function(object, name, handler, useCapture) { if (object.addEventListener) object.addEventListener(name, handler, useCapture); else object.attachEvent("on"+name, handler); }; this.removeEvent = function(object, name, handler, useCapture) { try { if (object.removeEventListener) object.removeEventListener(name, handler, useCapture); else object.detachEvent("on"+name, handler); } catch(e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("FBL.removeEvent error: ", object, name); } }; this.cancelEvent = function(e, preventDefault) { if (!e) return; if (preventDefault) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.addGlobalEvent = function(name, handler) { var doc = this.Firebug.browser.document; var frames = this.Firebug.browser.window.frames; this.addEvent(doc, name, handler); if (this.Firebug.chrome.type == "popup") this.addEvent(this.Firebug.chrome.document, name, handler); for (var i = 0, frame; frame = frames[i]; i++) { try { this.addEvent(frame.document, name, handler); } catch(E) { // Avoid acess denied } } }; this.removeGlobalEvent = function(name, handler) { var doc = this.Firebug.browser.document; var frames = this.Firebug.browser.window.frames; this.removeEvent(doc, name, handler); if (this.Firebug.chrome.type == "popup") this.removeEvent(this.Firebug.chrome.document, name, handler); for (var i = 0, frame; frame = frames[i]; i++) { try { this.removeEvent(frame.document, name, handler); } catch(E) { // Avoid acess denied } } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.dispatch = function(listeners, name, args) { if (!listeners) return; try {/**/ if (typeof listeners.length != "undefined") { if (FBTrace.DBG_DISPATCH) FBTrace.sysout("FBL.dispatch", name+" to "+listeners.length+" listeners"); for (var i = 0; i < listeners.length; ++i) { var listener = listeners[i]; if ( listener[name] ) listener[name].apply(listener, args); } } else { if (FBTrace.DBG_DISPATCH) FBTrace.sysout("FBL.dispatch", name+" to listeners of an object"); for (var prop in listeners) { var listener = listeners[prop]; if ( listener[name] ) listener[name].apply(listener, args); } } } catch (exc) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout(" Exception in lib.dispatch "+ name, exc); //FBTrace.dumpProperties(" Exception in lib.dispatch listener", listener); } } /**/ }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var disableTextSelectionHandler = function(event) { FBL.cancelEvent(event, true); return false; }; this.disableTextSelection = function(e) { if (typeof e.onselectstart != "undefined") // IE this.addEvent(e, "selectstart", disableTextSelectionHandler); else // others { e.style.cssText = "user-select: none; -khtml-user-select: none; -moz-user-select: none;"; // canceling the event in FF will prevent the menu popups to close when clicking over // text-disabled elements if (!this.isFirefox) this.addEvent(e, "mousedown", disableTextSelectionHandler); } e.style.cursor = "default"; }; this.restoreTextSelection = function(e) { if (typeof e.onselectstart != "undefined") // IE this.removeEvent(e, "selectstart", disableTextSelectionHandler); else // others { e.style.cssText = "cursor: default;"; // canceling the event in FF will prevent the menu popups to close when clicking over // text-disabled elements if (!this.isFirefox) this.removeEvent(e, "mousedown", disableTextSelectionHandler); } }; // ************************************************************************************************ // DOM Events var eventTypes = { composition: [ "composition", "compositionstart", "compositionend" ], contextmenu: [ "contextmenu" ], drag: [ "dragenter", "dragover", "dragexit", "dragdrop", "draggesture" ], focus: [ "focus", "blur" ], form: [ "submit", "reset", "change", "select", "input" ], key: [ "keydown", "keyup", "keypress" ], load: [ "load", "beforeunload", "unload", "abort", "error" ], mouse: [ "mousedown", "mouseup", "click", "dblclick", "mouseover", "mouseout", "mousemove" ], mutation: [ "DOMSubtreeModified", "DOMNodeInserted", "DOMNodeRemoved", "DOMNodeRemovedFromDocument", "DOMNodeInsertedIntoDocument", "DOMAttrModified", "DOMCharacterDataModified" ], paint: [ "paint", "resize", "scroll" ], scroll: [ "overflow", "underflow", "overflowchanged" ], text: [ "text" ], ui: [ "DOMActivate", "DOMFocusIn", "DOMFocusOut" ], xul: [ "popupshowing", "popupshown", "popuphiding", "popuphidden", "close", "command", "broadcast", "commandupdate" ] }; this.getEventFamily = function(eventType) { if (!this.families) { this.families = {}; for (var family in eventTypes) { var types = eventTypes[family]; for (var i = 0; i < types.length; ++i) this.families[types[i]] = family; } } return this.families[eventType]; }; // ************************************************************************************************ // URLs this.getFileName = function(url) { var split = this.splitURLBase(url); return split.name; }; this.splitURLBase = function(url) { if (this.isDataURL(url)) return this.splitDataURL(url); return this.splitURLTrue(url); }; this.splitDataURL = function(url) { var mark = url.indexOf(':', 3); if (mark != 4) return false; // the first 5 chars must be 'data:' var point = url.indexOf(',', mark+1); if (point < mark) return false; // syntax error var props = { encodedContent: url.substr(point+1) }; var metadataBuffer = url.substr(mark+1, point); var metadata = metadataBuffer.split(';'); for (var i = 0; i < metadata.length; i++) { var nv = metadata[i].split('='); if (nv.length == 2) props[nv[0]] = nv[1]; } // Additional Firebug-specific properties if (props.hasOwnProperty('fileName')) { var caller_URL = decodeURIComponent(props['fileName']); var caller_split = this.splitURLTrue(caller_URL); if (props.hasOwnProperty('baseLineNumber')) // this means it's probably an eval() { props['path'] = caller_split.path; props['line'] = props['baseLineNumber']; var hint = decodeURIComponent(props['encodedContent'].substr(0,200)).replace(/\s*$/, ""); props['name'] = 'eval->'+hint; } else { props['name'] = caller_split.name; props['path'] = caller_split.path; } } else { if (!props.hasOwnProperty('path')) props['path'] = "data:"; if (!props.hasOwnProperty('name')) props['name'] = decodeURIComponent(props['encodedContent'].substr(0,200)).replace(/\s*$/, ""); } return props; }; this.splitURLTrue = function(url) { var m = reSplitFile.exec(url); if (!m) return {name: url, path: url}; else if (!m[2]) return {path: m[1], name: m[1]}; else return {path: m[1], name: m[2]+m[3]}; }; this.getFileExtension = function(url) { if (!url) return null; // Remove query string from the URL if any. var queryString = url.indexOf("?"); if (queryString != -1) url = url.substr(0, queryString); // Now get the file extension. var lastDot = url.lastIndexOf("."); return url.substr(lastDot+1); }; this.isSystemURL = function(url) { if (!url) return true; if (url.length == 0) return true; if (url[0] == 'h') return false; if (url.substr(0, 9) == "resource:") return true; else if (url.substr(0, 16) == "chrome://firebug") return true; else if (url == "XPCSafeJSObjectWrapper.cpp") return true; else if (url.substr(0, 6) == "about:") return true; else if (url.indexOf("firebug-service.js") != -1) return true; else return false; }; this.isSystemPage = function(win) { try { var doc = win.document; if (!doc) return false; // Detect pages for pretty printed XML if ((doc.styleSheets.length && doc.styleSheets[0].href == "chrome://global/content/xml/XMLPrettyPrint.css") || (doc.styleSheets.length > 1 && doc.styleSheets[1].href == "chrome://browser/skin/feeds/subscribe.css")) return true; return FBL.isSystemURL(win.location.href); } catch (exc) { // Sometimes documents just aren't ready to be manipulated here, but don't let that // gum up the works ERROR("tabWatcher.isSystemPage document not ready:"+ exc); return false; } }; this.isSystemStyleSheet = function(sheet) { var href = sheet && sheet.href; return href && FBL.isSystemURL(href); }; this.getURIHost = function(uri) { try { if (uri) return uri.host; else return ""; } catch (exc) { return ""; } }; this.isLocalURL = function(url) { if (url.substr(0, 5) == "file:") return true; else if (url.substr(0, 8) == "wyciwyg:") return true; else return false; }; this.isDataURL = function(url) { return (url && url.substr(0,5) == "data:"); }; this.getLocalPath = function(url) { if (this.isLocalURL(url)) { var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler); var file = fileHandler.getFileFromURLSpec(url); return file.path; } }; this.getURLFromLocalFile = function(file) { var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler); var URL = fileHandler.getURLSpecFromFile(file); return URL; }; this.getDataURLForContent = function(content, url) { // data:text/javascript;fileName=x%2Cy.js;baseLineNumber=10,<the-url-encoded-data> var uri = "data:text/html;"; uri += "fileName="+encodeURIComponent(url)+ ","; uri += encodeURIComponent(content); return uri; }, this.getDomain = function(url) { var m = /[^:]+:\/{1,3}([^\/]+)/.exec(url); return m ? m[1] : ""; }; this.getURLPath = function(url) { var m = /[^:]+:\/{1,3}[^\/]+(\/.*?)$/.exec(url); return m ? m[1] : ""; }; this.getPrettyDomain = function(url) { var m = /[^:]+:\/{1,3}(www\.)?([^\/]+)/.exec(url); return m ? m[2] : ""; }; this.absoluteURL = function(url, baseURL) { return this.absoluteURLWithDots(url, baseURL).replace("/./", "/", "g"); }; this.absoluteURLWithDots = function(url, baseURL) { if (url[0] == "?") return baseURL + url; var reURL = /(([^:]+:)\/{1,2}[^\/]*)(.*?)$/; var m = reURL.exec(url); if (m) return url; var m = reURL.exec(baseURL); if (!m) return ""; var head = m[1]; var tail = m[3]; if (url.substr(0, 2) == "//") return m[2] + url; else if (url[0] == "/") { return head + url; } else if (tail[tail.length-1] == "/") return baseURL + url; else { var parts = tail.split("/"); return head + parts.slice(0, parts.length-1).join("/") + "/" + url; } }; this.normalizeURL = function(url) // this gets called a lot, any performance improvement welcome { if (!url) return ""; // Replace one or more characters that are not forward-slash followed by /.., by space. if (url.length < 255) // guard against monsters. { // Replace one or more characters that are not forward-slash followed by /.., by space. url = url.replace(/[^\/]+\/\.\.\//, "", "g"); // Issue 1496, avoid # url = url.replace(/#.*/,""); // For some reason, JSDS reports file URLs like "file:/" instead of "file:///", so they // don't match up with the URLs we get back from the DOM url = url.replace(/file:\/([^\/])/g, "file:///$1"); if (url.indexOf('chrome:')==0) { var m = reChromeCase.exec(url); // 1 is package name, 2 is path if (m) { url = "chrome://"+m[1].toLowerCase()+"/"+m[2]; } } } return url; }; this.denormalizeURL = function(url) { return url.replace(/file:\/\/\//g, "file:/"); }; this.parseURLParams = function(url) { var q = url ? url.indexOf("?") : -1; if (q == -1) return []; var search = url.substr(q+1); var h = search.lastIndexOf("#"); if (h != -1) search = search.substr(0, h); if (!search) return []; return this.parseURLEncodedText(search); }; this.parseURLEncodedText = function(text) { var maxValueLength = 25000; var params = []; // Unescape '+' characters that are used to encode a space. // See section 2.2.in RFC 3986: http://www.ietf.org/rfc/rfc3986.txt text = text.replace(/\+/g, " "); var args = text.split("&"); for (var i = 0; i < args.length; ++i) { try { var parts = args[i].split("="); if (parts.length == 2) { if (parts[1].length > maxValueLength) parts[1] = this.$STR("LargeData"); params.push({name: decodeURIComponent(parts[0]), value: decodeURIComponent(parts[1])}); } else params.push({name: decodeURIComponent(parts[0]), value: ""}); } catch (e) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout("parseURLEncodedText EXCEPTION ", e); FBTrace.sysout("parseURLEncodedText EXCEPTION URI", args[i]); } } } params.sort(function(a, b) { return a.name <= b.name ? -1 : 1; }); return params; }; // TODO: xxxpedro lib. why loops in domplate are requiring array in parameters // as in response/request headers and get/post parameters in Net module? this.parseURLParamsArray = function(url) { var q = url ? url.indexOf("?") : -1; if (q == -1) return []; var search = url.substr(q+1); var h = search.lastIndexOf("#"); if (h != -1) search = search.substr(0, h); if (!search) return []; return this.parseURLEncodedTextArray(search); }; this.parseURLEncodedTextArray = function(text) { var maxValueLength = 25000; var params = []; // Unescape '+' characters that are used to encode a space. // See section 2.2.in RFC 3986: http://www.ietf.org/rfc/rfc3986.txt text = text.replace(/\+/g, " "); var args = text.split("&"); for (var i = 0; i < args.length; ++i) { try { var parts = args[i].split("="); if (parts.length == 2) { if (parts[1].length > maxValueLength) parts[1] = this.$STR("LargeData"); params.push({name: decodeURIComponent(parts[0]), value: [decodeURIComponent(parts[1])]}); } else params.push({name: decodeURIComponent(parts[0]), value: [""]}); } catch (e) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout("parseURLEncodedText EXCEPTION ", e); FBTrace.sysout("parseURLEncodedText EXCEPTION URI", args[i]); } } } params.sort(function(a, b) { return a.name <= b.name ? -1 : 1; }); return params; }; this.reEncodeURL = function(file, text) { var lines = text.split("\n"); var params = this.parseURLEncodedText(lines[lines.length-1]); var args = []; for (var i = 0; i < params.length; ++i) args.push(encodeURIComponent(params[i].name)+"="+encodeURIComponent(params[i].value)); var url = file.href; url += (url.indexOf("?") == -1 ? "?" : "&") + args.join("&"); return url; }; this.getResource = function(aURL) { try { var channel=ioService.newChannel(aURL,null,null); var input=channel.open(); return FBL.readFromStream(input); } catch (e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.getResource FAILS for "+aURL, e); } }; this.parseJSONString = function(jsonString, originURL) { // See if this is a Prototype style *-secure request. var regex = new RegExp(/^\/\*-secure-([\s\S]*)\*\/\s*$/); var matches = regex.exec(jsonString); if (matches) { jsonString = matches[1]; if (jsonString[0] == "\\" && jsonString[1] == "n") jsonString = jsonString.substr(2); if (jsonString[jsonString.length-2] == "\\" && jsonString[jsonString.length-1] == "n") jsonString = jsonString.substr(0, jsonString.length-2); } if (jsonString.indexOf("&&&START&&&")) { regex = new RegExp(/&&&START&&& (.+) &&&END&&&/); matches = regex.exec(jsonString); if (matches) jsonString = matches[1]; } // throw on the extra parentheses jsonString = "(" + jsonString + ")"; ///var s = Components.utils.Sandbox(originURL); var jsonObject = null; try { ///jsonObject = Components.utils.evalInSandbox(jsonString, s); //jsonObject = Firebug.context.eval(jsonString); jsonObject = Firebug.context.evaluate(jsonString, null, null, function(){return null;}); } catch(e) { /*** if (e.message.indexOf("is not defined")) { var parts = e.message.split(" "); s[parts[0]] = function(str){ return str; }; try { jsonObject = Components.utils.evalInSandbox(jsonString, s); } catch(ex) { if (FBTrace.DBG_ERRORS || FBTrace.DBG_JSONVIEWER) FBTrace.sysout("jsonviewer.parseJSON EXCEPTION", e); return null; } } else {/**/ if (FBTrace.DBG_ERRORS || FBTrace.DBG_JSONVIEWER) FBTrace.sysout("jsonviewer.parseJSON EXCEPTION", e); return null; ///} } return jsonObject; }; // ************************************************************************************************ this.objectToString = function(object) { try { return object+""; } catch (exc) { return null; } }; // ************************************************************************************************ // Input Caret Position this.setSelectionRange = function(input, start, length) { if (input.createTextRange) { var range = input.createTextRange(); range.moveStart("character", start); range.moveEnd("character", length - input.value.length); range.select(); } else if (input.setSelectionRange) { input.setSelectionRange(start, length); input.focus(); } }; // ************************************************************************************************ // Input Selection Start / Caret Position this.getInputSelectionStart = function(input) { if (document.selection) { var range = input.ownerDocument.selection.createRange(); var text = range.text; //console.log("range", range.text); // if there is a selection, find the start position if (text) { return input.value.indexOf(text); } // if there is no selection, find the caret position else { range.moveStart("character", -input.value.length); return range.text.length; } } else if (typeof input.selectionStart != "undefined") return input.selectionStart; return 0; }; // ************************************************************************************************ // Opera Tab Fix function onOperaTabBlur(e) { if (this.lastKey == 9) this.focus(); }; function onOperaTabKeyDown(e) { this.lastKey = e.keyCode; }; function onOperaTabFocus(e) { this.lastKey = null; }; this.fixOperaTabKey = function(el) { el.onfocus = onOperaTabFocus; el.onblur = onOperaTabBlur; el.onkeydown = onOperaTabKeyDown; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.Property = function(object, name) { this.object = object; this.name = name; this.getObject = function() { return object[name]; }; }; this.ErrorCopy = function(message) { this.message = message; }; function EventCopy(event) { // Because event objects are destroyed arbitrarily by Gecko, we must make a copy of them to // represent them long term in the inspector. for (var name in event) { try { this[name] = event[name]; } catch (exc) { } } } this.EventCopy = EventCopy; // ************************************************************************************************ // Type Checking var toString = Object.prototype.toString; var reFunction = /^\s*function(\s+[\w_$][\w\d_$]*)?\s*\(/; this.isArray = function(object) { return toString.call(object) === '[object Array]'; }; this.isFunction = function(object) { if (!object) return false; try { // FIXME: xxxpedro this is failing in IE for the global "external" object return toString.call(object) === "[object Function]" || this.isIE && typeof object != "string" && reFunction.test(""+object); } catch (E) { FBTrace.sysout("Lib.isFunction() failed for ", object); return false; } }; // ************************************************************************************************ // Instance Checking this.instanceOf = function(object, className) { if (!object || typeof object != "object") return false; // Try to use the native instanceof operator. We can only use it when we know // exactly the window where the object is located at if (object.ownerDocument) { // find the correct window of the object var win = object.ownerDocument.defaultView || object.ownerDocument.parentWindow; // if the class is accessible in the window, uses the native instanceof operator // if the instanceof evaluates to "true" we can assume it is a instance, but if it // evaluates to "false" we must continue with the duck type detection below because // the native object may be extended, thus breaking the instanceof result // See Issue 3524: Firebug Lite Style Panel doesn't work if the native Element is extended if (className in win && object instanceof win[className]) return true; } // If the object doesn't have the ownerDocument property, we'll try to look at // the current context's window else { // TODO: xxxpedro context // Since we're not using yet a Firebug.context, we'll just use the top window // (browser) as a reference var win = Firebug.browser.window; if (className in win) return object instanceof win[className]; } // get the duck type model from the cache var cache = instanceCheckMap[className]; if (!cache) return false; // starts the hacky duck type detection for(var n in cache) { var obj = cache[n]; var type = typeof obj; obj = type == "object" ? obj : [obj]; for(var name in obj) { // avoid problems with extended native objects // See Issue 3524: Firebug Lite Style Panel doesn't work if the native Element is extended if (!obj.hasOwnProperty(name)) continue; var value = obj[name]; if( n == "property" && !(value in object) || n == "method" && !this.isFunction(object[value]) || n == "value" && (""+object[name]).toLowerCase() != (""+value).toLowerCase() ) return false; } } return true; }; var instanceCheckMap = { // DuckTypeCheck: // { // property: ["window", "document"], // method: "setTimeout", // value: {nodeType: 1} // }, Window: { property: ["window", "document"], method: "setTimeout" }, Document: { property: ["body", "cookie"], method: "getElementById" }, Node: { property: "ownerDocument", method: "appendChild" }, Element: { property: "tagName", value: {nodeType: 1} }, Location: { property: ["hostname", "protocol"], method: "assign" }, HTMLImageElement: { property: "useMap", value: { nodeType: 1, tagName: "img" } }, HTMLAnchorElement: { property: "hreflang", value: { nodeType: 1, tagName: "a" } }, HTMLInputElement: { property: "form", value: { nodeType: 1, tagName: "input" } }, HTMLButtonElement: { // ? }, HTMLFormElement: { method: "submit", value: { nodeType: 1, tagName: "form" } }, HTMLBodyElement: { }, HTMLHtmlElement: { }, CSSStyleRule: { property: ["selectorText", "style"] } }; // ************************************************************************************************ // DOM Constants /* Problems: - IE does not have window.Node, window.Element, etc - for (var name in Node.prototype) return nothing on FF */ var domMemberMap2 = {}; var domMemberMap2Sandbox = null; var getDomMemberMap2 = function(name) { if (!domMemberMap2Sandbox) { var doc = Firebug.chrome.document; var frame = doc.createElement("iframe"); frame.id = "FirebugSandbox"; frame.style.display = "none"; frame.src = "about:blank"; doc.body.appendChild(frame); domMemberMap2Sandbox = frame.window || frame.contentWindow; } var props = []; //var object = domMemberMap2Sandbox[name]; //object = object.prototype || object; var object = null; if (name == "Window") object = domMemberMap2Sandbox.window; else if (name == "Document") object = domMemberMap2Sandbox.document; else if (name == "HTMLScriptElement") object = domMemberMap2Sandbox.document.createElement("script"); else if (name == "HTMLAnchorElement") object = domMemberMap2Sandbox.document.createElement("a"); else if (name.indexOf("Element") != -1) { object = domMemberMap2Sandbox.document.createElement("div"); } if (object) { //object = object.prototype || object; //props = 'addEventListener,document,location,navigator,window'.split(','); for (var n in object) props.push(n); } /**/ return props; return extendArray(props, domMemberMap[name]); }; // xxxpedro experimental get DOM members this.getDOMMembers = function(object) { if (!domMemberCache) { FBL.domMemberCache = domMemberCache = {}; for (var name in domMemberMap) { var builtins = getDomMemberMap2(name); var cache = domMemberCache[name] = {}; /* if (name.indexOf("Element") != -1) { this.append(cache, this.getDOMMembers("Node")); this.append(cache, this.getDOMMembers("Element")); } /**/ for (var i = 0; i < builtins.length; ++i) cache[builtins[i]] = i; } } try { if (this.instanceOf(object, "Window")) { return domMemberCache.Window; } else if (this.instanceOf(object, "Document") || this.instanceOf(object, "XMLDocument")) { return domMemberCache.Document; } else if (this.instanceOf(object, "Location")) { return domMemberCache.Location; } else if (this.instanceOf(object, "HTMLImageElement")) { return domMemberCache.HTMLImageElement; } else if (this.instanceOf(object, "HTMLAnchorElement")) { return domMemberCache.HTMLAnchorElement; } else if (this.instanceOf(object, "HTMLInputElement")) { return domMemberCache.HTMLInputElement; } else if (this.instanceOf(object, "HTMLButtonElement")) { return domMemberCache.HTMLButtonElement; } else if (this.instanceOf(object, "HTMLFormElement")) { return domMemberCache.HTMLFormElement; } else if (this.instanceOf(object, "HTMLBodyElement")) { return domMemberCache.HTMLBodyElement; } else if (this.instanceOf(object, "HTMLHtmlElement")) { return domMemberCache.HTMLHtmlElement; } else if (this.instanceOf(object, "HTMLScriptElement")) { return domMemberCache.HTMLScriptElement; } else if (this.instanceOf(object, "HTMLTableElement")) { return domMemberCache.HTMLTableElement; } else if (this.instanceOf(object, "HTMLTableRowElement")) { return domMemberCache.HTMLTableRowElement; } else if (this.instanceOf(object, "HTMLTableCellElement")) { return domMemberCache.HTMLTableCellElement; } else if (this.instanceOf(object, "HTMLIFrameElement")) { return domMemberCache.HTMLIFrameElement; } else if (this.instanceOf(object, "SVGSVGElement")) { return domMemberCache.SVGSVGElement; } else if (this.instanceOf(object, "SVGElement")) { return domMemberCache.SVGElement; } else if (this.instanceOf(object, "Element")) { return domMemberCache.Element; } else if (this.instanceOf(object, "Text") || this.instanceOf(object, "CDATASection")) { return domMemberCache.Text; } else if (this.instanceOf(object, "Attr")) { return domMemberCache.Attr; } else if (this.instanceOf(object, "Node")) { return domMemberCache.Node; } else if (this.instanceOf(object, "Event") || this.instanceOf(object, "EventCopy")) { return domMemberCache.Event; } else return {}; } catch(E) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.getDOMMembers FAILED ", E); return {}; } }; /* this.getDOMMembers = function(object) { if (!domMemberCache) { domMemberCache = {}; for (var name in domMemberMap) { var builtins = domMemberMap[name]; var cache = domMemberCache[name] = {}; for (var i = 0; i < builtins.length; ++i) cache[builtins[i]] = i; } } try { if (this.instanceOf(object, "Window")) { return domMemberCache.Window; } else if (object instanceof Document || object instanceof XMLDocument) { return domMemberCache.Document; } else if (object instanceof Location) { return domMemberCache.Location; } else if (object instanceof HTMLImageElement) { return domMemberCache.HTMLImageElement; } else if (object instanceof HTMLAnchorElement) { return domMemberCache.HTMLAnchorElement; } else if (object instanceof HTMLInputElement) { return domMemberCache.HTMLInputElement; } else if (object instanceof HTMLButtonElement) { return domMemberCache.HTMLButtonElement; } else if (object instanceof HTMLFormElement) { return domMemberCache.HTMLFormElement; } else if (object instanceof HTMLBodyElement) { return domMemberCache.HTMLBodyElement; } else if (object instanceof HTMLHtmlElement) { return domMemberCache.HTMLHtmlElement; } else if (object instanceof HTMLScriptElement) { return domMemberCache.HTMLScriptElement; } else if (object instanceof HTMLTableElement) { return domMemberCache.HTMLTableElement; } else if (object instanceof HTMLTableRowElement) { return domMemberCache.HTMLTableRowElement; } else if (object instanceof HTMLTableCellElement) { return domMemberCache.HTMLTableCellElement; } else if (object instanceof HTMLIFrameElement) { return domMemberCache.HTMLIFrameElement; } else if (object instanceof SVGSVGElement) { return domMemberCache.SVGSVGElement; } else if (object instanceof SVGElement) { return domMemberCache.SVGElement; } else if (object instanceof Element) { return domMemberCache.Element; } else if (object instanceof Text || object instanceof CDATASection) { return domMemberCache.Text; } else if (object instanceof Attr) { return domMemberCache.Attr; } else if (object instanceof Node) { return domMemberCache.Node; } else if (object instanceof Event || object instanceof EventCopy) { return domMemberCache.Event; } else return {}; } catch(E) { return {}; } }; /**/ this.isDOMMember = function(object, propName) { var members = this.getDOMMembers(object); return members && propName in members; }; var domMemberCache = null; var domMemberMap = {}; domMemberMap.Window = [ "document", "frameElement", "innerWidth", "innerHeight", "outerWidth", "outerHeight", "screenX", "screenY", "pageXOffset", "pageYOffset", "scrollX", "scrollY", "scrollMaxX", "scrollMaxY", "status", "defaultStatus", "parent", "opener", "top", "window", "content", "self", "location", "history", "frames", "navigator", "screen", "menubar", "toolbar", "locationbar", "personalbar", "statusbar", "directories", "scrollbars", "fullScreen", "netscape", "java", "console", "Components", "controllers", "closed", "crypto", "pkcs11", "name", "property", "length", "sessionStorage", "globalStorage", "setTimeout", "setInterval", "clearTimeout", "clearInterval", "addEventListener", "removeEventListener", "dispatchEvent", "getComputedStyle", "captureEvents", "releaseEvents", "routeEvent", "enableExternalCapture", "disableExternalCapture", "moveTo", "moveBy", "resizeTo", "resizeBy", "scroll", "scrollTo", "scrollBy", "scrollByLines", "scrollByPages", "sizeToContent", "setResizable", "getSelection", "open", "openDialog", "close", "alert", "confirm", "prompt", "dump", "focus", "blur", "find", "back", "forward", "home", "stop", "print", "atob", "btoa", "updateCommands", "XPCNativeWrapper", "GeckoActiveXObject", "applicationCache" // FF3 ]; domMemberMap.Location = [ "href", "protocol", "host", "hostname", "port", "pathname", "search", "hash", "assign", "reload", "replace" ]; domMemberMap.Node = [ "id", "className", "nodeType", "tagName", "nodeName", "localName", "prefix", "namespaceURI", "nodeValue", "ownerDocument", "parentNode", "offsetParent", "nextSibling", "previousSibling", "firstChild", "lastChild", "childNodes", "attributes", "dir", "baseURI", "textContent", "innerHTML", "addEventListener", "removeEventListener", "dispatchEvent", "cloneNode", "appendChild", "insertBefore", "replaceChild", "removeChild", "compareDocumentPosition", "hasAttributes", "hasChildNodes", "lookupNamespaceURI", "lookupPrefix", "normalize", "isDefaultNamespace", "isEqualNode", "isSameNode", "isSupported", "getFeature", "getUserData", "setUserData" ]; domMemberMap.Document = extendArray(domMemberMap.Node, [ "documentElement", "body", "title", "location", "referrer", "cookie", "contentType", "lastModified", "characterSet", "inputEncoding", "xmlEncoding", "xmlStandalone", "xmlVersion", "strictErrorChecking", "documentURI", "URL", "defaultView", "doctype", "implementation", "styleSheets", "images", "links", "forms", "anchors", "embeds", "plugins", "applets", "width", "height", "designMode", "compatMode", "async", "preferredStylesheetSet", "alinkColor", "linkColor", "vlinkColor", "bgColor", "fgColor", "domain", "addEventListener", "removeEventListener", "dispatchEvent", "captureEvents", "releaseEvents", "routeEvent", "clear", "open", "close", "execCommand", "execCommandShowHelp", "getElementsByName", "getSelection", "queryCommandEnabled", "queryCommandIndeterm", "queryCommandState", "queryCommandSupported", "queryCommandText", "queryCommandValue", "write", "writeln", "adoptNode", "appendChild", "removeChild", "renameNode", "cloneNode", "compareDocumentPosition", "createAttribute", "createAttributeNS", "createCDATASection", "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEntityReference", "createEvent", "createExpression", "createNSResolver", "createNodeIterator", "createProcessingInstruction", "createRange", "createTextNode", "createTreeWalker", "domConfig", "evaluate", "evaluateFIXptr", "evaluateXPointer", "getAnonymousElementByAttribute", "getAnonymousNodes", "addBinding", "removeBinding", "getBindingParent", "getBoxObjectFor", "setBoxObjectFor", "getElementById", "getElementsByTagName", "getElementsByTagNameNS", "hasAttributes", "hasChildNodes", "importNode", "insertBefore", "isDefaultNamespace", "isEqualNode", "isSameNode", "isSupported", "load", "loadBindingDocument", "lookupNamespaceURI", "lookupPrefix", "normalize", "normalizeDocument", "getFeature", "getUserData", "setUserData" ]); domMemberMap.Element = extendArray(domMemberMap.Node, [ "clientWidth", "clientHeight", "offsetLeft", "offsetTop", "offsetWidth", "offsetHeight", "scrollLeft", "scrollTop", "scrollWidth", "scrollHeight", "style", "tabIndex", "title", "lang", "align", "spellcheck", "addEventListener", "removeEventListener", "dispatchEvent", "focus", "blur", "cloneNode", "appendChild", "insertBefore", "replaceChild", "removeChild", "compareDocumentPosition", "getElementsByTagName", "getElementsByTagNameNS", "getAttribute", "getAttributeNS", "getAttributeNode", "getAttributeNodeNS", "setAttribute", "setAttributeNS", "setAttributeNode", "setAttributeNodeNS", "removeAttribute", "removeAttributeNS", "removeAttributeNode", "hasAttribute", "hasAttributeNS", "hasAttributes", "hasChildNodes", "lookupNamespaceURI", "lookupPrefix", "normalize", "isDefaultNamespace", "isEqualNode", "isSameNode", "isSupported", "getFeature", "getUserData", "setUserData" ]); domMemberMap.SVGElement = extendArray(domMemberMap.Element, [ "x", "y", "width", "height", "rx", "ry", "transform", "href", "ownerSVGElement", "viewportElement", "farthestViewportElement", "nearestViewportElement", "getBBox", "getCTM", "getScreenCTM", "getTransformToElement", "getPresentationAttribute", "preserveAspectRatio" ]); domMemberMap.SVGSVGElement = extendArray(domMemberMap.Element, [ "x", "y", "width", "height", "rx", "ry", "transform", "viewBox", "viewport", "currentView", "useCurrentView", "pixelUnitToMillimeterX", "pixelUnitToMillimeterY", "screenPixelToMillimeterX", "screenPixelToMillimeterY", "currentScale", "currentTranslate", "zoomAndPan", "ownerSVGElement", "viewportElement", "farthestViewportElement", "nearestViewportElement", "contentScriptType", "contentStyleType", "getBBox", "getCTM", "getScreenCTM", "getTransformToElement", "getEnclosureList", "getIntersectionList", "getViewboxToViewportTransform", "getPresentationAttribute", "getElementById", "checkEnclosure", "checkIntersection", "createSVGAngle", "createSVGLength", "createSVGMatrix", "createSVGNumber", "createSVGPoint", "createSVGRect", "createSVGString", "createSVGTransform", "createSVGTransformFromMatrix", "deSelectAll", "preserveAspectRatio", "forceRedraw", "suspendRedraw", "unsuspendRedraw", "unsuspendRedrawAll", "getCurrentTime", "setCurrentTime", "animationsPaused", "pauseAnimations", "unpauseAnimations" ]); domMemberMap.HTMLImageElement = extendArray(domMemberMap.Element, [ "src", "naturalWidth", "naturalHeight", "width", "height", "x", "y", "name", "alt", "longDesc", "lowsrc", "border", "complete", "hspace", "vspace", "isMap", "useMap" ]); domMemberMap.HTMLAnchorElement = extendArray(domMemberMap.Element, [ "name", "target", "accessKey", "href", "protocol", "host", "hostname", "port", "pathname", "search", "hash", "hreflang", "coords", "shape", "text", "type", "rel", "rev", "charset" ]); domMemberMap.HTMLIFrameElement = extendArray(domMemberMap.Element, [ "contentDocument", "contentWindow", "frameBorder", "height", "longDesc", "marginHeight", "marginWidth", "name", "scrolling", "src", "width" ]); domMemberMap.HTMLTableElement = extendArray(domMemberMap.Element, [ "bgColor", "border", "caption", "cellPadding", "cellSpacing", "frame", "rows", "rules", "summary", "tBodies", "tFoot", "tHead", "width", "createCaption", "createTFoot", "createTHead", "deleteCaption", "deleteRow", "deleteTFoot", "deleteTHead", "insertRow" ]); domMemberMap.HTMLTableRowElement = extendArray(domMemberMap.Element, [ "bgColor", "cells", "ch", "chOff", "rowIndex", "sectionRowIndex", "vAlign", "deleteCell", "insertCell" ]); domMemberMap.HTMLTableCellElement = extendArray(domMemberMap.Element, [ "abbr", "axis", "bgColor", "cellIndex", "ch", "chOff", "colSpan", "headers", "height", "noWrap", "rowSpan", "scope", "vAlign", "width" ]); domMemberMap.HTMLScriptElement = extendArray(domMemberMap.Element, [ "src" ]); domMemberMap.HTMLButtonElement = extendArray(domMemberMap.Element, [ "accessKey", "disabled", "form", "name", "type", "value", "click" ]); domMemberMap.HTMLInputElement = extendArray(domMemberMap.Element, [ "type", "value", "checked", "accept", "accessKey", "alt", "controllers", "defaultChecked", "defaultValue", "disabled", "form", "maxLength", "name", "readOnly", "selectionEnd", "selectionStart", "size", "src", "textLength", "useMap", "click", "select", "setSelectionRange" ]); domMemberMap.HTMLFormElement = extendArray(domMemberMap.Element, [ "acceptCharset", "action", "author", "elements", "encoding", "enctype", "entry_id", "length", "method", "name", "post", "target", "text", "url", "reset", "submit" ]); domMemberMap.HTMLBodyElement = extendArray(domMemberMap.Element, [ "aLink", "background", "bgColor", "link", "text", "vLink" ]); domMemberMap.HTMLHtmlElement = extendArray(domMemberMap.Element, [ "version" ]); domMemberMap.Text = extendArray(domMemberMap.Node, [ "data", "length", "appendData", "deleteData", "insertData", "replaceData", "splitText", "substringData" ]); domMemberMap.Attr = extendArray(domMemberMap.Node, [ "name", "value", "specified", "ownerElement" ]); domMemberMap.Event = [ "type", "target", "currentTarget", "originalTarget", "explicitOriginalTarget", "relatedTarget", "rangeParent", "rangeOffset", "view", "keyCode", "charCode", "screenX", "screenY", "clientX", "clientY", "layerX", "layerY", "pageX", "pageY", "detail", "button", "which", "ctrlKey", "shiftKey", "altKey", "metaKey", "eventPhase", "timeStamp", "bubbles", "cancelable", "cancelBubble", "isTrusted", "isChar", "getPreventDefault", "initEvent", "initMouseEvent", "initKeyEvent", "initUIEvent", "preventBubble", "preventCapture", "preventDefault", "stopPropagation" ]; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.domConstantMap = { "ELEMENT_NODE": 1, "ATTRIBUTE_NODE": 1, "TEXT_NODE": 1, "CDATA_SECTION_NODE": 1, "ENTITY_REFERENCE_NODE": 1, "ENTITY_NODE": 1, "PROCESSING_INSTRUCTION_NODE": 1, "COMMENT_NODE": 1, "DOCUMENT_NODE": 1, "DOCUMENT_TYPE_NODE": 1, "DOCUMENT_FRAGMENT_NODE": 1, "NOTATION_NODE": 1, "DOCUMENT_POSITION_DISCONNECTED": 1, "DOCUMENT_POSITION_PRECEDING": 1, "DOCUMENT_POSITION_FOLLOWING": 1, "DOCUMENT_POSITION_CONTAINS": 1, "DOCUMENT_POSITION_CONTAINED_BY": 1, "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC": 1, "UNKNOWN_RULE": 1, "STYLE_RULE": 1, "CHARSET_RULE": 1, "IMPORT_RULE": 1, "MEDIA_RULE": 1, "FONT_FACE_RULE": 1, "PAGE_RULE": 1, "CAPTURING_PHASE": 1, "AT_TARGET": 1, "BUBBLING_PHASE": 1, "SCROLL_PAGE_UP": 1, "SCROLL_PAGE_DOWN": 1, "MOUSEUP": 1, "MOUSEDOWN": 1, "MOUSEOVER": 1, "MOUSEOUT": 1, "MOUSEMOVE": 1, "MOUSEDRAG": 1, "CLICK": 1, "DBLCLICK": 1, "KEYDOWN": 1, "KEYUP": 1, "KEYPRESS": 1, "DRAGDROP": 1, "FOCUS": 1, "BLUR": 1, "SELECT": 1, "CHANGE": 1, "RESET": 1, "SUBMIT": 1, "SCROLL": 1, "LOAD": 1, "UNLOAD": 1, "XFER_DONE": 1, "ABORT": 1, "ERROR": 1, "LOCATE": 1, "MOVE": 1, "RESIZE": 1, "FORWARD": 1, "HELP": 1, "BACK": 1, "TEXT": 1, "ALT_MASK": 1, "CONTROL_MASK": 1, "SHIFT_MASK": 1, "META_MASK": 1, "DOM_VK_TAB": 1, "DOM_VK_PAGE_UP": 1, "DOM_VK_PAGE_DOWN": 1, "DOM_VK_UP": 1, "DOM_VK_DOWN": 1, "DOM_VK_LEFT": 1, "DOM_VK_RIGHT": 1, "DOM_VK_CANCEL": 1, "DOM_VK_HELP": 1, "DOM_VK_BACK_SPACE": 1, "DOM_VK_CLEAR": 1, "DOM_VK_RETURN": 1, "DOM_VK_ENTER": 1, "DOM_VK_SHIFT": 1, "DOM_VK_CONTROL": 1, "DOM_VK_ALT": 1, "DOM_VK_PAUSE": 1, "DOM_VK_CAPS_LOCK": 1, "DOM_VK_ESCAPE": 1, "DOM_VK_SPACE": 1, "DOM_VK_END": 1, "DOM_VK_HOME": 1, "DOM_VK_PRINTSCREEN": 1, "DOM_VK_INSERT": 1, "DOM_VK_DELETE": 1, "DOM_VK_0": 1, "DOM_VK_1": 1, "DOM_VK_2": 1, "DOM_VK_3": 1, "DOM_VK_4": 1, "DOM_VK_5": 1, "DOM_VK_6": 1, "DOM_VK_7": 1, "DOM_VK_8": 1, "DOM_VK_9": 1, "DOM_VK_SEMICOLON": 1, "DOM_VK_EQUALS": 1, "DOM_VK_A": 1, "DOM_VK_B": 1, "DOM_VK_C": 1, "DOM_VK_D": 1, "DOM_VK_E": 1, "DOM_VK_F": 1, "DOM_VK_G": 1, "DOM_VK_H": 1, "DOM_VK_I": 1, "DOM_VK_J": 1, "DOM_VK_K": 1, "DOM_VK_L": 1, "DOM_VK_M": 1, "DOM_VK_N": 1, "DOM_VK_O": 1, "DOM_VK_P": 1, "DOM_VK_Q": 1, "DOM_VK_R": 1, "DOM_VK_S": 1, "DOM_VK_T": 1, "DOM_VK_U": 1, "DOM_VK_V": 1, "DOM_VK_W": 1, "DOM_VK_X": 1, "DOM_VK_Y": 1, "DOM_VK_Z": 1, "DOM_VK_CONTEXT_MENU": 1, "DOM_VK_NUMPAD0": 1, "DOM_VK_NUMPAD1": 1, "DOM_VK_NUMPAD2": 1, "DOM_VK_NUMPAD3": 1, "DOM_VK_NUMPAD4": 1, "DOM_VK_NUMPAD5": 1, "DOM_VK_NUMPAD6": 1, "DOM_VK_NUMPAD7": 1, "DOM_VK_NUMPAD8": 1, "DOM_VK_NUMPAD9": 1, "DOM_VK_MULTIPLY": 1, "DOM_VK_ADD": 1, "DOM_VK_SEPARATOR": 1, "DOM_VK_SUBTRACT": 1, "DOM_VK_DECIMAL": 1, "DOM_VK_DIVIDE": 1, "DOM_VK_F1": 1, "DOM_VK_F2": 1, "DOM_VK_F3": 1, "DOM_VK_F4": 1, "DOM_VK_F5": 1, "DOM_VK_F6": 1, "DOM_VK_F7": 1, "DOM_VK_F8": 1, "DOM_VK_F9": 1, "DOM_VK_F10": 1, "DOM_VK_F11": 1, "DOM_VK_F12": 1, "DOM_VK_F13": 1, "DOM_VK_F14": 1, "DOM_VK_F15": 1, "DOM_VK_F16": 1, "DOM_VK_F17": 1, "DOM_VK_F18": 1, "DOM_VK_F19": 1, "DOM_VK_F20": 1, "DOM_VK_F21": 1, "DOM_VK_F22": 1, "DOM_VK_F23": 1, "DOM_VK_F24": 1, "DOM_VK_NUM_LOCK": 1, "DOM_VK_SCROLL_LOCK": 1, "DOM_VK_COMMA": 1, "DOM_VK_PERIOD": 1, "DOM_VK_SLASH": 1, "DOM_VK_BACK_QUOTE": 1, "DOM_VK_OPEN_BRACKET": 1, "DOM_VK_BACK_SLASH": 1, "DOM_VK_CLOSE_BRACKET": 1, "DOM_VK_QUOTE": 1, "DOM_VK_META": 1, "SVG_ZOOMANDPAN_DISABLE": 1, "SVG_ZOOMANDPAN_MAGNIFY": 1, "SVG_ZOOMANDPAN_UNKNOWN": 1 }; this.cssInfo = { "background": ["bgRepeat", "bgAttachment", "bgPosition", "color", "systemColor", "none"], "background-attachment": ["bgAttachment"], "background-color": ["color", "systemColor"], "background-image": ["none"], "background-position": ["bgPosition"], "background-repeat": ["bgRepeat"], "border": ["borderStyle", "thickness", "color", "systemColor", "none"], "border-top": ["borderStyle", "borderCollapse", "color", "systemColor", "none"], "border-right": ["borderStyle", "borderCollapse", "color", "systemColor", "none"], "border-bottom": ["borderStyle", "borderCollapse", "color", "systemColor", "none"], "border-left": ["borderStyle", "borderCollapse", "color", "systemColor", "none"], "border-collapse": ["borderCollapse"], "border-color": ["color", "systemColor"], "border-top-color": ["color", "systemColor"], "border-right-color": ["color", "systemColor"], "border-bottom-color": ["color", "systemColor"], "border-left-color": ["color", "systemColor"], "border-spacing": [], "border-style": ["borderStyle"], "border-top-style": ["borderStyle"], "border-right-style": ["borderStyle"], "border-bottom-style": ["borderStyle"], "border-left-style": ["borderStyle"], "border-width": ["thickness"], "border-top-width": ["thickness"], "border-right-width": ["thickness"], "border-bottom-width": ["thickness"], "border-left-width": ["thickness"], "bottom": ["auto"], "caption-side": ["captionSide"], "clear": ["clear", "none"], "clip": ["auto"], "color": ["color", "systemColor"], "content": ["content"], "counter-increment": ["none"], "counter-reset": ["none"], "cursor": ["cursor", "none"], "direction": ["direction"], "display": ["display", "none"], "empty-cells": [], "float": ["float", "none"], "font": ["fontStyle", "fontVariant", "fontWeight", "fontFamily"], "font-family": ["fontFamily"], "font-size": ["fontSize"], "font-size-adjust": [], "font-stretch": [], "font-style": ["fontStyle"], "font-variant": ["fontVariant"], "font-weight": ["fontWeight"], "height": ["auto"], "left": ["auto"], "letter-spacing": [], "line-height": [], "list-style": ["listStyleType", "listStylePosition", "none"], "list-style-image": ["none"], "list-style-position": ["listStylePosition"], "list-style-type": ["listStyleType", "none"], "margin": [], "margin-top": [], "margin-right": [], "margin-bottom": [], "margin-left": [], "marker-offset": ["auto"], "min-height": ["none"], "max-height": ["none"], "min-width": ["none"], "max-width": ["none"], "outline": ["borderStyle", "color", "systemColor", "none"], "outline-color": ["color", "systemColor"], "outline-style": ["borderStyle"], "outline-width": [], "overflow": ["overflow", "auto"], "overflow-x": ["overflow", "auto"], "overflow-y": ["overflow", "auto"], "padding": [], "padding-top": [], "padding-right": [], "padding-bottom": [], "padding-left": [], "position": ["position"], "quotes": ["none"], "right": ["auto"], "table-layout": ["tableLayout", "auto"], "text-align": ["textAlign"], "text-decoration": ["textDecoration", "none"], "text-indent": [], "text-shadow": [], "text-transform": ["textTransform", "none"], "top": ["auto"], "unicode-bidi": [], "vertical-align": ["verticalAlign"], "white-space": ["whiteSpace"], "width": ["auto"], "word-spacing": [], "z-index": [], "-moz-appearance": ["mozAppearance"], "-moz-border-radius": [], "-moz-border-radius-bottomleft": [], "-moz-border-radius-bottomright": [], "-moz-border-radius-topleft": [], "-moz-border-radius-topright": [], "-moz-border-top-colors": ["color", "systemColor"], "-moz-border-right-colors": ["color", "systemColor"], "-moz-border-bottom-colors": ["color", "systemColor"], "-moz-border-left-colors": ["color", "systemColor"], "-moz-box-align": ["mozBoxAlign"], "-moz-box-direction": ["mozBoxDirection"], "-moz-box-flex": [], "-moz-box-ordinal-group": [], "-moz-box-orient": ["mozBoxOrient"], "-moz-box-pack": ["mozBoxPack"], "-moz-box-sizing": ["mozBoxSizing"], "-moz-opacity": [], "-moz-user-focus": ["userFocus", "none"], "-moz-user-input": ["userInput"], "-moz-user-modify": [], "-moz-user-select": ["userSelect", "none"], "-moz-background-clip": [], "-moz-background-inline-policy": [], "-moz-background-origin": [], "-moz-binding": [], "-moz-column-count": [], "-moz-column-gap": [], "-moz-column-width": [], "-moz-image-region": [] }; this.inheritedStyleNames = { "border-collapse": 1, "border-spacing": 1, "border-style": 1, "caption-side": 1, "color": 1, "cursor": 1, "direction": 1, "empty-cells": 1, "font": 1, "font-family": 1, "font-size-adjust": 1, "font-size": 1, "font-style": 1, "font-variant": 1, "font-weight": 1, "letter-spacing": 1, "line-height": 1, "list-style": 1, "list-style-image": 1, "list-style-position": 1, "list-style-type": 1, "quotes": 1, "text-align": 1, "text-decoration": 1, "text-indent": 1, "text-shadow": 1, "text-transform": 1, "white-space": 1, "word-spacing": 1 }; this.cssKeywords = { "appearance": [ "button", "button-small", "checkbox", "checkbox-container", "checkbox-small", "dialog", "listbox", "menuitem", "menulist", "menulist-button", "menulist-textfield", "menupopup", "progressbar", "radio", "radio-container", "radio-small", "resizer", "scrollbar", "scrollbarbutton-down", "scrollbarbutton-left", "scrollbarbutton-right", "scrollbarbutton-up", "scrollbartrack-horizontal", "scrollbartrack-vertical", "separator", "statusbar", "tab", "tab-left-edge", "tabpanels", "textfield", "toolbar", "toolbarbutton", "toolbox", "tooltip", "treeheadercell", "treeheadersortarrow", "treeitem", "treetwisty", "treetwistyopen", "treeview", "window" ], "systemColor": [ "ActiveBorder", "ActiveCaption", "AppWorkspace", "Background", "ButtonFace", "ButtonHighlight", "ButtonShadow", "ButtonText", "CaptionText", "GrayText", "Highlight", "HighlightText", "InactiveBorder", "InactiveCaption", "InactiveCaptionText", "InfoBackground", "InfoText", "Menu", "MenuText", "Scrollbar", "ThreeDDarkShadow", "ThreeDFace", "ThreeDHighlight", "ThreeDLightShadow", "ThreeDShadow", "Window", "WindowFrame", "WindowText", "-moz-field", "-moz-fieldtext", "-moz-workspace", "-moz-visitedhyperlinktext", "-moz-use-text-color" ], "color": [ "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkTurquoise", "DarkViolet", "DeepPink", "DarkSkyBlue", "DimGray", "DodgerBlue", "Feldspar", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateBlue", "LightSlateGray", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "VioletRed", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen", "transparent", "invert" ], "auto": [ "auto" ], "none": [ "none" ], "captionSide": [ "top", "bottom", "left", "right" ], "clear": [ "left", "right", "both" ], "cursor": [ "auto", "cell", "context-menu", "crosshair", "default", "help", "pointer", "progress", "move", "e-resize", "all-scroll", "ne-resize", "nw-resize", "n-resize", "se-resize", "sw-resize", "s-resize", "w-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "col-resize", "row-resize", "text", "vertical-text", "wait", "alias", "copy", "move", "no-drop", "not-allowed", "-moz-alias", "-moz-cell", "-moz-copy", "-moz-grab", "-moz-grabbing", "-moz-contextmenu", "-moz-zoom-in", "-moz-zoom-out", "-moz-spinning" ], "direction": [ "ltr", "rtl" ], "bgAttachment": [ "scroll", "fixed" ], "bgPosition": [ "top", "center", "bottom", "left", "right" ], "bgRepeat": [ "repeat", "repeat-x", "repeat-y", "no-repeat" ], "borderStyle": [ "hidden", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset", "-moz-bg-inset", "-moz-bg-outset", "-moz-bg-solid" ], "borderCollapse": [ "collapse", "separate" ], "overflow": [ "visible", "hidden", "scroll", "-moz-scrollbars-horizontal", "-moz-scrollbars-none", "-moz-scrollbars-vertical" ], "listStyleType": [ "disc", "circle", "square", "decimal", "decimal-leading-zero", "lower-roman", "upper-roman", "lower-greek", "lower-alpha", "lower-latin", "upper-alpha", "upper-latin", "hebrew", "armenian", "georgian", "cjk-ideographic", "hiragana", "katakana", "hiragana-iroha", "katakana-iroha", "inherit" ], "listStylePosition": [ "inside", "outside" ], "content": [ "open-quote", "close-quote", "no-open-quote", "no-close-quote", "inherit" ], "fontStyle": [ "normal", "italic", "oblique", "inherit" ], "fontVariant": [ "normal", "small-caps", "inherit" ], "fontWeight": [ "normal", "bold", "bolder", "lighter", "inherit" ], "fontSize": [ "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "smaller", "larger" ], "fontFamily": [ "Arial", "Comic Sans MS", "Georgia", "Tahoma", "Verdana", "Times New Roman", "Trebuchet MS", "Lucida Grande", "Helvetica", "serif", "sans-serif", "cursive", "fantasy", "monospace", "caption", "icon", "menu", "message-box", "small-caption", "status-bar", "inherit" ], "display": [ "block", "inline", "inline-block", "list-item", "marker", "run-in", "compact", "table", "inline-table", "table-row-group", "table-column", "table-column-group", "table-header-group", "table-footer-group", "table-row", "table-cell", "table-caption", "-moz-box", "-moz-compact", "-moz-deck", "-moz-grid", "-moz-grid-group", "-moz-grid-line", "-moz-groupbox", "-moz-inline-block", "-moz-inline-box", "-moz-inline-grid", "-moz-inline-stack", "-moz-inline-table", "-moz-marker", "-moz-popup", "-moz-runin", "-moz-stack" ], "position": [ "static", "relative", "absolute", "fixed", "inherit" ], "float": [ "left", "right" ], "textAlign": [ "left", "right", "center", "justify" ], "tableLayout": [ "fixed" ], "textDecoration": [ "underline", "overline", "line-through", "blink" ], "textTransform": [ "capitalize", "lowercase", "uppercase", "inherit" ], "unicodeBidi": [ "normal", "embed", "bidi-override" ], "whiteSpace": [ "normal", "pre", "nowrap" ], "verticalAlign": [ "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom", "inherit" ], "thickness": [ "thin", "medium", "thick" ], "userFocus": [ "ignore", "normal" ], "userInput": [ "disabled", "enabled" ], "userSelect": [ "normal" ], "mozBoxSizing": [ "content-box", "padding-box", "border-box" ], "mozBoxAlign": [ "start", "center", "end", "baseline", "stretch" ], "mozBoxDirection": [ "normal", "reverse" ], "mozBoxOrient": [ "horizontal", "vertical" ], "mozBoxPack": [ "start", "center", "end" ] }; this.nonEditableTags = { "HTML": 1, "HEAD": 1, "html": 1, "head": 1 }; this.innerEditableTags = { "BODY": 1, "body": 1 }; this.selfClosingTags = { // End tags for void elements are forbidden http://wiki.whatwg.org/wiki/HTML_vs._XHTML "meta": 1, "link": 1, "area": 1, "base": 1, "col": 1, "input": 1, "img": 1, "br": 1, "hr": 1, "param":1, "embed":1 }; var invisibleTags = this.invisibleTags = { "HTML": 1, "HEAD": 1, "TITLE": 1, "META": 1, "LINK": 1, "STYLE": 1, "SCRIPT": 1, "NOSCRIPT": 1, "BR": 1, "PARAM": 1, "COL": 1, "html": 1, "head": 1, "title": 1, "meta": 1, "link": 1, "style": 1, "script": 1, "noscript": 1, "br": 1, "param": 1, "col": 1 /* "window": 1, "browser": 1, "frame": 1, "tabbrowser": 1, "WINDOW": 1, "BROWSER": 1, "FRAME": 1, "TABBROWSER": 1, */ }; if (typeof KeyEvent == "undefined") { this.KeyEvent = { DOM_VK_CANCEL: 3, DOM_VK_HELP: 6, DOM_VK_BACK_SPACE: 8, DOM_VK_TAB: 9, DOM_VK_CLEAR: 12, DOM_VK_RETURN: 13, DOM_VK_ENTER: 14, DOM_VK_SHIFT: 16, DOM_VK_CONTROL: 17, DOM_VK_ALT: 18, DOM_VK_PAUSE: 19, DOM_VK_CAPS_LOCK: 20, DOM_VK_ESCAPE: 27, DOM_VK_SPACE: 32, DOM_VK_PAGE_UP: 33, DOM_VK_PAGE_DOWN: 34, DOM_VK_END: 35, DOM_VK_HOME: 36, DOM_VK_LEFT: 37, DOM_VK_UP: 38, DOM_VK_RIGHT: 39, DOM_VK_DOWN: 40, DOM_VK_PRINTSCREEN: 44, DOM_VK_INSERT: 45, DOM_VK_DELETE: 46, DOM_VK_0: 48, DOM_VK_1: 49, DOM_VK_2: 50, DOM_VK_3: 51, DOM_VK_4: 52, DOM_VK_5: 53, DOM_VK_6: 54, DOM_VK_7: 55, DOM_VK_8: 56, DOM_VK_9: 57, DOM_VK_SEMICOLON: 59, DOM_VK_EQUALS: 61, DOM_VK_A: 65, DOM_VK_B: 66, DOM_VK_C: 67, DOM_VK_D: 68, DOM_VK_E: 69, DOM_VK_F: 70, DOM_VK_G: 71, DOM_VK_H: 72, DOM_VK_I: 73, DOM_VK_J: 74, DOM_VK_K: 75, DOM_VK_L: 76, DOM_VK_M: 77, DOM_VK_N: 78, DOM_VK_O: 79, DOM_VK_P: 80, DOM_VK_Q: 81, DOM_VK_R: 82, DOM_VK_S: 83, DOM_VK_T: 84, DOM_VK_U: 85, DOM_VK_V: 86, DOM_VK_W: 87, DOM_VK_X: 88, DOM_VK_Y: 89, DOM_VK_Z: 90, DOM_VK_CONTEXT_MENU: 93, DOM_VK_NUMPAD0: 96, DOM_VK_NUMPAD1: 97, DOM_VK_NUMPAD2: 98, DOM_VK_NUMPAD3: 99, DOM_VK_NUMPAD4: 100, DOM_VK_NUMPAD5: 101, DOM_VK_NUMPAD6: 102, DOM_VK_NUMPAD7: 103, DOM_VK_NUMPAD8: 104, DOM_VK_NUMPAD9: 105, DOM_VK_MULTIPLY: 106, DOM_VK_ADD: 107, DOM_VK_SEPARATOR: 108, DOM_VK_SUBTRACT: 109, DOM_VK_DECIMAL: 110, DOM_VK_DIVIDE: 111, DOM_VK_F1: 112, DOM_VK_F2: 113, DOM_VK_F3: 114, DOM_VK_F4: 115, DOM_VK_F5: 116, DOM_VK_F6: 117, DOM_VK_F7: 118, DOM_VK_F8: 119, DOM_VK_F9: 120, DOM_VK_F10: 121, DOM_VK_F11: 122, DOM_VK_F12: 123, DOM_VK_F13: 124, DOM_VK_F14: 125, DOM_VK_F15: 126, DOM_VK_F16: 127, DOM_VK_F17: 128, DOM_VK_F18: 129, DOM_VK_F19: 130, DOM_VK_F20: 131, DOM_VK_F21: 132, DOM_VK_F22: 133, DOM_VK_F23: 134, DOM_VK_F24: 135, DOM_VK_NUM_LOCK: 144, DOM_VK_SCROLL_LOCK: 145, DOM_VK_COMMA: 188, DOM_VK_PERIOD: 190, DOM_VK_SLASH: 191, DOM_VK_BACK_QUOTE: 192, DOM_VK_OPEN_BRACKET: 219, DOM_VK_BACK_SLASH: 220, DOM_VK_CLOSE_BRACKET: 221, DOM_VK_QUOTE: 222, DOM_VK_META: 224 }; } // ************************************************************************************************ // Ajax /** * @namespace */ this.Ajax = { requests: [], transport: null, states: ["Uninitialized","Loading","Loaded","Interactive","Complete"], initialize: function() { this.transport = FBL.getNativeXHRObject(); }, getXHRObject: function() { var xhrObj = false; try { xhrObj = new XMLHttpRequest(); } catch(e) { var progid = [ "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ]; for ( var i=0; i < progid.length; ++i ) { try { xhrObj = new ActiveXObject(progid[i]); } catch(e) { continue; } break; } } finally { return xhrObj; } }, /** * Create a AJAX request. * * @name request * @param {Object} options request options * @param {String} options.url URL to be requested * @param {String} options.type Request type ("get" ou "post"). Default is "get". * @param {Boolean} options.async Asynchronous flag. Default is "true". * @param {String} options.dataType Data type ("text", "html", "xml" or "json"). Default is "text". * @param {String} options.contentType Content-type of the data being sent. Default is "application/x-www-form-urlencoded". * @param {Function} options.onLoading onLoading callback * @param {Function} options.onLoaded onLoaded callback * @param {Function} options.onInteractive onInteractive callback * @param {Function} options.onComplete onComplete callback * @param {Function} options.onUpdate onUpdate callback * @param {Function} options.onSuccess onSuccess callback * @param {Function} options.onFailure onFailure callback */ request: function(options) { // process options var o = FBL.extend( { // default values type: "get", async: true, dataType: "text", contentType: "application/x-www-form-urlencoded" }, options || {} ); this.requests.push(o); var s = this.getState(); if (s == "Uninitialized" || s == "Complete" || s == "Loaded") this.sendRequest(); }, serialize: function(data) { var r = [""], rl = 0; if (data) { if (typeof data == "string") r[rl++] = data; else if (data.innerHTML && data.elements) { for (var i=0,el,l=(el=data.elements).length; i < l; i++) if (el[i].name) { r[rl++] = encodeURIComponent(el[i].name); r[rl++] = "="; r[rl++] = encodeURIComponent(el[i].value); r[rl++] = "&"; } } else for(var param in data) { r[rl++] = encodeURIComponent(param); r[rl++] = "="; r[rl++] = encodeURIComponent(data[param]); r[rl++] = "&"; } } return r.join("").replace(/&$/, ""); }, sendRequest: function() { var t = FBL.Ajax.transport, r = FBL.Ajax.requests.shift(), data; // open XHR object t.open(r.type, r.url, r.async); //setRequestHeaders(); // indicates that it is a XHR request to the server t.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // if data is being sent, sets the appropriate content-type if (data = FBL.Ajax.serialize(r.data)) t.setRequestHeader("Content-Type", r.contentType); /** @ignore */ // onreadystatechange handler t.onreadystatechange = function() { FBL.Ajax.onStateChange(r); }; // send the request t.send(data); }, /** * Handles the state change */ onStateChange: function(options) { var fn, o = options, t = this.transport; var state = this.getState(t); if (fn = o["on" + state]) fn(this.getResponse(o), o); if (state == "Complete") { var success = t.status == 200, response = this.getResponse(o); if (fn = o["onUpdate"]) fn(response, o); if (fn = o["on" + (success ? "Success" : "Failure")]) fn(response, o); t.onreadystatechange = FBL.emptyFn; if (this.requests.length > 0) setTimeout(this.sendRequest, 10); } }, /** * gets the appropriate response value according the type */ getResponse: function(options) { var t = this.transport, type = options.dataType; if (t.status != 200) return t.statusText; else if (type == "text") return t.responseText; else if (type == "html") return t.responseText; else if (type == "xml") return t.responseXML; else if (type == "json") return eval("(" + t.responseText + ")"); }, /** * returns the current state of the XHR object */ getState: function() { return this.states[this.transport.readyState]; } }; // ************************************************************************************************ // Cookie, from http://www.quirksmode.org/js/cookies.html this.createCookie = function(name,value,days) { if ('cookie' in document) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } }; this.readCookie = function (name) { if ('cookie' in document) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } } return null; }; this.removeCookie = function(name) { this.createCookie(name, "", -1); }; // ************************************************************************************************ // http://www.mister-pixel.com/#Content__state=is_that_simple var fixIE6BackgroundImageCache = function(doc) { doc = doc || document; try { doc.execCommand("BackgroundImageCache", false, true); } catch(E) { } }; // ************************************************************************************************ // calculatePixelsPerInch var resetStyle = "margin:0; padding:0; border:0; position:absolute; overflow:hidden; display:block;"; var calculatePixelsPerInch = function calculatePixelsPerInch(doc, body) { var inch = FBL.createGlobalElement("div"); inch.style.cssText = resetStyle + "width:1in; height:1in; position:absolute; top:-1234px; left:-1234px;"; body.appendChild(inch); FBL.pixelsPerInch = { x: inch.offsetWidth, y: inch.offsetHeight }; body.removeChild(inch); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.SourceLink = function(url, line, type, object, instance) { this.href = url; this.instance = instance; this.line = line; this.type = type; this.object = object; }; this.SourceLink.prototype = { toString: function() { return this.href; }, toJSON: function() // until 3.1... { return "{\"href\":\""+this.href+"\", "+ (this.line?("\"line\":"+this.line+","):"")+ (this.type?(" \"type\":\""+this.type+"\","):"")+ "}"; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.SourceText = function(lines, owner) { this.lines = lines; this.owner = owner; }; this.SourceText.getLineAsHTML = function(lineNo) { return escapeForSourceLine(this.lines[lineNo-1]); }; // ************************************************************************************************ }).apply(FBL); /* See license.txt for terms of usage */ FBL.ns( /** @scope s_i18n */ function() { with (FBL) { // ************************************************************************************************ // TODO: xxxpedro localization var oSTR = { "NoMembersWarning": "There are no properties to show for this object.", "EmptyStyleSheet": "There are no rules in this stylesheet.", "EmptyElementCSS": "This element has no style rules.", "AccessRestricted": "Access to restricted URI denied.", "net.label.Parameters": "Parameters", "net.label.Source": "Source", "URLParameters": "Params", "EditStyle": "Edit Element Style...", "NewRule": "New Rule...", "NewProp": "New Property...", "EditProp": 'Edit "%s"', "DeleteProp": 'Delete "%s"', "DisableProp": 'Disable "%s"' }; // ************************************************************************************************ FBL.$STR = function(name) { return oSTR.hasOwnProperty(name) ? oSTR[name] : name; }; FBL.$STRF = function(name, args) { if (!oSTR.hasOwnProperty(name)) return name; var format = oSTR[name]; var objIndex = 0; var parts = parseFormat(format); var trialIndex = objIndex; var objects = args; for (var i= 0; i < parts.length; i++) { var part = parts[i]; if (part && typeof(part) == "object") { if (++trialIndex > objects.length) // then too few parameters for format, assume unformatted. { format = ""; objIndex = -1; parts.length = 0; break; } } } var result = []; for (var i = 0; i < parts.length; ++i) { var part = parts[i]; if (part && typeof(part) == "object") { result.push(""+args.shift()); } else result.push(part); } return result.join(""); }; // ************************************************************************************************ var parseFormat = function parseFormat(format) { var parts = []; if (format.length <= 0) return parts; var reg = /((^%|.%)(\d+)?(\.)([a-zA-Z]))|((^%|.%)([a-zA-Z]))/; for (var m = reg.exec(format); m; m = reg.exec(format)) { if (m[0].substr(0, 2) == "%%") { parts.push(format.substr(0, m.index)); parts.push(m[0].substr(1)); } else { var type = m[8] ? m[8] : m[5]; var precision = m[3] ? parseInt(m[3]) : (m[4] == "." ? -1 : 0); var rep = null; switch (type) { case "s": rep = FirebugReps.Text; break; case "f": case "i": case "d": rep = FirebugReps.Number; break; case "o": rep = null; break; } parts.push(format.substr(0, m[0][0] == "%" ? m.index : m.index+1)); parts.push({rep: rep, precision: precision, type: ("%" + type)}); } format = format.substr(m.index+m[0].length); } parts.push(format); return parts; }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns( /** @scope s_firebug */ function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Internals var modules = []; var panelTypes = []; var panelTypeMap = {}; var reps = []; var parentPanelMap = {}; // ************************************************************************************************ // Firebug /** * @namespace describe Firebug * @exports FBL.Firebug as Firebug */ FBL.Firebug = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * version: "Firebug Lite 1.4.0", revision: "$Revision: 11967 $", // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * modules: modules, panelTypes: panelTypes, panelTypeMap: panelTypeMap, reps: reps, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Initialization initialize: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.initialize", "initializing application"); Firebug.browser = new Context(Env.browser); Firebug.context = Firebug.browser; Firebug.loadPrefs(); Firebug.context.persistedState.isOpen = false; // Document must be cached before chrome initialization cacheDocument(); if (Firebug.Inspector && Firebug.Inspector.create) Firebug.Inspector.create(); if (FBL.CssAnalyzer && FBL.CssAnalyzer.processAllStyleSheets) FBL.CssAnalyzer.processAllStyleSheets(Firebug.browser.document); FirebugChrome.initialize(); dispatch(modules, "initialize", []); if (Firebug.disableResourceFetching) Firebug.Console.logFormatted(["Some Firebug Lite features are not working because " + "resource fetching is disabled. To enabled it set the Firebug Lite option " + "\"disableResourceFetching\" to \"false\". More info at " + "http://getfirebug.com/firebuglite#Options"], Firebug.context, "warn"); if (Env.onLoad) { var onLoad = Env.onLoad; delete Env.onLoad; setTimeout(onLoad, 200); } }, shutdown: function() { if (Firebug.saveCookies) Firebug.savePrefs(); if (Firebug.Inspector) Firebug.Inspector.destroy(); dispatch(modules, "shutdown", []); var chromeMap = FirebugChrome.chromeMap; for (var name in chromeMap) { if (chromeMap.hasOwnProperty(name)) { try { chromeMap[name].destroy(); } catch(E) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("chrome.destroy() failed to: " + name); } } } Firebug.Lite.Cache.Element.clear(); Firebug.Lite.Cache.StyleSheet.clear(); Firebug.browser = null; Firebug.context = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Registration registerModule: function() { modules.push.apply(modules, arguments); if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.registerModule"); }, registerPanel: function() { panelTypes.push.apply(panelTypes, arguments); for (var i = 0, panelType; panelType = arguments[i]; ++i) { panelTypeMap[panelType.prototype.name] = arguments[i]; if (panelType.prototype.parentPanel) parentPanelMap[panelType.prototype.parentPanel] = 1; } if (FBTrace.DBG_INITIALIZE) for (var i = 0; i < arguments.length; ++i) FBTrace.sysout("Firebug.registerPanel", arguments[i].prototype.name); }, registerRep: function() { reps.push.apply(reps, arguments); }, unregisterRep: function() { for (var i = 0; i < arguments.length; ++i) remove(reps, arguments[i]); }, setDefaultReps: function(funcRep, rep) { FBL.defaultRep = rep; FBL.defaultFuncRep = funcRep; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Reps getRep: function(object) { var type = typeof object; if (isIE && isFunction(object)) type = "function"; for (var i = 0; i < reps.length; ++i) { var rep = reps[i]; try { if (rep.supportsObject(object, type)) { if (FBTrace.DBG_DOM) FBTrace.sysout("getRep type: "+type+" object: "+object, rep); return rep; } } catch (exc) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout("firebug.getRep FAILS: ", exc.message || exc); FBTrace.sysout("firebug.getRep reps["+i+"/"+reps.length+"]: Rep="+reps[i].className); // TODO: xxxpedro add trace to FBTrace logs like in Firebug //firebug.trace(); } } } return (type == 'function') ? defaultFuncRep : defaultRep; }, getRepObject: function(node) { var target = null; for (var child = node; child; child = child.parentNode) { if (hasClass(child, "repTarget")) target = child; if (child.repObject) { if (!target && hasClass(child, "repIgnore")) break; else return child.repObject; } } }, getRepNode: function(node) { for (var child = node; child; child = child.parentNode) { if (child.repObject) return child; } }, getElementByRepObject: function(element, object) { for (var child = element.firstChild; child; child = child.nextSibling) { if (child.repObject == object) return child; } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Preferences getPref: function(name) { return Firebug[name]; }, setPref: function(name, value) { Firebug[name] = value; Firebug.savePrefs(); }, setPrefs: function(prefs) { for (var name in prefs) { if (prefs.hasOwnProperty(name)) Firebug[name] = prefs[name]; } Firebug.savePrefs(); }, restorePrefs: function() { var Options = Env.DefaultOptions; for (var name in Options) { Firebug[name] = Options[name]; } }, loadPrefs: function() { this.restorePrefs(); var prefs = Store.get("FirebugLite") || {}; var options = prefs.options; var persistedState = prefs.persistedState || FBL.defaultPersistedState; for (var name in options) { if (options.hasOwnProperty(name)) Firebug[name] = options[name]; } if (Firebug.context && persistedState) Firebug.context.persistedState = persistedState; }, savePrefs: function() { var prefs = { options: {} }; var EnvOptions = Env.Options; var options = prefs.options; for (var name in EnvOptions) { if (EnvOptions.hasOwnProperty(name)) { options[name] = Firebug[name]; } } var persistedState = Firebug.context.persistedState; if (!persistedState) { persistedState = Firebug.context.persistedState = FBL.defaultPersistedState; } prefs.persistedState = persistedState; Store.set("FirebugLite", prefs); }, erasePrefs: function() { Store.remove("FirebugLite"); this.restorePrefs(); } }; Firebug.restorePrefs(); // xxxpedro should we remove this? window.Firebug = FBL.Firebug; if (!Env.Options.enablePersistent || Env.Options.enablePersistent && Env.isChromeContext || Env.isDebugMode) Env.browser.window.Firebug = FBL.Firebug; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Other methods FBL.cacheDocument = function cacheDocument() { var ElementCache = Firebug.Lite.Cache.Element; var els = Firebug.browser.document.getElementsByTagName("*"); for (var i=0, l=els.length, el; i<l; i++) { el = els[i]; ElementCache(el); } }; // ************************************************************************************************ /** * @class * * Support for listeners registration. This object also extended by Firebug.Module so, * all modules supports listening automatically. Notice that array of listeners * is created for each intance of a module within initialize method. Thus all derived * module classes must ensure that Firebug.Module.initialize method is called for the * super class. */ Firebug.Listener = function() { // The array is created when the first listeners is added. // It can't be created here since derived objects would share // the same array. this.fbListeners = null; }; Firebug.Listener.prototype = { addListener: function(listener) { if (!this.fbListeners) this.fbListeners = []; // delay the creation until the objects are created so 'this' causes new array for each module this.fbListeners.push(listener); }, removeListener: function(listener) { remove(this.fbListeners, listener); // if this.fbListeners is null, remove is being called with no add } }; // ************************************************************************************************ // ************************************************************************************************ // Module /** * @module Base class for all modules. Every derived module object must be registered using * <code>Firebug.registerModule</code> method. There is always one instance of a module object * per browser window. * @extends Firebug.Listener */ Firebug.Module = extend(new Firebug.Listener(), /** @extend Firebug.Module */ { /** * Called when the window is opened. */ initialize: function() { }, /** * Called when the window is closed. */ shutdown: function() { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Called when a new context is created but before the page is loaded. */ initContext: function(context) { }, /** * Called after a context is detached to a separate window; */ reattachContext: function(browser, context) { }, /** * Called when a context is destroyed. Module may store info on persistedState for reloaded pages. */ destroyContext: function(context, persistedState) { }, // Called when a FF tab is create or activated (user changes FF tab) // Called after context is created or with context == null (to abort?) showContext: function(browser, context) { }, /** * Called after a context's page gets DOMContentLoaded */ loadedContext: function(context) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * showPanel: function(browser, panel) { }, showSidePanel: function(browser, panel) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * updateOption: function(name, value) { }, getObjectByURL: function(context, url) { } }); // ************************************************************************************************ // Panel /** * @panel Base class for all panels. Every derived panel must define a constructor and * register with "Firebug.registerPanel" method. An instance of the panel * object is created by the framework for each browser tab where Firebug is activated. */ Firebug.Panel = { name: "HelloWorld", title: "Hello World!", parentPanel: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * options: { hasCommandLine: false, hasStatusBar: false, hasToolButtons: false, // Pre-rendered panels are those included in the skin file (firebug.html) isPreRendered: false, innerHTMLSync: false /* // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // To be used by external extensions panelHTML: "", panelCSS: "", toolButtonsHTML: "" /**/ }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * tabNode: null, panelNode: null, sidePanelNode: null, statusBarNode: null, toolButtonsNode: null, panelBarNode: null, sidePanelBarBoxNode: null, sidePanelBarNode: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * sidePanelBar: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * searchable: false, editable: true, order: 2147483647, statusSeparator: "<", create: function(context, doc) { this.hasSidePanel = parentPanelMap.hasOwnProperty(this.name); this.panelBarNode = $("fbPanelBar1"); this.sidePanelBarBoxNode = $("fbPanelBar2"); if (this.hasSidePanel) { this.sidePanelBar = extend({}, PanelBar); this.sidePanelBar.create(this); } var options = this.options = extend(Firebug.Panel.options, this.options); var panelId = "fb" + this.name; if (options.isPreRendered) { this.panelNode = $(panelId); this.tabNode = $(panelId + "Tab"); this.tabNode.style.display = "block"; if (options.hasToolButtons) { this.toolButtonsNode = $(panelId + "Buttons"); } if (options.hasStatusBar) { this.statusBarBox = $("fbStatusBarBox"); this.statusBarNode = $(panelId + "StatusBar"); } } else { var containerSufix = this.parentPanel ? "2" : "1"; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Create Panel var panelNode = this.panelNode = createElement("div", { id: panelId, className: "fbPanel" }); $("fbPanel" + containerSufix).appendChild(panelNode); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Create Panel Tab var tabHTML = '<span class="fbTabL"></span><span class="fbTabText">' + this.title + '</span><span class="fbTabR"></span>'; var tabNode = this.tabNode = createElement("a", { id: panelId + "Tab", className: "fbTab fbHover", innerHTML: tabHTML }); if (isIE6) { tabNode.href = "javascript:void(0)"; } var panelBarNode = this.parentPanel ? Firebug.chrome.getPanel(this.parentPanel).sidePanelBarNode : this.panelBarNode; panelBarNode.appendChild(tabNode); tabNode.style.display = "block"; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create ToolButtons if (options.hasToolButtons) { this.toolButtonsNode = createElement("span", { id: panelId + "Buttons", className: "fbToolbarButtons" }); $("fbToolbarButtons").appendChild(this.toolButtonsNode); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create StatusBar if (options.hasStatusBar) { this.statusBarBox = $("fbStatusBarBox"); this.statusBarNode = createElement("span", { id: panelId + "StatusBar", className: "fbToolbarButtons fbStatusBar" }); this.statusBarBox.appendChild(this.statusBarNode); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create SidePanel } this.containerNode = this.panelNode.parentNode; if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.Panel.create", this.name); // xxxpedro contextMenu this.onContextMenu = bind(this.onContextMenu, this); /* this.context = context; this.document = doc; this.panelNode = doc.createElement("div"); this.panelNode.ownerPanel = this; setClass(this.panelNode, "panelNode panelNode-"+this.name+" contextUID="+context.uid); doc.body.appendChild(this.panelNode); if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("firebug.initialize panelNode for "+this.name+"\n"); this.initializeNode(this.panelNode); /**/ }, destroy: function(state) // Panel may store info on state { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.Panel.destroy", this.name); if (this.hasSidePanel) { this.sidePanelBar.destroy(); this.sidePanelBar = null; } this.options = null; this.name = null; this.parentPanel = null; this.tabNode = null; this.panelNode = null; this.containerNode = null; this.toolButtonsNode = null; this.statusBarBox = null; this.statusBarNode = null; //if (this.panelNode) // delete this.panelNode.ownerPanel; //this.destroyNode(); }, initialize: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.Panel.initialize", this.name); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (this.hasSidePanel) { this.sidePanelBar.initialize(); } var options = this.options = extend(Firebug.Panel.options, this.options); var panelId = "fb" + this.name; this.panelNode = $(panelId); this.tabNode = $(panelId + "Tab"); this.tabNode.style.display = "block"; if (options.hasStatusBar) { this.statusBarBox = $("fbStatusBarBox"); this.statusBarNode = $(panelId + "StatusBar"); } if (options.hasToolButtons) { this.toolButtonsNode = $(panelId + "Buttons"); } this.containerNode = this.panelNode.parentNode; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // restore persistent state this.containerNode.scrollTop = this.lastScrollTop; // xxxpedro contextMenu addEvent(this.containerNode, "contextmenu", this.onContextMenu); /// TODO: xxxpedro infoTip Hack Firebug.chrome.currentPanel = Firebug.chrome.selectedPanel && Firebug.chrome.selectedPanel.sidePanelBar ? Firebug.chrome.selectedPanel.sidePanelBar.selectedPanel : Firebug.chrome.selectedPanel; Firebug.showInfoTips = true; if (Firebug.InfoTip) Firebug.InfoTip.initializeBrowser(Firebug.chrome); }, shutdown: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.Panel.shutdown", this.name); /// TODO: xxxpedro infoTip Hack if (Firebug.InfoTip) Firebug.InfoTip.uninitializeBrowser(Firebug.chrome); if (Firebug.chrome.largeCommandLineVisible) Firebug.chrome.hideLargeCommandLine(); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (this.hasSidePanel) { // TODO: xxxpedro firebug1.3a6 // new PanelBar mechanism will need to call shutdown to hide the panels (so it // doesn't appears in other panel's sidePanelBar. Therefore, we need to implement // a "remember selected panel" feature in the sidePanelBar //this.sidePanelBar.shutdown(); } // store persistent state this.lastScrollTop = this.containerNode.scrollTop; // xxxpedro contextMenu removeEvent(this.containerNode, "contextmenu", this.onContextMenu); }, detach: function(oldChrome, newChrome) { if (oldChrome && oldChrome.selectedPanel && oldChrome.selectedPanel.name == this.name) this.lastScrollTop = oldChrome.selectedPanel.containerNode.scrollTop; }, reattach: function(doc) { if (this.options.innerHTMLSync) this.synchronizeUI(); }, synchronizeUI: function() { this.containerNode.scrollTop = this.lastScrollTop || 0; }, show: function(state) { var options = this.options; if (options.hasStatusBar) { this.statusBarBox.style.display = "inline"; this.statusBarNode.style.display = "inline"; } if (options.hasToolButtons) { this.toolButtonsNode.style.display = "inline"; } this.panelNode.style.display = "block"; this.visible = true; if (!this.parentPanel) Firebug.chrome.layout(this); }, hide: function(state) { var options = this.options; if (options.hasStatusBar) { this.statusBarBox.style.display = "none"; this.statusBarNode.style.display = "none"; } if (options.hasToolButtons) { this.toolButtonsNode.style.display = "none"; } this.panelNode.style.display = "none"; this.visible = false; }, watchWindow: function(win) { }, unwatchWindow: function(win) { }, updateOption: function(name, value) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Toolbar helpers */ showToolbarButtons: function(buttonsId, show) { try { if (!this.context.browser) // XXXjjb this is bug. Somehow the panel context is not FirebugContext. { if (FBTrace.DBG_ERRORS) FBTrace.sysout("firebug.Panel showToolbarButtons this.context has no browser, this:", this); return; } var buttons = this.context.browser.chrome.$(buttonsId); if (buttons) collapse(buttons, show ? "false" : "true"); } catch (exc) { if (FBTrace.DBG_ERRORS) { FBTrace.dumpProperties("firebug.Panel showToolbarButtons FAILS", exc); if (!this.context.browser)FBTrace.dumpStack("firebug.Panel showToolbarButtons no browser"); } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Returns a number indicating the view's ability to inspect the object. * * Zero means not supported, and higher numbers indicate specificity. */ supportsObject: function(object) { return 0; }, hasObject: function(object) // beyond type testing, is this object selectable? { return false; }, select: function(object, forceUpdate) { if (!object) object = this.getDefaultSelection(this.context); if(FBTrace.DBG_PANELS) FBTrace.sysout("firebug.select "+this.name+" forceUpdate: "+forceUpdate+" "+object+((object==this.selection)?"==":"!=")+this.selection); if (forceUpdate || object != this.selection) { this.selection = object; this.updateSelection(object); // TODO: xxxpedro // XXXjoe This is kind of cheating, but, feh. //Firebug.chrome.onPanelSelect(object, this); //if (uiListeners.length > 0) // dispatch(uiListeners, "onPanelSelect", [object, this]); // TODO: make Firebug.chrome a uiListener } }, updateSelection: function(object) { }, markChange: function(skipSelf) { if (this.dependents) { if (skipSelf) { for (var i = 0; i < this.dependents.length; ++i) { var panelName = this.dependents[i]; if (panelName != this.name) this.context.invalidatePanels(panelName); } } else this.context.invalidatePanels.apply(this.context, this.dependents); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * startInspecting: function() { }, stopInspecting: function(object, cancelled) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * search: function(text, reverse) { }, /** * Retrieves the search options that this modules supports. * This is used by the search UI to present the proper options. */ getSearchOptionsMenuItems: function() { return [ Firebug.Search.searchOptionMenu("search.Case Sensitive", "searchCaseSensitive") ]; }, /** * Navigates to the next document whose match parameter returns true. */ navigateToNextDocument: function(match, reverse) { // This is an approximation of the UI that is displayed by the location // selector. This should be close enough, although it may be better // to simply generate the sorted list within the module, rather than // sorting within the UI. var self = this; function compare(a, b) { var locA = self.getObjectDescription(a); var locB = self.getObjectDescription(b); if(locA.path > locB.path) return 1; if(locA.path < locB.path) return -1; if(locA.name > locB.name) return 1; if(locA.name < locB.name) return -1; return 0; } var allLocs = this.getLocationList().sort(compare); for (var curPos = 0; curPos < allLocs.length && allLocs[curPos] != this.location; curPos++); function transformIndex(index) { if (reverse) { // For the reverse case we need to implement wrap around. var intermediate = curPos - index - 1; return (intermediate < 0 ? allLocs.length : 0) + intermediate; } else { return (curPos + index + 1) % allLocs.length; } }; for (var next = 0; next < allLocs.length - 1; next++) { var object = allLocs[transformIndex(next)]; if (match(object)) { this.navigate(object); return object; } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Called when "Options" clicked. Return array of // {label: 'name', nol10n: true, type: "checkbox", checked: <value>, command:function to set <value>} getOptionsMenuItems: function() { return null; }, /* * Called by chrome.onContextMenu to build the context menu when this panel has focus. * See also FirebugRep for a similar function also called by onContextMenu * Extensions may monkey patch and chain off this call * @param object: the 'realObject', a model value, eg a DOM property * @param target: the HTML element clicked on. * @return an array of menu items. */ getContextMenuItems: function(object, target) { return []; }, getBreakOnMenuItems: function() { return []; }, getEditor: function(target, value) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getDefaultSelection: function() { return null; }, browseObject: function(object) { }, getPopupObject: function(target) { return Firebug.getRepObject(target); }, getTooltipObject: function(target) { return Firebug.getRepObject(target); }, showInfoTip: function(infoTip, x, y) { }, getObjectPath: function(object) { return null; }, // An array of objects that can be passed to getObjectLocation. // The list of things a panel can show, eg sourceFiles. // Only shown if panel.location defined and supportsObject true getLocationList: function() { return null; }, getDefaultLocation: function() { return null; }, getObjectLocation: function(object) { return ""; }, // Text for the location list menu eg script panel source file list // return.path: group/category label, return.name: item label getObjectDescription: function(object) { var url = this.getObjectLocation(object); return FBL.splitURLBase(url); }, /* * UI signal that a tab needs attention, eg Script panel is currently stopped on a breakpoint * @param: show boolean, true turns on. */ highlight: function(show) { var tab = this.getTab(); if (!tab) return; if (show) tab.setAttribute("highlight", "true"); else tab.removeAttribute("highlight"); }, getTab: function() { var chrome = Firebug.chrome; var tab = chrome.$("fbPanelBar2").getTab(this.name); if (!tab) tab = chrome.$("fbPanelBar1").getTab(this.name); return tab; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Support for Break On Next /** * Called by the framework when the user clicks on the Break On Next button. * @param {Boolean} armed Set to true if the Break On Next feature is * to be armed for action and set to false if the Break On Next should be disarmed. * If 'armed' is true, then the next call to shouldBreakOnNext should be |true|. */ breakOnNext: function(armed) { }, /** * Called when a panel is selected/displayed. The method should return true * if the Break On Next feature is currently armed for this panel. */ shouldBreakOnNext: function() { return false; }, /** * Returns labels for Break On Next tooltip (one for enabled and one for disabled state). * @param {Boolean} enabled Set to true if the Break On Next feature is * currently activated for this panel. */ getBreakOnNextTooltip: function(enabled) { return null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // xxxpedro contextMenu onContextMenu: function(event) { if (!this.getContextMenuItems) return; cancelEvent(event, true); var target = event.target || event.srcElement; var menu = this.getContextMenuItems(this.selection, target); if (!menu) return; var contextMenu = new Menu( { id: "fbPanelContextMenu", items: menu }); contextMenu.show(event.clientX, event.clientY); return true; /* // TODO: xxxpedro move code to somewhere. code to get cross-browser // window to screen coordinates var box = Firebug.browser.getElementPosition(Firebug.chrome.node); var screenY = 0; // Firefox if (typeof window.mozInnerScreenY != "undefined") { screenY = window.mozInnerScreenY; } // Chrome else if (typeof window.innerHeight != "undefined") { screenY = window.outerHeight - window.innerHeight; } // IE else if (typeof window.screenTop != "undefined") { screenY = window.screenTop; } contextMenu.show(event.screenX-box.left, event.screenY-screenY-box.top); /**/ } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * MeasureBox * To get pixels size.width and size.height: * <ul><li> this.startMeasuring(view); </li> * <li> var size = this.measureText(lineNoCharsSpacer); </li> * <li> this.stopMeasuring(); </li> * </ul> * * @namespace */ Firebug.MeasureBox = { startMeasuring: function(target) { if (!this.measureBox) { this.measureBox = target.ownerDocument.createElement("span"); this.measureBox.className = "measureBox"; } copyTextStyles(target, this.measureBox); target.ownerDocument.body.appendChild(this.measureBox); }, getMeasuringElement: function() { return this.measureBox; }, measureText: function(value) { this.measureBox.innerHTML = value ? escapeForSourceLine(value) : "m"; return {width: this.measureBox.offsetWidth, height: this.measureBox.offsetHeight-1}; }, measureInputText: function(value) { value = value ? escapeForTextNode(value) : "m"; if (!Firebug.showTextNodesWithWhitespace) value = value.replace(/\t/g,'mmmmmm').replace(/\ /g,'m'); this.measureBox.innerHTML = value; return {width: this.measureBox.offsetWidth, height: this.measureBox.offsetHeight-1}; }, getBox: function(target) { var style = this.measureBox.ownerDocument.defaultView.getComputedStyle(this.measureBox, ""); var box = getBoxFromStyles(style, this.measureBox); return box; }, stopMeasuring: function() { this.measureBox.parentNode.removeChild(this.measureBox); } }; // ************************************************************************************************ if (FBL.domplate) Firebug.Rep = domplate( { className: "", inspectable: true, supportsObject: function(object, type) { return false; }, inspectObject: function(object, context) { Firebug.chrome.select(object); }, browseObject: function(object, context) { }, persistObject: function(object, context) { }, getRealObject: function(object, context) { return object; }, getTitle: function(object) { var label = safeToString(object); var re = /\[object (.*?)\]/; var m = re.exec(label); ///return m ? m[1] : label; // if the label is in the "[object TYPE]" format return its type if (m) { return m[1]; } // if it is IE we need to handle some special cases else if ( // safeToString() fails to recognize some objects in IE isIE && // safeToString() returns "[object]" for some objects like window.Image (label == "[object]" || // safeToString() returns undefined for some objects like window.clientInformation typeof object == "object" && typeof label == "undefined") ) { return "Object"; } else { return label; } }, getTooltip: function(object) { return null; }, getContextMenuItems: function(object, target, context) { return []; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Convenience for domplates STR: function(name) { return $STR(name); }, cropString: function(text) { return cropString(text); }, cropMultipleLines: function(text, limit) { return cropMultipleLines(text, limit); }, toLowerCase: function(text) { return text ? text.toLowerCase() : text; }, plural: function(n) { return n == 1 ? "" : "s"; } }); // ************************************************************************************************ // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns( /** @scope s_gui */ function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Controller /**@namespace*/ FBL.Controller = { controllers: null, controllerContext: null, initialize: function(context) { this.controllers = []; this.controllerContext = context || Firebug.chrome; }, shutdown: function() { this.removeControllers(); //this.controllers = null; //this.controllerContext = null; }, addController: function() { for (var i=0, arg; arg=arguments[i]; i++) { // If the first argument is a string, make a selector query // within the controller node context if (typeof arg[0] == "string") { arg[0] = $$(arg[0], this.controllerContext); } // bind the handler to the proper context var handler = arg[2]; arg[2] = bind(handler, this); // save the original handler as an extra-argument, so we can // look for it later, when removing a particular controller arg[3] = handler; this.controllers.push(arg); addEvent.apply(this, arg); } }, removeController: function() { for (var i=0, arg; arg=arguments[i]; i++) { for (var j=0, c; c=this.controllers[j]; j++) { if (arg[0] == c[0] && arg[1] == c[1] && arg[2] == c[3]) removeEvent.apply(this, c); } } }, removeControllers: function() { for (var i=0, c; c=this.controllers[i]; i++) { removeEvent.apply(this, c); } } }; // ************************************************************************************************ // PanelBar /**@namespace*/ FBL.PanelBar = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * panelMap: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * selectedPanel: null, parentPanelName: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * create: function(ownerPanel) { this.panelMap = {}; this.ownerPanel = ownerPanel; if (ownerPanel) { ownerPanel.sidePanelBarNode = createElement("span"); ownerPanel.sidePanelBarNode.style.display = "none"; ownerPanel.sidePanelBarBoxNode.appendChild(ownerPanel.sidePanelBarNode); } var panels = Firebug.panelTypes; for (var i=0, p; p=panels[i]; i++) { if ( // normal Panel of the Chrome's PanelBar !ownerPanel && !p.prototype.parentPanel || // Child Panel of the current Panel's SidePanelBar ownerPanel && p.prototype.parentPanel && ownerPanel.name == p.prototype.parentPanel) { this.addPanel(p.prototype.name); } } }, destroy: function() { PanelBar.shutdown.call(this); for (var name in this.panelMap) { this.removePanel(name); var panel = this.panelMap[name]; panel.destroy(); this.panelMap[name] = null; delete this.panelMap[name]; } this.panelMap = null; this.ownerPanel = null; }, initialize: function() { if (this.ownerPanel) this.ownerPanel.sidePanelBarNode.style.display = "inline"; for(var name in this.panelMap) { (function(self, name){ // tab click handler var onTabClick = function onTabClick() { self.selectPanel(name); return false; }; Firebug.chrome.addController([self.panelMap[name].tabNode, "mousedown", onTabClick]); })(this, name); } }, shutdown: function() { var selectedPanel = this.selectedPanel; if (selectedPanel) { removeClass(selectedPanel.tabNode, "fbSelectedTab"); selectedPanel.hide(); selectedPanel.shutdown(); } if (this.ownerPanel) this.ownerPanel.sidePanelBarNode.style.display = "none"; this.selectedPanel = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * addPanel: function(panelName, parentPanel) { var PanelType = Firebug.panelTypeMap[panelName]; var panel = this.panelMap[panelName] = new PanelType(); panel.create(); }, removePanel: function(panelName) { var panel = this.panelMap[panelName]; if (panel.hasOwnProperty(panelName)) panel.destroy(); }, selectPanel: function(panelName) { var selectedPanel = this.selectedPanel; var panel = this.panelMap[panelName]; if (panel && selectedPanel != panel) { if (selectedPanel) { removeClass(selectedPanel.tabNode, "fbSelectedTab"); selectedPanel.shutdown(); selectedPanel.hide(); } if (!panel.parentPanel) Firebug.context.persistedState.selectedPanelName = panelName; this.selectedPanel = panel; setClass(panel.tabNode, "fbSelectedTab"); panel.show(); panel.initialize(); } }, getPanel: function(panelName) { var panel = this.panelMap[panelName]; return panel; } }; //************************************************************************************************ // Button /** * options.element * options.caption * options.title * * options.owner * options.className * options.pressedClassName * * options.onPress * options.onUnpress * options.onClick * * @class * @extends FBL.Controller * */ FBL.Button = function(options) { options = options || {}; append(this, options); this.state = "unpressed"; this.display = "unpressed"; if (this.element) { this.container = this.element.parentNode; } else { this.shouldDestroy = true; this.container = this.owner.getPanel().toolButtonsNode; this.element = createElement("a", { className: this.baseClassName + " " + this.className + " fbHover", innerHTML: this.caption }); if (this.title) this.element.title = this.title; this.container.appendChild(this.element); } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Button.prototype = extend(Controller, /**@extend FBL.Button.prototype*/ { type: "normal", caption: "caption", title: null, className: "", // custom class baseClassName: "fbButton", // control class pressedClassName: "fbBtnPressed", // control pressed class element: null, container: null, owner: null, state: null, display: null, destroy: function() { this.shutdown(); // only remove if it is a dynamically generated button (not pre-rendered) if (this.shouldDestroy) this.container.removeChild(this.element); this.element = null; this.container = null; this.owner = null; }, initialize: function() { Controller.initialize.apply(this); var element = this.element; this.addController([element, "mousedown", this.handlePress]); if (this.type == "normal") this.addController( [element, "mouseup", this.handleUnpress], [element, "mouseout", this.handleUnpress], [element, "click", this.handleClick] ); }, shutdown: function() { Controller.shutdown.apply(this); }, restore: function() { this.changeState("unpressed"); }, changeState: function(state) { this.state = state; this.changeDisplay(state); }, changeDisplay: function(display) { if (display != this.display) { if (display == "pressed") { setClass(this.element, this.pressedClassName); } else if (display == "unpressed") { removeClass(this.element, this.pressedClassName); } this.display = display; } }, handlePress: function(event) { cancelEvent(event, true); if (this.type == "normal") { this.changeDisplay("pressed"); this.beforeClick = true; } else if (this.type == "toggle") { if (this.state == "pressed") { this.changeState("unpressed"); if (this.onUnpress) this.onUnpress.apply(this.owner, arguments); } else { this.changeState("pressed"); if (this.onPress) this.onPress.apply(this.owner, arguments); } if (this.onClick) this.onClick.apply(this.owner, arguments); } return false; }, handleUnpress: function(event) { cancelEvent(event, true); if (this.beforeClick) this.changeDisplay("unpressed"); return false; }, handleClick: function(event) { cancelEvent(event, true); if (this.type == "normal") { if (this.onClick) this.onClick.apply(this.owner); this.changeState("unpressed"); } this.beforeClick = false; return false; } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * @class * @extends FBL.Button */ FBL.IconButton = function() { Button.apply(this, arguments); }; IconButton.prototype = extend(Button.prototype, /**@extend FBL.IconButton.prototype*/ { baseClassName: "fbIconButton", pressedClassName: "fbIconPressed" }); //************************************************************************************************ // Menu var menuItemProps = {"class": "$item.className", type: "$item.type", value: "$item.value", _command: "$item.command"}; if (isIE6) menuItemProps.href = "javascript:void(0)"; // Allow GUI to be loaded even when Domplate module is not installed. if (FBL.domplate) var MenuPlate = domplate(Firebug.Rep, { tag: DIV({"class": "fbMenu fbShadow"}, DIV({"class": "fbMenuContent fbShadowContent"}, FOR("item", "$object.items|memberIterator", TAG("$item.tag", {item: "$item"}) ) ) ), itemTag: A(menuItemProps, "$item.label" ), checkBoxTag: A(extend(menuItemProps, {checked : "$item.checked"}), "$item.label" ), radioButtonTag: A(extend(menuItemProps, {selected : "$item.selected"}), "$item.label" ), groupTag: A(extend(menuItemProps, {child: "$item.child"}), "$item.label" ), shortcutTag: A(menuItemProps, "$item.label", SPAN({"class": "fbMenuShortcutKey"}, "$item.key" ) ), separatorTag: SPAN({"class": "fbMenuSeparator"}), memberIterator: function(items) { var result = []; for (var i=0, length=items.length; i<length; i++) { var item = items[i]; // separator representation if (typeof item == "string" && item.indexOf("-") == 0) { result.push({tag: this.separatorTag}); continue; } item = extend(item, {}); item.type = item.type || ""; item.value = item.value || ""; var type = item.type; // default item representation item.tag = this.itemTag; var className = item.className || ""; className += "fbMenuOption fbHover "; // specific representations if (type == "checkbox") { className += "fbMenuCheckBox "; item.tag = this.checkBoxTag; } else if (type == "radiobutton") { className += "fbMenuRadioButton "; item.tag = this.radioButtonTag; } else if (type == "group") { className += "fbMenuGroup "; item.tag = this.groupTag; } else if (type == "shortcut") { className += "fbMenuShortcut "; item.tag = this.shortcutTag; } if (item.checked) className += "fbMenuChecked "; else if (item.selected) className += "fbMenuRadioSelected "; if (item.disabled) className += "fbMenuDisabled "; item.className = className; item.label = $STR(item.label); result.push(item); } return result; } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * options * options.element * options.id * options.items * * item.label * item.className * item.type * item.value * item.disabled * item.checked * item.selected * item.command * item.child * * * @class * @extends FBL.Controller * */ FBL.Menu = function(options) { // if element is not pre-rendered, we must render it now if (!options.element) { if (options.getItems) options.items = options.getItems(); options.element = MenuPlate.tag.append( {object: options}, getElementByClass(Firebug.chrome.document, "fbBody"), MenuPlate ); } // extend itself with the provided options append(this, options); if (typeof this.element == "string") { this.id = this.element; this.element = $(this.id); } else if (this.id) { this.element.id = this.id; } this.element.firebugIgnore = true; this.elementStyle = this.element.style; this.isVisible = false; this.handleMouseDown = bind(this.handleMouseDown, this); this.handleMouseOver = bind(this.handleMouseOver, this); this.handleMouseOut = bind(this.handleMouseOut, this); this.handleWindowMouseDown = bind(this.handleWindowMouseDown, this); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var menuMap = {}; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Menu.prototype = extend(Controller, /**@extend FBL.Menu.prototype*/ { destroy: function() { //if (this.element) console.log("destroy", this.element.id); this.hide(); // if it is a childMenu, remove its reference from the parentMenu if (this.parentMenu) this.parentMenu.childMenu = null; // remove the element from the document this.element.parentNode.removeChild(this.element); // clear references this.element = null; this.elementStyle = null; this.parentMenu = null; this.parentTarget = null; }, initialize: function() { Controller.initialize.call(this); this.addController( [this.element, "mousedown", this.handleMouseDown], [this.element, "mouseover", this.handleMouseOver] ); }, shutdown: function() { Controller.shutdown.call(this); }, show: function(x, y) { this.initialize(); if (this.isVisible) return; //console.log("show", this.element.id); x = x || 0; y = y || 0; if (this.parentMenu) { var oldChildMenu = this.parentMenu.childMenu; if (oldChildMenu && oldChildMenu != this) { oldChildMenu.destroy(); } this.parentMenu.childMenu = this; } else addEvent(Firebug.chrome.document, "mousedown", this.handleWindowMouseDown); this.elementStyle.display = "block"; this.elementStyle.visibility = "hidden"; var size = Firebug.chrome.getSize(); x = Math.min(x, size.width - this.element.clientWidth - 10); x = Math.max(x, 0); y = Math.min(y, size.height - this.element.clientHeight - 10); y = Math.max(y, 0); this.elementStyle.left = x + "px"; this.elementStyle.top = y + "px"; this.elementStyle.visibility = "visible"; this.isVisible = true; if (isFunction(this.onShow)) this.onShow.apply(this, arguments); }, hide: function() { this.clearHideTimeout(); this.clearShowChildTimeout(); if (!this.isVisible) return; //console.log("hide", this.element.id); this.elementStyle.display = "none"; if(this.childMenu) { this.childMenu.destroy(); this.childMenu = null; } if(this.parentTarget) removeClass(this.parentTarget, "fbMenuGroupSelected"); this.isVisible = false; this.shutdown(); if (isFunction(this.onHide)) this.onHide.apply(this, arguments); }, showChildMenu: function(target) { var id = target.getAttribute("child"); var parent = this; var target = target; this.showChildTimeout = Firebug.chrome.window.setTimeout(function(){ //if (!parent.isVisible) return; var box = Firebug.chrome.getElementBox(target); var childMenuObject = menuMap.hasOwnProperty(id) ? menuMap[id] : {element: $(id)}; var childMenu = new Menu(extend(childMenuObject, { parentMenu: parent, parentTarget: target })); var offsetLeft = isIE6 ? -1 : -6; // IE6 problem with fixed position childMenu.show(box.left + box.width + offsetLeft, box.top -6); setClass(target, "fbMenuGroupSelected"); },350); }, clearHideTimeout: function() { if (this.hideTimeout) { Firebug.chrome.window.clearTimeout(this.hideTimeout); delete this.hideTimeout; } }, clearShowChildTimeout: function() { if(this.showChildTimeout) { Firebug.chrome.window.clearTimeout(this.showChildTimeout); this.showChildTimeout = null; } }, handleMouseDown: function(event) { cancelEvent(event, true); var topParent = this; while (topParent.parentMenu) topParent = topParent.parentMenu; var target = event.target || event.srcElement; target = getAncestorByClass(target, "fbMenuOption"); if(!target || hasClass(target, "fbMenuGroup")) return false; if (target && !hasClass(target, "fbMenuDisabled")) { var type = target.getAttribute("type"); if (type == "checkbox") { var checked = target.getAttribute("checked"); var value = target.getAttribute("value"); var wasChecked = hasClass(target, "fbMenuChecked"); if (wasChecked) { removeClass(target, "fbMenuChecked"); target.setAttribute("checked", ""); } else { setClass(target, "fbMenuChecked"); target.setAttribute("checked", "true"); } if (isFunction(this.onCheck)) this.onCheck.call(this, target, value, !wasChecked); } if (type == "radiobutton") { var selectedRadios = getElementsByClass(target.parentNode, "fbMenuRadioSelected"); var group = target.getAttribute("group"); for (var i = 0, length = selectedRadios.length; i < length; i++) { radio = selectedRadios[i]; if (radio.getAttribute("group") == group) { removeClass(radio, "fbMenuRadioSelected"); radio.setAttribute("selected", ""); } } setClass(target, "fbMenuRadioSelected"); target.setAttribute("selected", "true"); } var handler = null; // target.command can be a function or a string. var cmd = target.command; // If it is a function it will be used as the handler if (isFunction(cmd)) handler = cmd; // If it is a string it the property of the current menu object // will be used as the handler else if (typeof cmd == "string") handler = this[cmd]; var closeMenu = true; if (handler) closeMenu = handler.call(this, target) !== false; if (closeMenu) topParent.hide(); } return false; }, handleWindowMouseDown: function(event) { //console.log("handleWindowMouseDown"); var target = event.target || event.srcElement; target = getAncestorByClass(target, "fbMenu"); if (!target) { removeEvent(Firebug.chrome.document, "mousedown", this.handleWindowMouseDown); this.hide(); } }, handleMouseOver: function(event) { //console.log("handleMouseOver", this.element.id); this.clearHideTimeout(); this.clearShowChildTimeout(); var target = event.target || event.srcElement; target = getAncestorByClass(target, "fbMenuOption"); if(!target) return; var childMenu = this.childMenu; if(childMenu) { removeClass(childMenu.parentTarget, "fbMenuGroupSelected"); if (childMenu.parentTarget != target && childMenu.isVisible) { childMenu.clearHideTimeout(); childMenu.hideTimeout = Firebug.chrome.window.setTimeout(function(){ childMenu.destroy(); },300); } } if(hasClass(target, "fbMenuGroup")) { this.showChildMenu(target); } } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * append(Menu, /**@extend FBL.Menu*/ { register: function(object) { menuMap[object.id] = object; }, check: function(element) { setClass(element, "fbMenuChecked"); element.setAttribute("checked", "true"); }, uncheck: function(element) { removeClass(element, "fbMenuChecked"); element.setAttribute("checked", ""); }, disable: function(element) { setClass(element, "fbMenuDisabled"); }, enable: function(element) { removeClass(element, "fbMenuDisabled"); } }); //************************************************************************************************ // Status Bar /**@class*/ function StatusBar(){}; StatusBar.prototype = extend(Controller, { }); // ************************************************************************************************ // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns( /**@scope s_context*/ function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals var refreshDelay = 300; // Opera and some versions of webkit returns the wrong value of document.elementFromPoint() // function, without taking into account the scroll position. Safari 4 (webkit/531.21.8) // still have this issue. Google Chrome 4 (webkit/532.5) does not. So, we're assuming this // issue was fixed in the 532 version var shouldFixElementFromPoint = isOpera || isSafari && browserVersion < "532"; var evalError = "___firebug_evaluation_error___"; var pixelsPerInch; var resetStyle = "margin:0; padding:0; border:0; position:absolute; overflow:hidden; display:block;"; var offscreenStyle = resetStyle + "top:-1234px; left:-1234px;"; // ************************************************************************************************ // Context /** @class */ FBL.Context = function(win) { this.window = win.window; this.document = win.document; this.browser = Env.browser; // Some windows in IE, like iframe, doesn't have the eval() method if (isIE && !this.window.eval) { // But after executing the following line the method magically appears! this.window.execScript("null"); // Just to make sure the "magic" really happened if (!this.window.eval) throw new Error("Firebug Error: eval() method not found in this window"); } // Create a new "black-box" eval() method that runs in the global namespace // of the context window, without exposing the local variables declared // by the function that calls it this.eval = this.window.eval("new Function('" + "try{ return window.eval.apply(window,arguments) }catch(E){ E."+evalError+"=true; return E }" + "')"); }; FBL.Context.prototype = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // partial-port of Firebug tabContext.js browser: null, loaded: true, setTimeout: function(fn, delay) { var win = this.window; if (win.setTimeout == this.setTimeout) throw new Error("setTimeout recursion"); var timeout = win.setTimeout.apply ? // IE doesn't have apply method on setTimeout win.setTimeout.apply(win, arguments) : win.setTimeout(fn, delay); if (!this.timeouts) this.timeouts = {}; this.timeouts[timeout] = 1; return timeout; }, clearTimeout: function(timeout) { clearTimeout(timeout); if (this.timeouts) delete this.timeouts[timeout]; }, setInterval: function(fn, delay) { var win = this.window; var timeout = win.setInterval.apply ? // IE doesn't have apply method on setTimeout win.setInterval.apply(win, arguments) : win.setInterval(fn, delay); if (!this.intervals) this.intervals = {}; this.intervals[timeout] = 1; return timeout; }, clearInterval: function(timeout) { clearInterval(timeout); if (this.intervals) delete this.intervals[timeout]; }, invalidatePanels: function() { if (!this.invalidPanels) this.invalidPanels = {}; for (var i = 0; i < arguments.length; ++i) { var panelName = arguments[i]; // avoid error. need to create a better getPanel() function as explained below if (!Firebug.chrome || !Firebug.chrome.selectedPanel) return; //var panel = this.getPanel(panelName, true); //TODO: xxxpedro context how to get all panels using a single function? // the current workaround to make the invalidation works is invalidating // only sidePanels. There's also a problem with panel name (LowerCase in Firebug Lite) var panel = Firebug.chrome.selectedPanel.sidePanelBar ? Firebug.chrome.selectedPanel.sidePanelBar.getPanel(panelName, true) : null; if (panel && !panel.noRefresh) this.invalidPanels[panelName] = 1; } if (this.refreshTimeout) { this.clearTimeout(this.refreshTimeout); delete this.refreshTimeout; } this.refreshTimeout = this.setTimeout(bindFixed(function() { var invalids = []; for (var panelName in this.invalidPanels) { //var panel = this.getPanel(panelName, true); //TODO: xxxpedro context how to get all panels using a single function? // the current workaround to make the invalidation works is invalidating // only sidePanels. There's also a problem with panel name (LowerCase in Firebug Lite) var panel = Firebug.chrome.selectedPanel.sidePanelBar ? Firebug.chrome.selectedPanel.sidePanelBar.getPanel(panelName, true) : null; if (panel) { if (panel.visible && !panel.editing) panel.refresh(); else panel.needsRefresh = true; // If the panel is being edited, we'll keep trying to // refresh it until editing is done if (panel.editing) invalids.push(panelName); } } delete this.invalidPanels; delete this.refreshTimeout; // Keep looping until every tab is valid if (invalids.length) this.invalidatePanels.apply(this, invalids); }, this), refreshDelay); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Evalutation Method /** * Evaluates an expression in the current context window. * * @param {String} expr expression to be evaluated * * @param {String} context string indicating the global location * of the object that will be used as the * context. The context is referred in * the expression as the "this" keyword. * If no context is informed, the "window" * context is used. * * @param {String} api string indicating the global location * of the object that will be used as the * api of the evaluation. * * @param {Function} errorHandler(message) error handler to be called * if the evaluation fails. */ evaluate: function(expr, context, api, errorHandler) { // the default context is the "window" object. It can be any string that represents // a global accessible element as: "my.namespaced.object" context = context || "window"; var isObjectLiteral = trim(expr).indexOf("{") == 0, cmd, result; // if the context is the "window" object, we don't need a closure if (context == "window") { // If it is an object literal, then wrap the expression with parenthesis so we can // capture the return value if (isObjectLiteral) { cmd = api ? "with("+api+"){ ("+expr+") }" : "(" + expr + ")"; } else { cmd = api ? "with("+api+"){ "+expr+" }" : expr; } } else { cmd = api ? // with API and context, no return value "(function(arguments){ with(" + api + "){ " + expr + " } }).call(" + context + ",undefined)" : // with context only, no return value "(function(arguments){ " + expr + " }).call(" + context + ",undefined)"; } result = this.eval(cmd); if (result && result[evalError]) { var msg = result.name ? (result.name + ": ") : ""; msg += result.message || result; if (errorHandler) result = errorHandler(msg); else result = msg; } return result; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Window Methods getWindowSize: function() { var width=0, height=0, el; if (typeof this.window.innerWidth == "number") { width = this.window.innerWidth; height = this.window.innerHeight; } else if ((el=this.document.documentElement) && (el.clientHeight || el.clientWidth)) { width = el.clientWidth; height = el.clientHeight; } else if ((el=this.document.body) && (el.clientHeight || el.clientWidth)) { width = el.clientWidth; height = el.clientHeight; } return {width: width, height: height}; }, getWindowScrollSize: function() { var width=0, height=0, el; // first try the document.documentElement scroll size if (!isIEQuiksMode && (el=this.document.documentElement) && (el.scrollHeight || el.scrollWidth)) { width = el.scrollWidth; height = el.scrollHeight; } // then we need to check if document.body has a bigger scroll size value // because sometimes depending on the browser and the page, the document.body // scroll size returns a smaller (and wrong) measure if ((el=this.document.body) && (el.scrollHeight || el.scrollWidth) && (el.scrollWidth > width || el.scrollHeight > height)) { width = el.scrollWidth; height = el.scrollHeight; } return {width: width, height: height}; }, getWindowScrollPosition: function() { var top=0, left=0, el; if(typeof this.window.pageYOffset == "number") { top = this.window.pageYOffset; left = this.window.pageXOffset; } else if((el=this.document.body) && (el.scrollTop || el.scrollLeft)) { top = el.scrollTop; left = el.scrollLeft; } else if((el=this.document.documentElement) && (el.scrollTop || el.scrollLeft)) { top = el.scrollTop; left = el.scrollLeft; } return {top:top, left:left}; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Element Methods getElementFromPoint: function(x, y) { if (shouldFixElementFromPoint) { var scroll = this.getWindowScrollPosition(); return this.document.elementFromPoint(x + scroll.left, y + scroll.top); } else return this.document.elementFromPoint(x, y); }, getElementPosition: function(el) { var left = 0; var top = 0; do { left += el.offsetLeft; top += el.offsetTop; } while (el = el.offsetParent); return {left:left, top:top}; }, getElementBox: function(el) { var result = {}; if (el.getBoundingClientRect) { var rect = el.getBoundingClientRect(); // fix IE problem with offset when not in fullscreen mode var offset = isIE ? this.document.body.clientTop || this.document.documentElement.clientTop: 0; var scroll = this.getWindowScrollPosition(); result.top = Math.round(rect.top - offset + scroll.top); result.left = Math.round(rect.left - offset + scroll.left); result.height = Math.round(rect.bottom - rect.top); result.width = Math.round(rect.right - rect.left); } else { var position = this.getElementPosition(el); result.top = position.top; result.left = position.left; result.height = el.offsetHeight; result.width = el.offsetWidth; } return result; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Measurement Methods getMeasurement: function(el, name) { var result = {value: 0, unit: "px"}; var cssValue = this.getStyle(el, name); if (!cssValue) return result; if (cssValue.toLowerCase() == "auto") return result; var reMeasure = /(\d+\.?\d*)(.*)/; var m = cssValue.match(reMeasure); if (m) { result.value = m[1]-0; result.unit = m[2].toLowerCase(); } return result; }, getMeasurementInPixels: function(el, name) { if (!el) return null; var m = this.getMeasurement(el, name); var value = m.value; var unit = m.unit; if (unit == "px") return value; else if (unit == "pt") return this.pointsToPixels(name, value); else if (unit == "em") return this.emToPixels(el, value); else if (unit == "%") return this.percentToPixels(el, value); else if (unit == "ex") return this.exToPixels(el, value); // TODO: add other units. Maybe create a better general way // to calculate measurements in different units. }, getMeasurementBox1: function(el, name) { var sufixes = ["Top", "Left", "Bottom", "Right"]; var result = []; for(var i=0, sufix; sufix=sufixes[i]; i++) result[i] = Math.round(this.getMeasurementInPixels(el, name + sufix)); return {top:result[0], left:result[1], bottom:result[2], right:result[3]}; }, getMeasurementBox: function(el, name) { var result = []; var sufixes = name == "border" ? ["TopWidth", "LeftWidth", "BottomWidth", "RightWidth"] : ["Top", "Left", "Bottom", "Right"]; if (isIE) { var propName, cssValue; var autoMargin = null; for(var i=0, sufix; sufix=sufixes[i]; i++) { propName = name + sufix; cssValue = el.currentStyle[propName] || el.style[propName]; if (cssValue == "auto") { if (!autoMargin) autoMargin = this.getCSSAutoMarginBox(el); result[i] = autoMargin[sufix.toLowerCase()]; } else result[i] = this.getMeasurementInPixels(el, propName); } } else { for(var i=0, sufix; sufix=sufixes[i]; i++) result[i] = this.getMeasurementInPixels(el, name + sufix); } return {top:result[0], left:result[1], bottom:result[2], right:result[3]}; }, getCSSAutoMarginBox: function(el) { if (isIE && " meta title input script link a ".indexOf(" "+el.nodeName.toLowerCase()+" ") != -1) return {top:0, left:0, bottom:0, right:0}; /**/ if (isIE && " h1 h2 h3 h4 h5 h6 h7 ul p ".indexOf(" "+el.nodeName.toLowerCase()+" ") == -1) return {top:0, left:0, bottom:0, right:0}; /**/ var offsetTop = 0; if (false && isIEStantandMode) { var scrollSize = Firebug.browser.getWindowScrollSize(); offsetTop = scrollSize.height; } var box = this.document.createElement("div"); //box.style.cssText = "margin:0; padding:1px; border: 0; position:static; overflow:hidden; visibility: hidden;"; box.style.cssText = "margin:0; padding:1px; border: 0; visibility: hidden;"; var clone = el.cloneNode(false); var text = this.document.createTextNode("&nbsp;"); clone.appendChild(text); box.appendChild(clone); this.document.body.appendChild(box); var marginTop = clone.offsetTop - box.offsetTop - 1; var marginBottom = box.offsetHeight - clone.offsetHeight - 2 - marginTop; var marginLeft = clone.offsetLeft - box.offsetLeft - 1; var marginRight = box.offsetWidth - clone.offsetWidth - 2 - marginLeft; this.document.body.removeChild(box); return {top:marginTop+offsetTop, left:marginLeft, bottom:marginBottom-offsetTop, right:marginRight}; }, getFontSizeInPixels: function(el) { var size = this.getMeasurement(el, "fontSize"); if (size.unit == "px") return size.value; // get font size, the dirty way var computeDirtyFontSize = function(el, calibration) { var div = this.document.createElement("div"); var divStyle = offscreenStyle; if (calibration) divStyle += " font-size:"+calibration+"px;"; div.style.cssText = divStyle; div.innerHTML = "A"; el.appendChild(div); var value = div.offsetHeight; el.removeChild(div); return value; }; /* var calibrationBase = 200; var calibrationValue = computeDirtyFontSize(el, calibrationBase); var rate = calibrationBase / calibrationValue; /**/ // the "dirty technique" fails in some environments, so we're using a static value // based in some tests. var rate = 200 / 225; var value = computeDirtyFontSize(el); return value * rate; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Unit Funtions pointsToPixels: function(name, value, returnFloat) { var axis = /Top$|Bottom$/.test(name) ? "y" : "x"; var result = value * pixelsPerInch[axis] / 72; return returnFloat ? result : Math.round(result); }, emToPixels: function(el, value) { if (!el) return null; var fontSize = this.getFontSizeInPixels(el); return Math.round(value * fontSize); }, exToPixels: function(el, value) { if (!el) return null; // get ex value, the dirty way var div = this.document.createElement("div"); div.style.cssText = offscreenStyle + "width:"+value + "ex;"; el.appendChild(div); var value = div.offsetWidth; el.removeChild(div); return value; }, percentToPixels: function(el, value) { if (!el) return null; // get % value, the dirty way var div = this.document.createElement("div"); div.style.cssText = offscreenStyle + "width:"+value + "%;"; el.appendChild(div); var value = div.offsetWidth; el.removeChild(div); return value; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getStyle: isIE ? function(el, name) { return el.currentStyle[name] || el.style[name] || undefined; } : function(el, name) { return this.document.defaultView.getComputedStyle(el,null)[name] || el.style[name] || undefined; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns( /**@scope ns-chrome*/ function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Window Options var WindowDefaultOptions = { type: "frame", id: "FirebugUI" //height: 350 // obsolete }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Instantiated objects commandLine, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Interface Elements Cache fbTop, fbContent, fbContentStyle, fbBottom, fbBtnInspect, fbToolbar, fbPanelBox1, fbPanelBox1Style, fbPanelBox2, fbPanelBox2Style, fbPanelBar2Box, fbPanelBar2BoxStyle, fbHSplitter, fbVSplitter, fbVSplitterStyle, fbPanel1, fbPanel1Style, fbPanel2, fbPanel2Style, fbConsole, fbConsoleStyle, fbHTML, fbCommandLine, fbLargeCommandLine, fbLargeCommandButtons, //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Cached size values topHeight, topPartialHeight, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * chromeRedrawSkipRate = isIE ? 75 : isOpera ? 80 : 75, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * lastSelectedPanelName, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * focusCommandLineState = 0, lastFocusedPanelName, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * lastHSplitterMouseMove = 0, onHSplitterMouseMoveBuffer = null, onHSplitterMouseMoveTimer = null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * lastVSplitterMouseMove = 0; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ************************************************************************************************ // FirebugChrome FBL.defaultPersistedState = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * isOpen: false, height: 300, sidePanelWidth: 350, selectedPanelName: "Console", selectedHTMLElementId: null, htmlSelectionStack: [] // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * }; /**@namespace*/ FBL.FirebugChrome = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //isOpen: false, //height: 300, //sidePanelWidth: 350, //selectedPanelName: "Console", //selectedHTMLElementId: null, chromeMap: {}, htmlSelectionStack: [], // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * create: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("FirebugChrome.create", "creating chrome window"); createChromeWindow(); }, initialize: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("FirebugChrome.initialize", "initializing chrome window"); if (Env.chrome.type == "frame" || Env.chrome.type == "div") ChromeMini.create(Env.chrome); var chrome = Firebug.chrome = new Chrome(Env.chrome); FirebugChrome.chromeMap[chrome.type] = chrome; addGlobalEvent("keydown", onGlobalKeyDown); if (Env.Options.enablePersistent && chrome.type == "popup") { // TODO: xxxpedro persist - revise chrome synchronization when in persistent mode var frame = FirebugChrome.chromeMap.frame; if (frame) frame.close(); //chrome.reattach(frame, chrome); //TODO: xxxpedro persist synchronize? chrome.initialize(); } }, clone: function(FBChrome) { for (var name in FBChrome) { var prop = FBChrome[name]; if (FBChrome.hasOwnProperty(name) && !isFunction(prop)) { this[name] = prop; } } } }; // ************************************************************************************************ // Chrome Window Creation var createChromeWindow = function(options) { options = extend(WindowDefaultOptions, options || {}); //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Locals var browserWin = Env.browser.window; var browserContext = new Context(browserWin); var prefs = Store.get("FirebugLite"); var persistedState = prefs && prefs.persistedState || defaultPersistedState; var chrome = {}, context = options.context || Env.browser, type = chrome.type = Env.Options.enablePersistent ? "popup" : options.type, isChromeFrame = type == "frame", useLocalSkin = Env.useLocalSkin, url = useLocalSkin ? Env.Location.skin : "about:blank", // document.body not available in XML+XSL documents in Firefox body = context.document.getElementsByTagName("body")[0], formatNode = function(node) { if (!Env.isDebugMode) { node.firebugIgnore = true; } var browserWinSize = browserContext.getWindowSize(); var height = persistedState.height || 300; height = Math.min(browserWinSize.height, height); height = Math.max(200, height); node.style.border = "0"; node.style.visibility = "hidden"; node.style.zIndex = "2147483647"; // MAX z-index = 2147483647 node.style.position = noFixedPosition ? "absolute" : "fixed"; node.style.width = "100%"; // "102%"; IE auto margin bug node.style.left = "0"; node.style.bottom = noFixedPosition ? "-1px" : "0"; node.style.height = height + "px"; // avoid flickering during chrome rendering //if (isFirefox) // node.style.display = "none"; }, createChromeDiv = function() { //Firebug.Console.warn("Firebug Lite GUI is working in 'windowless mode'. It may behave slower and receive interferences from the page in which it is installed."); var node = chrome.node = createGlobalElement("div"), style = createGlobalElement("style"), css = FirebugChrome.Skin.CSS /* .replace(/;/g, " !important;") .replace(/!important\s!important/g, "!important") .replace(/display\s*:\s*(\w+)\s*!important;/g, "display:$1;")*/, // reset some styles to minimize interference from the main page's style rules = ".fbBody *{margin:0;padding:0;font-size:11px;line-height:13px;color:inherit;}" + // load the chrome styles css + // adjust some remaining styles ".fbBody #fbHSplitter{position:absolute !important;} .fbBody #fbHTML span{line-height:14px;} .fbBody .lineNo div{line-height:inherit !important;}"; /* if (isIE) { // IE7 CSS bug (FbChrome table bigger than its parent div) rules += ".fbBody table.fbChrome{position: static !important;}"; }/**/ style.type = "text/css"; if (style.styleSheet) style.styleSheet.cssText = rules; else style.appendChild(context.document.createTextNode(rules)); document.getElementsByTagName("head")[0].appendChild(style); node.className = "fbBody"; node.style.overflow = "hidden"; node.innerHTML = getChromeDivTemplate(); if (isIE) { // IE7 CSS bug (FbChrome table bigger than its parent div) setTimeout(function(){ node.firstChild.style.height = "1px"; node.firstChild.style.position = "static"; },0); /**/ } formatNode(node); body.appendChild(node); chrome.window = window; chrome.document = document; onChromeLoad(chrome); }; //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * try { //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create the Chrome as a "div" (windowless mode) if (type == "div") { createChromeDiv(); return; } //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // cretate the Chrome as an "iframe" else if (isChromeFrame) { // Create the Chrome Frame var node = chrome.node = createGlobalElement("iframe"); node.setAttribute("src", url); node.setAttribute("frameBorder", "0"); formatNode(node); body.appendChild(node); // must set the id after appending to the document, otherwise will cause an // strange error in IE, making the iframe load the page in which the bookmarklet // was created (like getfirebug.com), before loading the injected UI HTML, // generating an "Access Denied" error. node.id = options.id; } //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create the Chrome as a "popup" else { var height = persistedState.popupHeight || 300; var browserWinSize = browserContext.getWindowSize(); var browserWinLeft = typeof browserWin.screenX == "number" ? browserWin.screenX : browserWin.screenLeft; var popupLeft = typeof persistedState.popupLeft == "number" ? persistedState.popupLeft : browserWinLeft; var browserWinTop = typeof browserWin.screenY == "number" ? browserWin.screenY : browserWin.screenTop; var popupTop = typeof persistedState.popupTop == "number" ? persistedState.popupTop : Math.max( 0, Math.min( browserWinTop + browserWinSize.height - height, // Google Chrome bug screen.availHeight - height - 61 ) ); var popupWidth = typeof persistedState.popupWidth == "number" ? persistedState.popupWidth : Math.max( 0, Math.min( browserWinSize.width, // Opera opens popup in a new tab if it's too big! screen.availWidth-10 ) ); var popupHeight = typeof persistedState.popupHeight == "number" ? persistedState.popupHeight : 300; var options = [ "true,top=", popupTop, ",left=", popupLeft, ",height=", popupHeight, ",width=", popupWidth, ",resizable" ].join(""), node = chrome.node = context.window.open( url, "popup", options ); if (node) { try { node.focus(); } catch(E) { alert("Firebug Error: Firebug popup was blocked."); return; } } else { alert("Firebug Error: Firebug popup was blocked."); return; } } //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Inject the interface HTML if it is not using the local skin if (!useLocalSkin) { var tpl = getChromeTemplate(!isChromeFrame), doc = isChromeFrame ? node.contentWindow.document : node.document; doc.write(tpl); doc.close(); } //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Wait the Window to be loaded var win, waitDelay = useLocalSkin ? isChromeFrame ? 200 : 300 : 100, waitForWindow = function() { if ( // Frame loaded... OR isChromeFrame && (win=node.contentWindow) && node.contentWindow.document.getElementById("fbCommandLine") || // Popup loaded !isChromeFrame && (win=node.window) && node.document && node.document.getElementById("fbCommandLine") ) { chrome.window = win.window; chrome.document = win.document; // Prevent getting the wrong chrome height in FF when opening a popup setTimeout(function(){ onChromeLoad(chrome); }, useLocalSkin ? 200 : 0); } else setTimeout(waitForWindow, waitDelay); }; waitForWindow(); } catch(e) { var msg = e.message || e; if (/access/i.test(msg)) { // Firebug Lite could not create a window for its Graphical User Interface due to // a access restriction. This happens in some pages, when loading via bookmarklet. // In such cases, the only way is to load the GUI in a "windowless mode". if (isChromeFrame) body.removeChild(node); else if(type == "popup") node.close(); // Load the GUI in a "windowless mode" createChromeDiv(); } else { alert("Firebug Error: Firebug GUI could not be created."); } } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var onChromeLoad = function onChromeLoad(chrome) { Env.chrome = chrome; if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Chrome onChromeLoad", "chrome window loaded"); if (Env.Options.enablePersistent) { // TODO: xxxpedro persist - make better chrome synchronization when in persistent mode Env.FirebugChrome = FirebugChrome; chrome.window.Firebug = chrome.window.Firebug || {}; chrome.window.Firebug.SharedEnv = Env; if (Env.isDevelopmentMode) { Env.browser.window.FBDev.loadChromeApplication(chrome); } else { var doc = chrome.document; var script = doc.createElement("script"); script.src = Env.Location.app + "#remote,persist"; doc.getElementsByTagName("head")[0].appendChild(script); } } else { if (chrome.type == "frame" || chrome.type == "div") { // initialize the chrome application setTimeout(function(){ FBL.Firebug.initialize(); },0); } else if (chrome.type == "popup") { var oldChrome = FirebugChrome.chromeMap.frame; var newChrome = new Chrome(chrome); // TODO: xxxpedro sync detach reattach attach dispatch(newChrome.panelMap, "detach", [oldChrome, newChrome]); newChrome.reattach(oldChrome, newChrome); } } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var getChromeDivTemplate = function() { return FirebugChrome.Skin.HTML; }; var getChromeTemplate = function(isPopup) { var tpl = FirebugChrome.Skin; var r = [], i = -1; r[++i] = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/DTD/strict.dtd">'; r[++i] = '<html><head><title>'; r[++i] = Firebug.version; /* r[++i] = '</title><link href="'; r[++i] = Env.Location.skinDir + 'firebug.css'; r[++i] = '" rel="stylesheet" type="text/css" />'; /**/ r[++i] = '</title><style>html,body{margin:0;padding:0;overflow:hidden;}'; r[++i] = tpl.CSS; r[++i] = '</style>'; /**/ r[++i] = '</head><body class="fbBody' + (isPopup ? ' FirebugPopup' : '') + '">'; r[++i] = tpl.HTML; r[++i] = '</body></html>'; return r.join(""); }; // ************************************************************************************************ // Chrome Class /**@class*/ var Chrome = function Chrome(chrome) { var type = chrome.type; var Base = type == "frame" || type == "div" ? ChromeFrameBase : ChromePopupBase; append(this, Base); // inherit from base class (ChromeFrameBase or ChromePopupBase) append(this, chrome); // inherit chrome window properties append(this, new Context(chrome.window)); // inherit from Context class FirebugChrome.chromeMap[type] = this; Firebug.chrome = this; Env.chrome = chrome.window; this.commandLineVisible = false; this.sidePanelVisible = false; this.create(); return this; }; // ************************************************************************************************ // ChromeBase /** * @namespace * @extends FBL.Controller * @extends FBL.PanelBar **/ var ChromeBase = {}; append(ChromeBase, Controller); append(ChromeBase, PanelBar); append(ChromeBase, /**@extend ns-chrome-ChromeBase*/ { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // inherited properties // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // inherited from createChrome function node: null, type: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // inherited from Context.prototype document: null, window: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value properties sidePanelVisible: false, commandLineVisible: false, largeCommandLineVisible: false, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // object properties inspectButton: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * create: function() { PanelBar.create.call(this); if (Firebug.Inspector) this.inspectButton = new Button({ type: "toggle", element: $("fbChrome_btInspect"), owner: Firebug.Inspector, onPress: Firebug.Inspector.startInspecting, onUnpress: Firebug.Inspector.stopInspecting }); }, destroy: function() { if(Firebug.Inspector) this.inspectButton.destroy(); PanelBar.destroy.call(this); this.shutdown(); }, testMenu: function() { var firebugMenu = new Menu( { id: "fbFirebugMenu", items: [ { label: "Open Firebug", type: "shortcut", key: isFirefox ? "Shift+F12" : "F12", checked: true, command: "toggleChrome" }, { label: "Open Firebug in New Window", type: "shortcut", key: isFirefox ? "Ctrl+Shift+F12" : "Ctrl+F12", command: "openPopup" }, { label: "Inspect Element", type: "shortcut", key: "Ctrl+Shift+C", command: "toggleInspect" }, { label: "Command Line", type: "shortcut", key: "Ctrl+Shift+L", command: "focusCommandLine" }, "-", { label: "Options", type: "group", child: "fbFirebugOptionsMenu" }, "-", { label: "Firebug Lite Website...", command: "visitWebsite" }, { label: "Discussion Group...", command: "visitDiscussionGroup" }, { label: "Issue Tracker...", command: "visitIssueTracker" } ], onHide: function() { iconButton.restore(); }, toggleChrome: function() { Firebug.chrome.toggle(); }, openPopup: function() { Firebug.chrome.toggle(true, true); }, toggleInspect: function() { Firebug.Inspector.toggleInspect(); }, focusCommandLine: function() { Firebug.chrome.focusCommandLine(); }, visitWebsite: function() { this.visit("http://getfirebug.com/lite.html"); }, visitDiscussionGroup: function() { this.visit("http://groups.google.com/group/firebug"); }, visitIssueTracker: function() { this.visit("http://code.google.com/p/fbug/issues/list"); }, visit: function(url) { window.open(url); } }); /**@private*/ var firebugOptionsMenu = { id: "fbFirebugOptionsMenu", getItems: function() { var cookiesDisabled = !Firebug.saveCookies; return [ { label: "Start Opened", type: "checkbox", value: "startOpened", checked: Firebug.startOpened, disabled: cookiesDisabled }, { label: "Start in New Window", type: "checkbox", value: "startInNewWindow", checked: Firebug.startInNewWindow, disabled: cookiesDisabled }, { label: "Show Icon When Hidden", type: "checkbox", value: "showIconWhenHidden", checked: Firebug.showIconWhenHidden, disabled: cookiesDisabled }, { label: "Override Console Object", type: "checkbox", value: "overrideConsole", checked: Firebug.overrideConsole, disabled: cookiesDisabled }, { label: "Ignore Firebug Elements", type: "checkbox", value: "ignoreFirebugElements", checked: Firebug.ignoreFirebugElements, disabled: cookiesDisabled }, { label: "Disable When Firebug Active", type: "checkbox", value: "disableWhenFirebugActive", checked: Firebug.disableWhenFirebugActive, disabled: cookiesDisabled }, { label: "Disable XHR Listener", type: "checkbox", value: "disableXHRListener", checked: Firebug.disableXHRListener, disabled: cookiesDisabled }, { label: "Disable Resource Fetching", type: "checkbox", value: "disableResourceFetching", checked: Firebug.disableResourceFetching, disabled: cookiesDisabled }, { label: "Enable Trace Mode", type: "checkbox", value: "enableTrace", checked: Firebug.enableTrace, disabled: cookiesDisabled }, { label: "Enable Persistent Mode (experimental)", type: "checkbox", value: "enablePersistent", checked: Firebug.enablePersistent, disabled: cookiesDisabled }, "-", { label: "Reset All Firebug Options", command: "restorePrefs", disabled: cookiesDisabled } ]; }, onCheck: function(target, value, checked) { Firebug.setPref(value, checked); }, restorePrefs: function(target) { Firebug.erasePrefs(); if (target) this.updateMenu(target); }, updateMenu: function(target) { var options = getElementsByClass(target.parentNode, "fbMenuOption"); var firstOption = options[0]; var enabled = Firebug.saveCookies; if (enabled) Menu.check(firstOption); else Menu.uncheck(firstOption); if (enabled) Menu.check(options[0]); else Menu.uncheck(options[0]); for (var i = 1, length = options.length; i < length; i++) { var option = options[i]; var value = option.getAttribute("value"); var pref = Firebug[value]; if (pref) Menu.check(option); else Menu.uncheck(option); if (enabled) Menu.enable(option); else Menu.disable(option); } } }; Menu.register(firebugOptionsMenu); var menu = firebugMenu; var testMenuClick = function(event) { //console.log("testMenuClick"); cancelEvent(event, true); var target = event.target || event.srcElement; if (menu.isVisible) menu.hide(); else { var offsetLeft = isIE6 ? 1 : -4, // IE6 problem with fixed position chrome = Firebug.chrome, box = chrome.getElementBox(target), offset = chrome.type == "div" ? chrome.getElementPosition(chrome.node) : {top: 0, left: 0}; menu.show( box.left + offsetLeft - offset.left, box.top + box.height -5 - offset.top ); } return false; }; var iconButton = new IconButton({ type: "toggle", element: $("fbFirebugButton"), onClick: testMenuClick }); iconButton.initialize(); //addEvent($("fbToolbarIcon"), "click", testMenuClick); }, initialize: function() { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (Env.bookmarkletOutdated) Firebug.Console.logFormatted([ "A new bookmarklet version is available. " + "Please visit http://getfirebug.com/firebuglite#Install and update it." ], Firebug.context, "warn"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (Firebug.Console) Firebug.Console.flush(); if (Firebug.Trace) FBTrace.flush(Firebug.Trace); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.chrome.initialize", "initializing chrome application"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // initialize inherited classes Controller.initialize.call(this); PanelBar.initialize.call(this); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create the interface elements cache fbTop = $("fbTop"); fbContent = $("fbContent"); fbContentStyle = fbContent.style; fbBottom = $("fbBottom"); fbBtnInspect = $("fbBtnInspect"); fbToolbar = $("fbToolbar"); fbPanelBox1 = $("fbPanelBox1"); fbPanelBox1Style = fbPanelBox1.style; fbPanelBox2 = $("fbPanelBox2"); fbPanelBox2Style = fbPanelBox2.style; fbPanelBar2Box = $("fbPanelBar2Box"); fbPanelBar2BoxStyle = fbPanelBar2Box.style; fbHSplitter = $("fbHSplitter"); fbVSplitter = $("fbVSplitter"); fbVSplitterStyle = fbVSplitter.style; fbPanel1 = $("fbPanel1"); fbPanel1Style = fbPanel1.style; fbPanel2 = $("fbPanel2"); fbPanel2Style = fbPanel2.style; fbConsole = $("fbConsole"); fbConsoleStyle = fbConsole.style; fbHTML = $("fbHTML"); fbCommandLine = $("fbCommandLine"); fbLargeCommandLine = $("fbLargeCommandLine"); fbLargeCommandButtons = $("fbLargeCommandButtons"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // static values cache topHeight = fbTop.offsetHeight; topPartialHeight = fbToolbar.offsetHeight; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * disableTextSelection($("fbToolbar")); disableTextSelection($("fbPanelBarBox")); disableTextSelection($("fbPanelBar1")); disableTextSelection($("fbPanelBar2")); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Add the "javascript:void(0)" href attributes used to make the hover effect in IE6 if (isIE6 && Firebug.Selector) { // TODO: xxxpedro change to getElementsByClass var as = $$(".fbHover"); for (var i=0, a; a=as[i]; i++) { a.setAttribute("href", "javascript:void(0)"); } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // initialize all panels /* var panelMap = Firebug.panelTypes; for (var i=0, p; p=panelMap[i]; i++) { if (!p.parentPanel) { this.addPanel(p.prototype.name); } } /**/ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ if(Firebug.Inspector) this.inspectButton.initialize(); // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ this.addController( [$("fbLargeCommandLineIcon"), "click", this.showLargeCommandLine] ); // ************************************************************************************************ // Select the first registered panel // TODO: BUG IE7 var self = this; setTimeout(function(){ self.selectPanel(Firebug.context.persistedState.selectedPanelName); if (Firebug.context.persistedState.selectedPanelName == "Console" && Firebug.CommandLine) Firebug.chrome.focusCommandLine(); },0); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //this.draw(); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var onPanelMouseDown = function onPanelMouseDown(event) { //console.log("onPanelMouseDown", event.target || event.srcElement, event); var target = event.target || event.srcElement; if (FBL.isLeftClick(event)) { var editable = FBL.getAncestorByClass(target, "editable"); // if an editable element has been clicked then start editing if (editable) { Firebug.Editor.startEditing(editable); FBL.cancelEvent(event); } // if any other element has been clicked then stop editing else { if (!hasClass(target, "textEditorInner")) Firebug.Editor.stopEditing(); } } else if (FBL.isMiddleClick(event) && Firebug.getRepNode(target)) { // Prevent auto-scroll when middle-clicking a rep object FBL.cancelEvent(event); } }; Firebug.getElementPanel = function(element) { var panelNode = getAncestorByClass(element, "fbPanel"); var id = panelNode.id.substr(2); var panel = Firebug.chrome.panelMap[id]; if (!panel) { if (Firebug.chrome.selectedPanel.sidePanelBar) panel = Firebug.chrome.selectedPanel.sidePanelBar.panelMap[id]; } return panel; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // TODO: xxxpedro port to Firebug // Improved window key code event listener. Only one "keydown" event will be attached // to the window, and the onKeyCodeListen() function will delegate which listeners // should be called according to the event.keyCode fired. var onKeyCodeListenersMap = []; var onKeyCodeListen = function(event) { for (var keyCode in onKeyCodeListenersMap) { var listeners = onKeyCodeListenersMap[keyCode]; for (var i = 0, listener; listener = listeners[i]; i++) { var filter = listener.filter || FBL.noKeyModifiers; if (event.keyCode == keyCode && (!filter || filter(event))) { listener.listener(); FBL.cancelEvent(event, true); return false; } } } }; addEvent(Firebug.chrome.document, "keydown", onKeyCodeListen); /** * @name keyCodeListen * @memberOf FBL.FirebugChrome */ Firebug.chrome.keyCodeListen = function(key, filter, listener, capture) { var keyCode = KeyEvent["DOM_VK_"+key]; if (!onKeyCodeListenersMap[keyCode]) onKeyCodeListenersMap[keyCode] = []; onKeyCodeListenersMap[keyCode].push({ filter: filter, listener: listener }); return keyCode; }; /** * @name keyIgnore * @memberOf FBL.FirebugChrome */ Firebug.chrome.keyIgnore = function(keyCode) { onKeyCodeListenersMap[keyCode] = null; delete onKeyCodeListenersMap[keyCode]; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /**/ // move to shutdown //removeEvent(Firebug.chrome.document, "keydown", listener[0]); /* Firebug.chrome.keyCodeListen = function(key, filter, listener, capture) { if (!filter) filter = FBL.noKeyModifiers; var keyCode = KeyEvent["DOM_VK_"+key]; var fn = function fn(event) { if (event.keyCode == keyCode && (!filter || filter(event))) { listener(); FBL.cancelEvent(event, true); return false; } } addEvent(Firebug.chrome.document, "keydown", fn); return [fn, capture]; }; Firebug.chrome.keyIgnore = function(listener) { removeEvent(Firebug.chrome.document, "keydown", listener[0]); }; /**/ this.addController( [fbPanel1, "mousedown", onPanelMouseDown], [fbPanel2, "mousedown", onPanelMouseDown] ); /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // menus can be used without domplate if (FBL.domplate) this.testMenu(); /**/ //test XHR /* setTimeout(function(){ FBL.Ajax.request({url: "../content/firebug/boot.js"}); FBL.Ajax.request({url: "../content/firebug/boot.js.invalid"}); },1000); /**/ }, shutdown: function() { // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ if(Firebug.Inspector) this.inspectButton.shutdown(); // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // remove disableTextSelection event handlers restoreTextSelection($("fbToolbar")); restoreTextSelection($("fbPanelBarBox")); restoreTextSelection($("fbPanelBar1")); restoreTextSelection($("fbPanelBar2")); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // shutdown inherited classes Controller.shutdown.call(this); PanelBar.shutdown.call(this); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Remove the interface elements cache (this must happen after calling // the shutdown method of all dependent components to avoid errors) fbTop = null; fbContent = null; fbContentStyle = null; fbBottom = null; fbBtnInspect = null; fbToolbar = null; fbPanelBox1 = null; fbPanelBox1Style = null; fbPanelBox2 = null; fbPanelBox2Style = null; fbPanelBar2Box = null; fbPanelBar2BoxStyle = null; fbHSplitter = null; fbVSplitter = null; fbVSplitterStyle = null; fbPanel1 = null; fbPanel1Style = null; fbPanel2 = null; fbConsole = null; fbConsoleStyle = null; fbHTML = null; fbCommandLine = null; fbLargeCommandLine = null; fbLargeCommandButtons = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // static values cache topHeight = null; topPartialHeight = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * toggle: function(forceOpen, popup) { if(popup) { this.detach(); } else { if (isOpera && Firebug.chrome.type == "popup" && Firebug.chrome.node.closed) { var frame = FirebugChrome.chromeMap.frame; frame.reattach(); FirebugChrome.chromeMap.popup = null; frame.open(); return; } // If the context is a popup, ignores the toggle process if (Firebug.chrome.type == "popup") return; var shouldOpen = forceOpen || !Firebug.context.persistedState.isOpen; if(shouldOpen) this.open(); else this.close(); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * detach: function() { if(!FirebugChrome.chromeMap.popup) { this.close(); createChromeWindow({type: "popup"}); } }, reattach: function(oldChrome, newChrome) { Firebug.browser.window.Firebug = Firebug; // chrome synchronization var newPanelMap = newChrome.panelMap; var oldPanelMap = oldChrome.panelMap; var panel; for(var name in newPanelMap) { // TODO: xxxpedro innerHTML panel = newPanelMap[name]; if (panel.options.innerHTMLSync) panel.panelNode.innerHTML = oldPanelMap[name].panelNode.innerHTML; } Firebug.chrome = newChrome; // TODO: xxxpedro sync detach reattach attach //dispatch(Firebug.chrome.panelMap, "detach", [oldChrome, newChrome]); if (newChrome.type == "popup") { newChrome.initialize(); //dispatch(Firebug.modules, "initialize", []); } else { // TODO: xxxpedro only needed in persistent // should use FirebugChrome.clone, but popup FBChrome // isn't acessible Firebug.context.persistedState.selectedPanelName = oldChrome.selectedPanel.name; } dispatch(newPanelMap, "reattach", [oldChrome, newChrome]); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * draw: function() { var size = this.getSize(); // Height related values var commandLineHeight = Firebug.chrome.commandLineVisible ? fbCommandLine.offsetHeight : 0, y = Math.max(size.height /* chrome height */, topHeight), heightValue = Math.max(y - topHeight - commandLineHeight /* fixed height */, 0), height = heightValue + "px", // Width related values sideWidthValue = Firebug.chrome.sidePanelVisible ? Firebug.context.persistedState.sidePanelWidth : 0, width = Math.max(size.width /* chrome width */ - sideWidthValue, 0) + "px"; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Height related rendering fbPanelBox1Style.height = height; fbPanel1Style.height = height; if (isIE || isOpera) { // Fix IE and Opera problems with auto resizing the verticall splitter fbVSplitterStyle.height = Math.max(y - topPartialHeight - commandLineHeight, 0) + "px"; } //xxxpedro FF2 only? /* else if (isFirefox) { // Fix Firefox problem with table rows with 100% height (fit height) fbContentStyle.maxHeight = Math.max(y - fixedHeight, 0)+ "px"; }/**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Width related rendering fbPanelBox1Style.width = width; fbPanel1Style.width = width; // SidePanel rendering if (Firebug.chrome.sidePanelVisible) { sideWidthValue = Math.max(sideWidthValue - 6, 0); var sideWidth = sideWidthValue + "px"; fbPanelBox2Style.width = sideWidth; fbVSplitterStyle.right = sideWidth; if (Firebug.chrome.largeCommandLineVisible) { fbLargeCommandLine = $("fbLargeCommandLine"); fbLargeCommandLine.style.height = heightValue - 4 + "px"; fbLargeCommandLine.style.width = sideWidthValue - 2 + "px"; fbLargeCommandButtons = $("fbLargeCommandButtons"); fbLargeCommandButtons.style.width = sideWidth; } else { fbPanel2Style.height = height; fbPanel2Style.width = sideWidth; fbPanelBar2BoxStyle.width = sideWidth; } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getSize: function() { return this.type == "div" ? { height: this.node.offsetHeight, width: this.node.offsetWidth } : this.getWindowSize(); }, resize: function() { var self = this; // avoid partial resize when maximizing window setTimeout(function(){ self.draw(); if (noFixedPosition && (self.type == "frame" || self.type == "div")) self.fixIEPosition(); }, 0); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * layout: function(panel) { if (FBTrace.DBG_CHROME) FBTrace.sysout("Chrome.layout", ""); var options = panel.options; changeCommandLineVisibility(options.hasCommandLine); changeSidePanelVisibility(panel.hasSidePanel); Firebug.chrome.draw(); }, showLargeCommandLine: function(hideToggleIcon) { var chrome = Firebug.chrome; if (!chrome.largeCommandLineVisible) { chrome.largeCommandLineVisible = true; if (chrome.selectedPanel.options.hasCommandLine) { if (Firebug.CommandLine) Firebug.CommandLine.blur(); changeCommandLineVisibility(false); } changeSidePanelVisibility(true); fbLargeCommandLine.style.display = "block"; fbLargeCommandButtons.style.display = "block"; fbPanel2Style.display = "none"; fbPanelBar2BoxStyle.display = "none"; chrome.draw(); fbLargeCommandLine.focus(); if (Firebug.CommandLine) Firebug.CommandLine.setMultiLine(true); } }, hideLargeCommandLine: function() { if (Firebug.chrome.largeCommandLineVisible) { Firebug.chrome.largeCommandLineVisible = false; if (Firebug.CommandLine) Firebug.CommandLine.setMultiLine(false); fbLargeCommandLine.blur(); fbPanel2Style.display = "block"; fbPanelBar2BoxStyle.display = "block"; fbLargeCommandLine.style.display = "none"; fbLargeCommandButtons.style.display = "none"; changeSidePanelVisibility(false); if (Firebug.chrome.selectedPanel.options.hasCommandLine) changeCommandLineVisibility(true); Firebug.chrome.draw(); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * focusCommandLine: function() { var selectedPanelName = this.selectedPanel.name, panelToSelect; if (focusCommandLineState == 0 || selectedPanelName != "Console") { focusCommandLineState = 0; lastFocusedPanelName = selectedPanelName; panelToSelect = "Console"; } if (focusCommandLineState == 1) { panelToSelect = lastFocusedPanelName; } this.selectPanel(panelToSelect); try { if (Firebug.CommandLine) { if (panelToSelect == "Console") Firebug.CommandLine.focus(); else Firebug.CommandLine.blur(); } } catch(e) { //TODO: xxxpedro trace error } focusCommandLineState = ++focusCommandLineState % 2; } }); // ************************************************************************************************ // ChromeFrameBase /** * @namespace * @extends ns-chrome-ChromeBase */ var ChromeFrameBase = extend(ChromeBase, /**@extend ns-chrome-ChromeFrameBase*/ { create: function() { ChromeBase.create.call(this); // restore display for the anti-flicker trick if (isFirefox) this.node.style.display = "block"; if (Env.Options.startInNewWindow) { this.close(); this.toggle(true, true); return; } if (Env.Options.startOpened) this.open(); else this.close(); }, destroy: function() { var size = Firebug.chrome.getWindowSize(); Firebug.context.persistedState.height = size.height; if (Firebug.saveCookies) Firebug.savePrefs(); removeGlobalEvent("keydown", onGlobalKeyDown); ChromeBase.destroy.call(this); this.document = null; delete this.document; this.window = null; delete this.window; this.node.parentNode.removeChild(this.node); this.node = null; delete this.node; }, initialize: function() { //FBTrace.sysout("Frame", "initialize();") ChromeBase.initialize.call(this); this.addController( [Firebug.browser.window, "resize", this.resize], [$("fbWindow_btClose"), "click", this.close], [$("fbWindow_btDetach"), "click", this.detach], [$("fbWindow_btDeactivate"), "click", this.deactivate] ); if (!Env.Options.enablePersistent) this.addController([Firebug.browser.window, "unload", Firebug.shutdown]); if (noFixedPosition) { this.addController( [Firebug.browser.window, "scroll", this.fixIEPosition] ); } fbVSplitter.onmousedown = onVSplitterMouseDown; fbHSplitter.onmousedown = onHSplitterMouseDown; this.isInitialized = true; }, shutdown: function() { fbVSplitter.onmousedown = null; fbHSplitter.onmousedown = null; ChromeBase.shutdown.apply(this); this.isInitialized = false; }, reattach: function() { var frame = FirebugChrome.chromeMap.frame; ChromeBase.reattach(FirebugChrome.chromeMap.popup, this); }, open: function() { if (!Firebug.context.persistedState.isOpen) { Firebug.context.persistedState.isOpen = true; if (Env.isChromeExtension) localStorage.setItem("Firebug", "1,1"); var node = this.node; node.style.visibility = "hidden"; // Avoid flickering if (Firebug.showIconWhenHidden) { if (ChromeMini.isInitialized) { ChromeMini.shutdown(); } } else node.style.display = "block"; var main = $("fbChrome"); // IE6 throws an error when setting this property! why? //main.style.display = "table"; main.style.display = ""; var self = this; /// TODO: xxxpedro FOUC node.style.visibility = "visible"; setTimeout(function(){ ///node.style.visibility = "visible"; //dispatch(Firebug.modules, "initialize", []); self.initialize(); if (noFixedPosition) self.fixIEPosition(); self.draw(); }, 10); } }, close: function() { if (Firebug.context.persistedState.isOpen) { if (this.isInitialized) { //dispatch(Firebug.modules, "shutdown", []); this.shutdown(); } Firebug.context.persistedState.isOpen = false; if (Env.isChromeExtension) localStorage.setItem("Firebug", "1,0"); var node = this.node; if (Firebug.showIconWhenHidden) { node.style.visibility = "hidden"; // Avoid flickering // TODO: xxxpedro - persist IE fixed? var main = $("fbChrome", FirebugChrome.chromeMap.frame.document); main.style.display = "none"; ChromeMini.initialize(); node.style.visibility = "visible"; } else node.style.display = "none"; } }, deactivate: function() { // if it is running as a Chrome extension, dispatch a message to the extension signaling // that Firebug should be deactivated for the current tab if (Env.isChromeExtension) { localStorage.removeItem("Firebug"); Firebug.GoogleChrome.dispatch("FB_deactivate"); // xxxpedro problem here regarding Chrome extension. We can't deactivate the whole // app, otherwise it won't be able to be reactivated without reloading the page. // but we need to stop listening global keys, otherwise the key activation won't work. Firebug.chrome.close(); } else { Firebug.shutdown(); } }, fixIEPosition: function() { // fix IE problem with offset when not in fullscreen mode var doc = this.document; var offset = isIE ? doc.body.clientTop || doc.documentElement.clientTop: 0; var size = Firebug.browser.getWindowSize(); var scroll = Firebug.browser.getWindowScrollPosition(); var maxHeight = size.height; var height = this.node.offsetHeight; var bodyStyle = doc.body.currentStyle; this.node.style.top = maxHeight - height + scroll.top + "px"; if ((this.type == "frame" || this.type == "div") && (bodyStyle.marginLeft || bodyStyle.marginRight)) { this.node.style.width = size.width + "px"; } if (fbVSplitterStyle) fbVSplitterStyle.right = Firebug.context.persistedState.sidePanelWidth + "px"; this.draw(); } }); // ************************************************************************************************ // ChromeMini /** * @namespace * @extends FBL.Controller */ var ChromeMini = extend(Controller, /**@extend ns-chrome-ChromeMini*/ { create: function(chrome) { append(this, chrome); this.type = "mini"; }, initialize: function() { Controller.initialize.apply(this); var doc = FirebugChrome.chromeMap.frame.document; var mini = $("fbMiniChrome", doc); mini.style.display = "block"; var miniIcon = $("fbMiniIcon", doc); var width = miniIcon.offsetWidth + 10; miniIcon.title = "Open " + Firebug.version; var errors = $("fbMiniErrors", doc); if (errors.offsetWidth) width += errors.offsetWidth + 10; var node = this.node; node.style.height = "27px"; node.style.width = width + "px"; node.style.left = ""; node.style.right = 0; if (this.node.nodeName.toLowerCase() == "iframe") { node.setAttribute("allowTransparency", "true"); this.document.body.style.backgroundColor = "transparent"; } else node.style.background = "transparent"; if (noFixedPosition) this.fixIEPosition(); this.addController( [$("fbMiniIcon", doc), "click", onMiniIconClick] ); if (noFixedPosition) { this.addController( [Firebug.browser.window, "scroll", this.fixIEPosition] ); } this.isInitialized = true; }, shutdown: function() { var node = this.node; node.style.height = Firebug.context.persistedState.height + "px"; node.style.width = "100%"; node.style.left = 0; node.style.right = ""; if (this.node.nodeName.toLowerCase() == "iframe") { node.setAttribute("allowTransparency", "false"); this.document.body.style.backgroundColor = "#fff"; } else node.style.background = "#fff"; if (noFixedPosition) this.fixIEPosition(); var doc = FirebugChrome.chromeMap.frame.document; var mini = $("fbMiniChrome", doc); mini.style.display = "none"; Controller.shutdown.apply(this); this.isInitialized = false; }, draw: function() { }, fixIEPosition: ChromeFrameBase.fixIEPosition }); // ************************************************************************************************ // ChromePopupBase /** * @namespace * @extends ns-chrome-ChromeBase */ var ChromePopupBase = extend(ChromeBase, /**@extend ns-chrome-ChromePopupBase*/ { initialize: function() { setClass(this.document.body, "FirebugPopup"); ChromeBase.initialize.call(this); this.addController( [Firebug.chrome.window, "resize", this.resize], [Firebug.chrome.window, "unload", this.destroy] //[Firebug.chrome.window, "beforeunload", this.destroy] ); if (Env.Options.enablePersistent) { this.persist = bind(this.persist, this); addEvent(Firebug.browser.window, "unload", this.persist); } else this.addController( [Firebug.browser.window, "unload", this.close] ); fbVSplitter.onmousedown = onVSplitterMouseDown; }, destroy: function() { var chromeWin = Firebug.chrome.window; var left = chromeWin.screenX || chromeWin.screenLeft; var top = chromeWin.screenY || chromeWin.screenTop; var size = Firebug.chrome.getWindowSize(); Firebug.context.persistedState.popupTop = top; Firebug.context.persistedState.popupLeft = left; Firebug.context.persistedState.popupWidth = size.width; Firebug.context.persistedState.popupHeight = size.height; if (Firebug.saveCookies) Firebug.savePrefs(); // TODO: xxxpedro sync detach reattach attach var frame = FirebugChrome.chromeMap.frame; if(frame) { dispatch(frame.panelMap, "detach", [this, frame]); frame.reattach(this, frame); } if (Env.Options.enablePersistent) { removeEvent(Firebug.browser.window, "unload", this.persist); } ChromeBase.destroy.apply(this); FirebugChrome.chromeMap.popup = null; this.node.close(); }, persist: function() { persistTimeStart = new Date().getTime(); removeEvent(Firebug.browser.window, "unload", this.persist); Firebug.Inspector.destroy(); Firebug.browser.window.FirebugOldBrowser = true; var persistTimeStart = new Date().getTime(); var waitMainWindow = function() { var doc, head; try { if (window.opener && !window.opener.FirebugOldBrowser && (doc = window.opener.document)/* && doc.documentElement && (head = doc.documentElement.firstChild)*/) { try { // exposes the FBL to the global namespace when in debug mode if (Env.isDebugMode) { window.FBL = FBL; } window.Firebug = Firebug; window.opener.Firebug = Firebug; Env.browser = window.opener; Firebug.browser = Firebug.context = new Context(Env.browser); Firebug.loadPrefs(); registerConsole(); // the delay time should be calculated right after registering the // console, once right after the console registration, call log messages // will be properly handled var persistDelay = new Date().getTime() - persistTimeStart; var chrome = Firebug.chrome; addEvent(Firebug.browser.window, "unload", chrome.persist); FBL.cacheDocument(); Firebug.Inspector.create(); Firebug.Console.logFormatted( ["Firebug could not capture console calls during " + persistDelay + "ms"], Firebug.context, "info" ); setTimeout(function(){ var htmlPanel = chrome.getPanel("HTML"); htmlPanel.createUI(); },50); } catch(pE) { alert("persist error: " + (pE.message || pE)); } } else { window.setTimeout(waitMainWindow, 0); } } catch (E) { window.close(); } }; waitMainWindow(); }, close: function() { this.destroy(); } }); //************************************************************************************************ // UI helpers var changeCommandLineVisibility = function changeCommandLineVisibility(visibility) { var last = Firebug.chrome.commandLineVisible; var visible = Firebug.chrome.commandLineVisible = typeof visibility == "boolean" ? visibility : !Firebug.chrome.commandLineVisible; if (visible != last) { if (visible) { fbBottom.className = ""; if (Firebug.CommandLine) Firebug.CommandLine.activate(); } else { if (Firebug.CommandLine) Firebug.CommandLine.deactivate(); fbBottom.className = "hide"; } } }; var changeSidePanelVisibility = function changeSidePanelVisibility(visibility) { var last = Firebug.chrome.sidePanelVisible; Firebug.chrome.sidePanelVisible = typeof visibility == "boolean" ? visibility : !Firebug.chrome.sidePanelVisible; if (Firebug.chrome.sidePanelVisible != last) { fbPanelBox2.className = Firebug.chrome.sidePanelVisible ? "" : "hide"; fbPanelBar2Box.className = Firebug.chrome.sidePanelVisible ? "" : "hide"; } }; // ************************************************************************************************ // F12 Handler var onGlobalKeyDown = function onGlobalKeyDown(event) { var keyCode = event.keyCode; var shiftKey = event.shiftKey; var ctrlKey = event.ctrlKey; if (keyCode == 123 /* F12 */ && (!isFirefox && !shiftKey || shiftKey && isFirefox)) { Firebug.chrome.toggle(false, ctrlKey); cancelEvent(event, true); // TODO: xxxpedro replace with a better solution. we're doing this // to allow reactivating with the F12 key after being deactivated if (Env.isChromeExtension) { Firebug.GoogleChrome.dispatch("FB_enableIcon"); } } else if (keyCode == 67 /* C */ && ctrlKey && shiftKey) { Firebug.Inspector.toggleInspect(); cancelEvent(event, true); } else if (keyCode == 76 /* L */ && ctrlKey && shiftKey) { Firebug.chrome.focusCommandLine(); cancelEvent(event, true); } }; var onMiniIconClick = function onMiniIconClick(event) { Firebug.chrome.toggle(false, event.ctrlKey); cancelEvent(event, true); }; // ************************************************************************************************ // Horizontal Splitter Handling var onHSplitterMouseDown = function onHSplitterMouseDown(event) { addGlobalEvent("mousemove", onHSplitterMouseMove); addGlobalEvent("mouseup", onHSplitterMouseUp); if (isIE) addEvent(Firebug.browser.document.documentElement, "mouseleave", onHSplitterMouseUp); fbHSplitter.className = "fbOnMovingHSplitter"; return false; }; var onHSplitterMouseMove = function onHSplitterMouseMove(event) { cancelEvent(event, true); var clientY = event.clientY; var win = isIE ? event.srcElement.ownerDocument.parentWindow : event.target.defaultView || event.target.ownerDocument && event.target.ownerDocument.defaultView; if (!win) return; if (win != win.parent) { var frameElement = win.frameElement; if (frameElement) { var framePos = Firebug.browser.getElementPosition(frameElement).top; clientY += framePos; if (frameElement.style.position != "fixed") clientY -= Firebug.browser.getWindowScrollPosition().top; } } if (isOpera && isQuiksMode && win.frameElement.id == "FirebugUI") { clientY = Firebug.browser.getWindowSize().height - win.frameElement.offsetHeight + clientY; } /* console.log( typeof win.FBL != "undefined" ? "no-Chrome" : "Chrome", //win.frameElement.id, event.target, clientY );/**/ onHSplitterMouseMoveBuffer = clientY; // buffer if (new Date().getTime() - lastHSplitterMouseMove > chromeRedrawSkipRate) // frame skipping { lastHSplitterMouseMove = new Date().getTime(); handleHSplitterMouseMove(); } else if (!onHSplitterMouseMoveTimer) onHSplitterMouseMoveTimer = setTimeout(handleHSplitterMouseMove, chromeRedrawSkipRate); // improving the resizing performance by canceling the mouse event. // canceling events will prevent the page to receive such events, which would imply // in more processing being expended. cancelEvent(event, true); return false; }; var handleHSplitterMouseMove = function() { if (onHSplitterMouseMoveTimer) { clearTimeout(onHSplitterMouseMoveTimer); onHSplitterMouseMoveTimer = null; } var clientY = onHSplitterMouseMoveBuffer; var windowSize = Firebug.browser.getWindowSize(); var scrollSize = Firebug.browser.getWindowScrollSize(); // compute chrome fixed size (top bar and command line) var commandLineHeight = Firebug.chrome.commandLineVisible ? fbCommandLine.offsetHeight : 0; var fixedHeight = topHeight + commandLineHeight; var chromeNode = Firebug.chrome.node; var scrollbarSize = !isIE && (scrollSize.width > windowSize.width) ? 17 : 0; //var height = !isOpera ? chromeNode.offsetTop + chromeNode.clientHeight : windowSize.height; var height = windowSize.height; // compute the min and max size of the chrome var chromeHeight = Math.max(height - clientY + 5 - scrollbarSize, fixedHeight); chromeHeight = Math.min(chromeHeight, windowSize.height - scrollbarSize); Firebug.context.persistedState.height = chromeHeight; chromeNode.style.height = chromeHeight + "px"; if (noFixedPosition) Firebug.chrome.fixIEPosition(); Firebug.chrome.draw(); }; var onHSplitterMouseUp = function onHSplitterMouseUp(event) { removeGlobalEvent("mousemove", onHSplitterMouseMove); removeGlobalEvent("mouseup", onHSplitterMouseUp); if (isIE) removeEvent(Firebug.browser.document.documentElement, "mouseleave", onHSplitterMouseUp); fbHSplitter.className = ""; Firebug.chrome.draw(); // avoid text selection in IE when returning to the document // after the mouse leaves the document during the resizing return false; }; // ************************************************************************************************ // Vertical Splitter Handling var onVSplitterMouseDown = function onVSplitterMouseDown(event) { addGlobalEvent("mousemove", onVSplitterMouseMove); addGlobalEvent("mouseup", onVSplitterMouseUp); return false; }; var onVSplitterMouseMove = function onVSplitterMouseMove(event) { if (new Date().getTime() - lastVSplitterMouseMove > chromeRedrawSkipRate) // frame skipping { var target = event.target || event.srcElement; if (target && target.ownerDocument) // avoid error when cursor reaches out of the chrome { var clientX = event.clientX; var win = document.all ? event.srcElement.ownerDocument.parentWindow : event.target.ownerDocument.defaultView; if (win != win.parent) clientX += win.frameElement ? win.frameElement.offsetLeft : 0; var size = Firebug.chrome.getSize(); var x = Math.max(size.width - clientX + 3, 6); Firebug.context.persistedState.sidePanelWidth = x; Firebug.chrome.draw(); } lastVSplitterMouseMove = new Date().getTime(); } cancelEvent(event, true); return false; }; var onVSplitterMouseUp = function onVSplitterMouseUp(event) { removeGlobalEvent("mousemove", onVSplitterMouseMove); removeGlobalEvent("mouseup", onVSplitterMouseUp); Firebug.chrome.draw(); }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite = { }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite.Cache = { ID: "firebug-" + new Date().getTime() }; // ************************************************************************************************ /** * TODO: if a cached element is cloned, the expando property will be cloned too in IE * which will result in a bug. Firebug Lite will think the new cloned node is the old * one. * * TODO: Investigate a possibility of cache validation, to be customized by each * kind of cache. For ElementCache it should validate if the element still is * inserted at the DOM. */ var cacheUID = 0; var createCache = function() { var map = {}; var data = {}; var CID = Firebug.Lite.Cache.ID; // better detection var supportsDeleteExpando = !document.all; var cacheFunction = function(element) { return cacheAPI.set(element); }; var cacheAPI = { get: function(key) { return map.hasOwnProperty(key) ? map[key] : null; }, set: function(element) { var id = getValidatedKey(element); if (!id) { id = ++cacheUID; element[CID] = id; } if (!map.hasOwnProperty(id)) { map[id] = element; data[id] = {}; } return id; }, unset: function(element) { var id = getValidatedKey(element); if (!id) return; if (supportsDeleteExpando) { delete element[CID]; } else if (element.removeAttribute) { element.removeAttribute(CID); } delete map[id]; delete data[id]; }, key: function(element) { return getValidatedKey(element); }, has: function(element) { var id = getValidatedKey(element); return id && map.hasOwnProperty(id); }, each: function(callback) { for (var key in map) { if (map.hasOwnProperty(key)) { callback(key, map[key]); } } }, data: function(element, name, value) { // set data if (value) { if (!name) return null; var id = cacheAPI.set(element); return data[id][name] = value; } // get data else { var id = cacheAPI.key(element); return data.hasOwnProperty(id) && data[id].hasOwnProperty(name) ? data[id][name] : null; } }, clear: function() { for (var id in map) { var element = map[id]; cacheAPI.unset(element); } } }; var getValidatedKey = function(element) { var id = element[CID]; // If a cached element is cloned in IE, the expando property CID will be also // cloned (differently than other browsers) resulting in a bug: Firebug Lite // will think the new cloned node is the old one. To prevent this problem we're // checking if the cached element matches the given element. if ( !supportsDeleteExpando && // the problem happens when supportsDeleteExpando is false id && // the element has the expando property map.hasOwnProperty(id) && // there is a cached element with the same id map[id] != element // but it is a different element than the current one ) { // remove the problematic property element.removeAttribute(CID); id = null; } return id; }; FBL.append(cacheFunction, cacheAPI); return cacheFunction; }; // ************************************************************************************************ // TODO: xxxpedro : check if we need really this on FBL scope Firebug.Lite.Cache.StyleSheet = createCache(); Firebug.Lite.Cache.Element = createCache(); // TODO: xxxpedro Firebug.Lite.Cache.Event = createCache(); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ var sourceMap = {}; // ************************************************************************************************ Firebug.Lite.Proxy = { // jsonp callbacks _callbacks: {}, /** * Load a resource, either locally (directly) or externally (via proxy) using * synchronous XHR calls. Loading external resources requires the proxy plugin to * be installed and configured (see /plugin/proxy/proxy.php). */ load: function(url) { var resourceDomain = getDomain(url); var isLocalResource = // empty domain means local URL !resourceDomain || // same domain means local too resourceDomain == Firebug.context.window.location.host; // TODO: xxxpedro context return isLocalResource ? fetchResource(url) : fetchProxyResource(url); }, /** * Load a resource using JSONP technique. */ loadJSONP: function(url, callback) { var script = createGlobalElement("script"), doc = Firebug.context.document, uid = "" + new Date().getTime(), callbackName = "callback=Firebug.Lite.Proxy._callbacks." + uid, jsonpURL = url.indexOf("?") != -1 ? url + "&" + callbackName : url + "?" + callbackName; Firebug.Lite.Proxy._callbacks[uid] = function(data) { if (callback) callback(data); script.parentNode.removeChild(script); delete Firebug.Lite.Proxy._callbacks[uid]; }; script.src = jsonpURL; if (doc.documentElement) doc.documentElement.appendChild(script); }, /** * Load a resource using YQL (not reliable). */ YQL: function(url, callback) { var yql = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) + "%22&format=xml"; this.loadJSONP(yql, function(data) { var source = data.results[0]; // clean up YQL bogus elements var match = /<body>\s+<p>([\s\S]+)<\/p>\s+<\/body>$/.exec(source); if (match) source = match[1]; console.log(source); }); } }; // ************************************************************************************************ Firebug.Lite.Proxy.fetchResourceDisabledMessage = "/* Firebug Lite resource fetching is disabled.\n" + "To enabled it set the Firebug Lite option \"disableResourceFetching\" to \"false\".\n" + "More info at http://getfirebug.com/firebuglite#Options */"; var fetchResource = function(url) { if (Firebug.disableResourceFetching) { var source = sourceMap[url] = Firebug.Lite.Proxy.fetchResourceDisabledMessage; return source; } if (sourceMap.hasOwnProperty(url)) return sourceMap[url]; // Getting the native XHR object so our calls won't be logged in the Console Panel var xhr = FBL.getNativeXHRObject(); xhr.open("get", url, false); xhr.send(); var source = sourceMap[url] = xhr.responseText; return source; }; var fetchProxyResource = function(url) { if (sourceMap.hasOwnProperty(url)) return sourceMap[url]; var proxyURL = Env.Location.baseDir + "plugin/proxy/proxy.php?url=" + encodeURIComponent(url); var response = fetchResource(proxyURL); try { var data = eval("(" + response + ")"); } catch(E) { return "ERROR: Firebug Lite Proxy plugin returned an invalid response."; } var source = data ? data.contents : ""; return source; }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite.Style = { }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite.Script = function(window) { this.fileName = null; this.isValid = null; this.baseLineNumber = null; this.lineExtent = null; this.tag = null; this.functionName = null; this.functionSource = null; }; Firebug.Lite.Script.prototype = { isLineExecutable: function(){}, pcToLine: function(){}, lineToPc: function(){}, toString: function() { return "Firebug.Lite.Script"; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite.Browser = function(window) { this.contentWindow = window; this.contentDocument = window.document; this.currentURI = { spec: window.location.href }; }; Firebug.Lite.Browser.prototype = { toString: function() { return "Firebug.Lite.Browser"; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ /* http://www.JSON.org/json2.js 2010-03-20 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. // ************************************************************************************************ var JSON = window.JSON || {}; // ************************************************************************************************ (function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } // ************************************************************************************************ // registration FBL.JSON = JSON; // ************************************************************************************************ }()); /* See license.txt for terms of usage */ (function(){ // ************************************************************************************************ /* Copyright (c) 2010-2011 Marcus Westin * * 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. */ var store = (function(){ var api = {}, win = window, doc = win.document, localStorageName = 'localStorage', globalStorageName = 'globalStorage', namespace = '__firebug__storejs__', storage api.disabled = false api.set = function(key, value) {} api.get = function(key) {} api.remove = function(key) {} api.clear = function() {} api.transact = function(key, transactionFn) { var val = api.get(key) if (typeof val == 'undefined') { val = {} } transactionFn(val) api.set(key, val) } api.serialize = function(value) { return JSON.stringify(value) } api.deserialize = function(value) { if (typeof value != 'string') { return undefined } return JSON.parse(value) } // Functions to encapsulate questionable FireFox 3.6.13 behavior // when about.config::dom.storage.enabled === false // See https://github.com/marcuswestin/store.js/issues#issue/13 function isLocalStorageNameSupported() { try { return (localStorageName in win && win[localStorageName]) } catch(err) { return false } } function isGlobalStorageNameSupported() { try { return (globalStorageName in win && win[globalStorageName] && win[globalStorageName][win.location.hostname]) } catch(err) { return false } } if (isLocalStorageNameSupported()) { storage = win[localStorageName] api.set = function(key, val) { storage.setItem(key, api.serialize(val)) } api.get = function(key) { return api.deserialize(storage.getItem(key)) } api.remove = function(key) { storage.removeItem(key) } api.clear = function() { storage.clear() } } else if (isGlobalStorageNameSupported()) { storage = win[globalStorageName][win.location.hostname] api.set = function(key, val) { storage[key] = api.serialize(val) } api.get = function(key) { return api.deserialize(storage[key] && storage[key].value) } api.remove = function(key) { delete storage[key] } api.clear = function() { for (var key in storage ) { delete storage[key] } } } else if (doc.documentElement.addBehavior) { var storage = doc.createElement('div') function withIEStorage(storeFunction) { return function() { var args = Array.prototype.slice.call(arguments, 0) args.unshift(storage) // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx // TODO: xxxpedro doc.body is not always available so we must use doc.documentElement. // We need to make sure this change won't affect the behavior of this library. doc.documentElement.appendChild(storage) storage.addBehavior('#default#userData') storage.load(localStorageName) var result = storeFunction.apply(api, args) doc.documentElement.removeChild(storage) return result } } api.set = withIEStorage(function(storage, key, val) { storage.setAttribute(key, api.serialize(val)) storage.save(localStorageName) }) api.get = withIEStorage(function(storage, key) { return api.deserialize(storage.getAttribute(key)) }) api.remove = withIEStorage(function(storage, key) { storage.removeAttribute(key) storage.save(localStorageName) }) api.clear = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes storage.load(localStorageName) for (var i=0, attr; attr = attributes[i]; i++) { storage.removeAttribute(attr.name) } storage.save(localStorageName) }) } try { api.set(namespace, namespace) if (api.get(namespace) != namespace) { api.disabled = true } api.remove(namespace) } catch(e) { api.disabled = true } return api })(); if (typeof module != 'undefined') { module.exports = store } // ************************************************************************************************ // registration FBL.Store = store; // ************************************************************************************************ })(); /* See license.txt for terms of usage */ FBL.ns( /**@scope s_selector*/ function() { with (FBL) { // ************************************************************************************************ /* * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // 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; }); /** * @name Firebug.Selector * @namespace */ /** * @exports Sizzle as Firebug.Selector */ var Sizzle = function(selector, context, results, seed) { results = results || []; var origContext = context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, check, mode, extra, prune = true, contextXML = isXML(context), soFar = selector; // Reset the position of the chunker regexp (start from head) while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } 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 ); } } } 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]) ) { var ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { var 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 ) { var 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 ) { throw "Syntax error, unrecognized expression: " + (cur || selector); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var 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.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.match[ type ].exec( expr )) != null ) { var filter = Expr.filter[ type ], found, item; anyFound = false; 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 ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var 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 ) { throw "Syntax error, unrecognized expression: " + expr; } else { break; } } old = expr; } return curLoop; }; /**#@+ @ignore */ 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|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part, isXML){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag && !isXML ) { part = part.toUpperCase(); } 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 === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part, isXML){ var isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = isXML ? part : part.toUpperCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var 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 doneName = done++, checkFn = dirCheck; if ( !/\W/.test(part) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); 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]); return m ? [m] : []; } }, NAME: function(match, context, isXML){ 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){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) { if ( !inplace ) result.push( elem ); } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ for ( var i = 0; curLoop[i] === false; i++ ){} return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase(); }, CHILD: function(match){ if ( match[1] == "nth" ) { // 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; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } 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 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){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, 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 || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } }, CHILD: function(elem, match){ var 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; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) return false; } return true; case 'nth': var first = match[2], last = match[3]; if ( first == 1 && last == 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var 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 === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = 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 === "=" ? 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; 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 ); } 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. try { Array.prototype.slice.call( document.documentElement.childNodes, 0 ); // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { if ( a == b ) { hasDuplicate = true; } return 0; } var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return 0; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { if ( !a.ownerDocument || !b.ownerDocument ) { if ( a == b ) { hasDuplicate = true; } return 0; } var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } // 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(); form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly var root = document.documentElement; 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 ); root = form = null; // release memory in IE })(); (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); }; } div = null; // release memory in IE })(); if ( document.querySelectorAll ) (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); 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 && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } div = null; // release memory in IE })(); if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (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) if ( 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]); } }; div = null; // release memory in IE })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { var sibDir = dir == "previousSibling" && !isXML; for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { if ( sibDir && elem.nodeType === 1 ){ elem.sizcache = doneName; elem.sizset = i; } elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { var sibDir = dir == "previousSibling" && !isXML; for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { if ( sibDir && elem.nodeType === 1 ) { elem.sizcache = doneName; elem.sizset = i; } elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = 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; } } } var contains = document.compareDocumentPosition ? function(a, b){ return a.compareDocumentPosition(b) & 16; } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var isXML = function(elem){ return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || !!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML"; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, 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 ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE Firebug.Selector = Sizzle; /**#@-*/ // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Inspector Module var ElementCache = Firebug.Lite.Cache.Element; var inspectorTS, inspectorTimer, isInspecting; Firebug.Inspector = { create: function() { offlineFragment = Env.browser.document.createDocumentFragment(); createBoxModelInspector(); createOutlineInspector(); }, destroy: function() { destroyBoxModelInspector(); destroyOutlineInspector(); offlineFragment = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Inspect functions toggleInspect: function() { if (isInspecting) { this.stopInspecting(); } else { Firebug.chrome.inspectButton.changeState("pressed"); this.startInspecting(); } }, startInspecting: function() { isInspecting = true; Firebug.chrome.selectPanel("HTML"); createInspectorFrame(); var size = Firebug.browser.getWindowScrollSize(); fbInspectFrame.style.width = size.width + "px"; fbInspectFrame.style.height = size.height + "px"; //addEvent(Firebug.browser.document.documentElement, "mousemove", Firebug.Inspector.onInspectingBody); addEvent(fbInspectFrame, "mousemove", Firebug.Inspector.onInspecting); addEvent(fbInspectFrame, "mousedown", Firebug.Inspector.onInspectingClick); }, stopInspecting: function() { isInspecting = false; if (outlineVisible) this.hideOutline(); removeEvent(fbInspectFrame, "mousemove", Firebug.Inspector.onInspecting); removeEvent(fbInspectFrame, "mousedown", Firebug.Inspector.onInspectingClick); destroyInspectorFrame(); Firebug.chrome.inspectButton.restore(); if (Firebug.chrome.type == "popup") Firebug.chrome.node.focus(); }, onInspectingClick: function(e) { fbInspectFrame.style.display = "none"; var targ = Firebug.browser.getElementFromPoint(e.clientX, e.clientY); fbInspectFrame.style.display = "block"; // Avoid inspecting the outline, and the FirebugUI var id = targ.id; if (id && /^fbOutline\w$/.test(id)) return; if (id == "FirebugUI") return; // Avoid looking at text nodes in Opera while (targ.nodeType != 1) targ = targ.parentNode; //Firebug.Console.log(targ); Firebug.Inspector.stopInspecting(); }, onInspecting: function(e) { if (new Date().getTime() - lastInspecting > 30) { fbInspectFrame.style.display = "none"; var targ = Firebug.browser.getElementFromPoint(e.clientX, e.clientY); fbInspectFrame.style.display = "block"; // Avoid inspecting the outline, and the FirebugUI var id = targ.id; if (id && /^fbOutline\w$/.test(id)) return; if (id == "FirebugUI") return; // Avoid looking at text nodes in Opera while (targ.nodeType != 1) targ = targ.parentNode; if (targ.nodeName.toLowerCase() == "body") return; //Firebug.Console.log(e.clientX, e.clientY, targ); Firebug.Inspector.drawOutline(targ); if (ElementCache(targ)) { var target = ""+ElementCache.key(targ); var lazySelect = function() { inspectorTS = new Date().getTime(); if (Firebug.HTML) Firebug.HTML.selectTreeNode(""+ElementCache.key(targ)); }; if (inspectorTimer) { clearTimeout(inspectorTimer); inspectorTimer = null; } if (new Date().getTime() - inspectorTS > 200) setTimeout(lazySelect, 0); else inspectorTimer = setTimeout(lazySelect, 300); } lastInspecting = new Date().getTime(); } }, // TODO: xxxpedro remove this? onInspectingBody: function(e) { if (new Date().getTime() - lastInspecting > 30) { var targ = e.target; // Avoid inspecting the outline, and the FirebugUI var id = targ.id; if (id && /^fbOutline\w$/.test(id)) return; if (id == "FirebugUI") return; // Avoid looking at text nodes in Opera while (targ.nodeType != 1) targ = targ.parentNode; if (targ.nodeName.toLowerCase() == "body") return; //Firebug.Console.log(e.clientX, e.clientY, targ); Firebug.Inspector.drawOutline(targ); if (ElementCache.has(targ)) FBL.Firebug.HTML.selectTreeNode(""+ElementCache.key(targ)); lastInspecting = new Date().getTime(); } }, /** * * llttttttrr * llttttttrr * ll rr * ll rr * llbbbbbbrr * llbbbbbbrr */ drawOutline: function(el) { var border = 2; var scrollbarSize = 17; var windowSize = Firebug.browser.getWindowSize(); var scrollSize = Firebug.browser.getWindowScrollSize(); var scrollPosition = Firebug.browser.getWindowScrollPosition(); var box = Firebug.browser.getElementBox(el); var top = box.top; var left = box.left; var height = box.height; var width = box.width; var freeHorizontalSpace = scrollPosition.left + windowSize.width - left - width - (!isIE && scrollSize.height > windowSize.height ? // is *vertical* scrollbar visible scrollbarSize : 0); var freeVerticalSpace = scrollPosition.top + windowSize.height - top - height - (!isIE && scrollSize.width > windowSize.width ? // is *horizontal* scrollbar visible scrollbarSize : 0); var numVerticalBorders = freeVerticalSpace > 0 ? 2 : 1; var o = outlineElements; var style; style = o.fbOutlineT.style; style.top = top-border + "px"; style.left = left + "px"; style.height = border + "px"; // TODO: on initialize() style.width = width + "px"; style = o.fbOutlineL.style; style.top = top-border + "px"; style.left = left-border + "px"; style.height = height+ numVerticalBorders*border + "px"; style.width = border + "px"; // TODO: on initialize() style = o.fbOutlineB.style; if (freeVerticalSpace > 0) { style.top = top+height + "px"; style.left = left + "px"; style.width = width + "px"; //style.height = border + "px"; // TODO: on initialize() or worst case? } else { style.top = -2*border + "px"; style.left = -2*border + "px"; style.width = border + "px"; //style.height = border + "px"; } style = o.fbOutlineR.style; if (freeHorizontalSpace > 0) { style.top = top-border + "px"; style.left = left+width + "px"; style.height = height + numVerticalBorders*border + "px"; style.width = (freeHorizontalSpace < border ? freeHorizontalSpace : border) + "px"; } else { style.top = -2*border + "px"; style.left = -2*border + "px"; style.height = border + "px"; style.width = border + "px"; } if (!outlineVisible) this.showOutline(); }, hideOutline: function() { if (!outlineVisible) return; for (var name in outline) offlineFragment.appendChild(outlineElements[name]); outlineVisible = false; }, showOutline: function() { if (outlineVisible) return; if (boxModelVisible) this.hideBoxModel(); for (var name in outline) Firebug.browser.document.getElementsByTagName("body")[0].appendChild(outlineElements[name]); outlineVisible = true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Box Model drawBoxModel: function(el) { // avoid error when the element is not attached a document if (!el || !el.parentNode) return; var box = Firebug.browser.getElementBox(el); var windowSize = Firebug.browser.getWindowSize(); var scrollPosition = Firebug.browser.getWindowScrollPosition(); // element may be occluded by the chrome, when in frame mode var offsetHeight = Firebug.chrome.type == "frame" ? Firebug.context.persistedState.height : 0; // if element box is not inside the viewport, don't draw the box model if (box.top > scrollPosition.top + windowSize.height - offsetHeight || box.left > scrollPosition.left + windowSize.width || scrollPosition.top > box.top + box.height || scrollPosition.left > box.left + box.width ) return; var top = box.top; var left = box.left; var height = box.height; var width = box.width; var margin = Firebug.browser.getMeasurementBox(el, "margin"); var padding = Firebug.browser.getMeasurementBox(el, "padding"); var border = Firebug.browser.getMeasurementBox(el, "border"); boxModelStyle.top = top - margin.top + "px"; boxModelStyle.left = left - margin.left + "px"; boxModelStyle.height = height + margin.top + margin.bottom + "px"; boxModelStyle.width = width + margin.left + margin.right + "px"; boxBorderStyle.top = margin.top + "px"; boxBorderStyle.left = margin.left + "px"; boxBorderStyle.height = height + "px"; boxBorderStyle.width = width + "px"; boxPaddingStyle.top = margin.top + border.top + "px"; boxPaddingStyle.left = margin.left + border.left + "px"; boxPaddingStyle.height = height - border.top - border.bottom + "px"; boxPaddingStyle.width = width - border.left - border.right + "px"; boxContentStyle.top = margin.top + border.top + padding.top + "px"; boxContentStyle.left = margin.left + border.left + padding.left + "px"; boxContentStyle.height = height - border.top - padding.top - padding.bottom - border.bottom + "px"; boxContentStyle.width = width - border.left - padding.left - padding.right - border.right + "px"; if (!boxModelVisible) this.showBoxModel(); }, hideBoxModel: function() { if (!boxModelVisible) return; offlineFragment.appendChild(boxModel); boxModelVisible = false; }, showBoxModel: function() { if (boxModelVisible) return; if (outlineVisible) this.hideOutline(); Firebug.browser.document.getElementsByTagName("body")[0].appendChild(boxModel); boxModelVisible = true; } }; // ************************************************************************************************ // Inspector Internals // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Shared variables // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Internal variables var offlineFragment = null; var boxModelVisible = false; var boxModel, boxModelStyle, boxMargin, boxMarginStyle, boxBorder, boxBorderStyle, boxPadding, boxPaddingStyle, boxContent, boxContentStyle; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var resetStyle = "margin:0; padding:0; border:0; position:absolute; overflow:hidden; display:block;"; var offscreenStyle = resetStyle + "top:-1234px; left:-1234px;"; var inspectStyle = resetStyle + "z-index: 2147483500;"; var inspectFrameStyle = resetStyle + "z-index: 2147483550; top:0; left:0; background:url(" + Env.Location.skinDir + "pixel_transparent.gif);"; //if (Env.Options.enableTrace) inspectFrameStyle = resetStyle + "z-index: 2147483550; top: 0; left: 0; background: #ff0; opacity: 0.05; _filter: alpha(opacity=5);"; var inspectModelOpacity = isIE ? "filter:alpha(opacity=80);" : "opacity:0.8;"; var inspectModelStyle = inspectStyle + inspectModelOpacity; var inspectMarginStyle = inspectStyle + "background: #EDFF64; height:100%; width:100%;"; var inspectBorderStyle = inspectStyle + "background: #666;"; var inspectPaddingStyle = inspectStyle + "background: SlateBlue;"; var inspectContentStyle = inspectStyle + "background: SkyBlue;"; var outlineStyle = { fbHorizontalLine: "background: #3875D7;height: 2px;", fbVerticalLine: "background: #3875D7;width: 2px;" }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var lastInspecting = 0; var fbInspectFrame = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var outlineVisible = false; var outlineElements = {}; var outline = { "fbOutlineT": "fbHorizontalLine", "fbOutlineL": "fbVerticalLine", "fbOutlineB": "fbHorizontalLine", "fbOutlineR": "fbVerticalLine" }; var getInspectingTarget = function() { }; // ************************************************************************************************ // Section var createInspectorFrame = function createInspectorFrame() { fbInspectFrame = createGlobalElement("div"); fbInspectFrame.id = "fbInspectFrame"; fbInspectFrame.firebugIgnore = true; fbInspectFrame.style.cssText = inspectFrameStyle; Firebug.browser.document.getElementsByTagName("body")[0].appendChild(fbInspectFrame); }; var destroyInspectorFrame = function destroyInspectorFrame() { if (fbInspectFrame) { Firebug.browser.document.getElementsByTagName("body")[0].removeChild(fbInspectFrame); fbInspectFrame = null; } }; var createOutlineInspector = function createOutlineInspector() { for (var name in outline) { var el = outlineElements[name] = createGlobalElement("div"); el.id = name; el.firebugIgnore = true; el.style.cssText = inspectStyle + outlineStyle[outline[name]]; offlineFragment.appendChild(el); } }; var destroyOutlineInspector = function destroyOutlineInspector() { for (var name in outline) { var el = outlineElements[name]; el.parentNode.removeChild(el); } }; var createBoxModelInspector = function createBoxModelInspector() { boxModel = createGlobalElement("div"); boxModel.id = "fbBoxModel"; boxModel.firebugIgnore = true; boxModelStyle = boxModel.style; boxModelStyle.cssText = inspectModelStyle; boxMargin = createGlobalElement("div"); boxMargin.id = "fbBoxMargin"; boxMarginStyle = boxMargin.style; boxMarginStyle.cssText = inspectMarginStyle; boxModel.appendChild(boxMargin); boxBorder = createGlobalElement("div"); boxBorder.id = "fbBoxBorder"; boxBorderStyle = boxBorder.style; boxBorderStyle.cssText = inspectBorderStyle; boxModel.appendChild(boxBorder); boxPadding = createGlobalElement("div"); boxPadding.id = "fbBoxPadding"; boxPaddingStyle = boxPadding.style; boxPaddingStyle.cssText = inspectPaddingStyle; boxModel.appendChild(boxPadding); boxContent = createGlobalElement("div"); boxContent.id = "fbBoxContent"; boxContentStyle = boxContent.style; boxContentStyle.cssText = inspectContentStyle; boxModel.appendChild(boxContent); offlineFragment.appendChild(boxModel); }; var destroyBoxModelInspector = function destroyBoxModelInspector() { boxModel.parentNode.removeChild(boxModel); }; // ************************************************************************************************ // Section // ************************************************************************************************ }}); // Problems in IE // FIXED - eval return // FIXED - addEventListener problem in IE // FIXED doc.createRange? // // class reserved word // test all honza examples in IE6 and IE7 /* See license.txt for terms of usage */ ( /** @scope s_domplate */ function() { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** @class */ FBL.DomplateTag = function DomplateTag(tagName) { this.tagName = tagName; }; /** * @class * @extends FBL.DomplateTag */ FBL.DomplateEmbed = function DomplateEmbed() { }; /** * @class * @extends FBL.DomplateTag */ FBL.DomplateLoop = function DomplateLoop() { }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var DomplateTag = FBL.DomplateTag; var DomplateEmbed = FBL.DomplateEmbed; var DomplateLoop = FBL.DomplateLoop; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var womb = null; FBL.domplate = function() { var lastSubject; for (var i = 0; i < arguments.length; ++i) lastSubject = lastSubject ? copyObject(lastSubject, arguments[i]) : arguments[i]; for (var name in lastSubject) { var val = lastSubject[name]; if (isTag(val)) val.tag.subject = lastSubject; } return lastSubject; }; var domplate = FBL.domplate; FBL.domplate.context = function(context, fn) { var lastContext = domplate.lastContext; domplate.topContext = context; fn.apply(context); domplate.topContext = lastContext; }; FBL.TAG = function() { var embed = new DomplateEmbed(); return embed.merge(arguments); }; FBL.FOR = function() { var loop = new DomplateLoop(); return loop.merge(arguments); }; FBL.DomplateTag.prototype = { merge: function(args, oldTag) { if (oldTag) this.tagName = oldTag.tagName; this.context = oldTag ? oldTag.context : null; this.subject = oldTag ? oldTag.subject : null; this.attrs = oldTag ? copyObject(oldTag.attrs) : {}; this.classes = oldTag ? copyObject(oldTag.classes) : {}; this.props = oldTag ? copyObject(oldTag.props) : null; this.listeners = oldTag ? copyArray(oldTag.listeners) : null; this.children = oldTag ? copyArray(oldTag.children) : []; this.vars = oldTag ? copyArray(oldTag.vars) : []; var attrs = args.length ? args[0] : null; var hasAttrs = typeof(attrs) == "object" && !isTag(attrs); this.children = []; if (domplate.topContext) this.context = domplate.topContext; if (args.length) parseChildren(args, hasAttrs ? 1 : 0, this.vars, this.children); if (hasAttrs) this.parseAttrs(attrs); return creator(this, DomplateTag); }, parseAttrs: function(args) { for (var name in args) { var val = parseValue(args[name]); readPartNames(val, this.vars); if (name.indexOf("on") == 0) { var eventName = name.substr(2); if (!this.listeners) this.listeners = []; this.listeners.push(eventName, val); } else if (name.indexOf("_") == 0) { var propName = name.substr(1); if (!this.props) this.props = {}; this.props[propName] = val; } else if (name.indexOf("$") == 0) { var className = name.substr(1); if (!this.classes) this.classes = {}; this.classes[className] = val; } else { if (name == "class" && this.attrs.hasOwnProperty(name) ) this.attrs[name] += " " + val; else this.attrs[name] = val; } } }, compile: function() { if (this.renderMarkup) return; this.compileMarkup(); this.compileDOM(); //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate renderMarkup: ", this.renderMarkup); //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate renderDOM:", this.renderDOM); //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate domArgs:", this.domArgs); }, compileMarkup: function() { this.markupArgs = []; var topBlock = [], topOuts = [], blocks = [], info = {args: this.markupArgs, argIndex: 0}; this.generateMarkup(topBlock, topOuts, blocks, info); this.addCode(topBlock, topOuts, blocks); var fnBlock = ['r=(function (__code__, __context__, __in__, __out__']; for (var i = 0; i < info.argIndex; ++i) fnBlock.push(', s', i); fnBlock.push(') {'); if (this.subject) fnBlock.push('with (this) {'); if (this.context) fnBlock.push('with (__context__) {'); fnBlock.push('with (__in__) {'); fnBlock.push.apply(fnBlock, blocks); if (this.subject) fnBlock.push('}'); if (this.context) fnBlock.push('}'); fnBlock.push('}})'); function __link__(tag, code, outputs, args) { if (!tag || !tag.tag) return; tag.tag.compile(); var tagOutputs = []; var markupArgs = [code, tag.tag.context, args, tagOutputs]; markupArgs.push.apply(markupArgs, tag.tag.markupArgs); tag.tag.renderMarkup.apply(tag.tag.subject, markupArgs); outputs.push(tag); outputs.push(tagOutputs); } function __escape__(value) { function replaceChars(ch) { switch (ch) { case "<": return "&lt;"; case ">": return "&gt;"; case "&": return "&amp;"; case "'": return "&#39;"; case '"': return "&quot;"; } return "?"; }; return String(value).replace(/[<>&"']/g, replaceChars); } function __loop__(iter, outputs, fn) { var iterOuts = []; outputs.push(iterOuts); if (iter instanceof Array) iter = new ArrayIterator(iter); try { while (1) { var value = iter.next(); var itemOuts = [0,0]; iterOuts.push(itemOuts); fn.apply(this, [value, itemOuts]); } } catch (exc) { if (exc != StopIteration) throw exc; } } var js = fnBlock.join(""); var r = null; eval(js); this.renderMarkup = r; }, getVarNames: function(args) { if (this.vars) args.push.apply(args, this.vars); for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; if (isTag(child)) child.tag.getVarNames(args); else if (child instanceof Parts) { for (var i = 0; i < child.parts.length; ++i) { if (child.parts[i] instanceof Variable) { var name = child.parts[i].name; var names = name.split("."); args.push(names[0]); } } } } }, generateMarkup: function(topBlock, topOuts, blocks, info) { topBlock.push(',"<', this.tagName, '"'); for (var name in this.attrs) { if (name != "class") { var val = this.attrs[name]; topBlock.push(', " ', name, '=\\""'); addParts(val, ',', topBlock, info, true); topBlock.push(', "\\""'); } } if (this.listeners) { for (var i = 0; i < this.listeners.length; i += 2) readPartNames(this.listeners[i+1], topOuts); } if (this.props) { for (var name in this.props) readPartNames(this.props[name], topOuts); } if ( this.attrs.hasOwnProperty("class") || this.classes) { topBlock.push(', " class=\\""'); if (this.attrs.hasOwnProperty("class")) addParts(this.attrs["class"], ',', topBlock, info, true); topBlock.push(', " "'); for (var name in this.classes) { topBlock.push(', ('); addParts(this.classes[name], '', topBlock, info); topBlock.push(' ? "', name, '" + " " : "")'); } topBlock.push(', "\\""'); } topBlock.push(',">"'); this.generateChildMarkup(topBlock, topOuts, blocks, info); topBlock.push(',"</', this.tagName, '>"'); }, generateChildMarkup: function(topBlock, topOuts, blocks, info) { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; if (isTag(child)) child.tag.generateMarkup(topBlock, topOuts, blocks, info); else addParts(child, ',', topBlock, info, true); } }, addCode: function(topBlock, topOuts, blocks) { if (topBlock.length) blocks.push('__code__.push(""', topBlock.join(""), ');'); if (topOuts.length) blocks.push('__out__.push(', topOuts.join(","), ');'); topBlock.splice(0, topBlock.length); topOuts.splice(0, topOuts.length); }, addLocals: function(blocks) { var varNames = []; this.getVarNames(varNames); var map = {}; for (var i = 0; i < varNames.length; ++i) { var name = varNames[i]; if ( map.hasOwnProperty(name) ) continue; map[name] = 1; var names = name.split("."); blocks.push('var ', names[0] + ' = ' + '__in__.' + names[0] + ';'); } }, compileDOM: function() { var path = []; var blocks = []; this.domArgs = []; path.embedIndex = 0; path.loopIndex = 0; path.staticIndex = 0; path.renderIndex = 0; var nodeCount = this.generateDOM(path, blocks, this.domArgs); var fnBlock = ['r=(function (root, context, o']; for (var i = 0; i < path.staticIndex; ++i) fnBlock.push(', ', 's'+i); for (var i = 0; i < path.renderIndex; ++i) fnBlock.push(', ', 'd'+i); fnBlock.push(') {'); for (var i = 0; i < path.loopIndex; ++i) fnBlock.push('var l', i, ' = 0;'); for (var i = 0; i < path.embedIndex; ++i) fnBlock.push('var e', i, ' = 0;'); if (this.subject) fnBlock.push('with (this) {'); if (this.context) fnBlock.push('with (context) {'); fnBlock.push(blocks.join("")); if (this.subject) fnBlock.push('}'); if (this.context) fnBlock.push('}'); fnBlock.push('return ', nodeCount, ';'); fnBlock.push('})'); function __bind__(object, fn) { return function(event) { return fn.apply(object, [event]); }; } function __link__(node, tag, args) { if (!tag || !tag.tag) return; tag.tag.compile(); var domArgs = [node, tag.tag.context, 0]; domArgs.push.apply(domArgs, tag.tag.domArgs); domArgs.push.apply(domArgs, args); //if (FBTrace.DBG_DOM) FBTrace.dumpProperties("domplate__link__ domArgs:", domArgs); return tag.tag.renderDOM.apply(tag.tag.subject, domArgs); } var self = this; function __loop__(iter, fn) { var nodeCount = 0; for (var i = 0; i < iter.length; ++i) { iter[i][0] = i; iter[i][1] = nodeCount; nodeCount += fn.apply(this, iter[i]); //if (FBTrace.DBG_DOM) FBTrace.sysout("nodeCount", nodeCount); } return nodeCount; } function __path__(parent, offset) { //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate __path__ offset: "+ offset+"\n"); var root = parent; for (var i = 2; i < arguments.length; ++i) { var index = arguments[i]; if (i == 3) index += offset; if (index == -1) parent = parent.parentNode; else parent = parent.childNodes[index]; } //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate: "+arguments[2]+", root: "+ root+", parent: "+ parent+"\n"); return parent; } var js = fnBlock.join(""); //if (FBTrace.DBG_DOM) FBTrace.sysout(js.replace(/(\;|\{)/g, "$1\n")); var r = null; eval(js); this.renderDOM = r; }, generateDOM: function(path, blocks, args) { if (this.listeners || this.props) this.generateNodePath(path, blocks); if (this.listeners) { for (var i = 0; i < this.listeners.length; i += 2) { var val = this.listeners[i+1]; var arg = generateArg(val, path, args); //blocks.push('node.addEventListener("', this.listeners[i], '", __bind__(this, ', arg, '), false);'); blocks.push('addEvent(node, "', this.listeners[i], '", __bind__(this, ', arg, '), false);'); } } if (this.props) { for (var name in this.props) { var val = this.props[name]; var arg = generateArg(val, path, args); blocks.push('node.', name, ' = ', arg, ';'); } } this.generateChildDOM(path, blocks, args); return 1; }, generateNodePath: function(path, blocks) { blocks.push("var node = __path__(root, o"); for (var i = 0; i < path.length; ++i) blocks.push(",", path[i]); blocks.push(");"); }, generateChildDOM: function(path, blocks, args) { path.push(0); for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; if (isTag(child)) path[path.length-1] += '+' + child.tag.generateDOM(path, blocks, args); else path[path.length-1] += '+1'; } path.pop(); } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * FBL.DomplateEmbed.prototype = copyObject(FBL.DomplateTag.prototype, /** @lends FBL.DomplateEmbed.prototype */ { merge: function(args, oldTag) { this.value = oldTag ? oldTag.value : parseValue(args[0]); this.attrs = oldTag ? oldTag.attrs : {}; this.vars = oldTag ? copyArray(oldTag.vars) : []; var attrs = args[1]; for (var name in attrs) { var val = parseValue(attrs[name]); this.attrs[name] = val; readPartNames(val, this.vars); } return creator(this, DomplateEmbed); }, getVarNames: function(names) { if (this.value instanceof Parts) names.push(this.value.parts[0].name); if (this.vars) names.push.apply(names, this.vars); }, generateMarkup: function(topBlock, topOuts, blocks, info) { this.addCode(topBlock, topOuts, blocks); blocks.push('__link__('); addParts(this.value, '', blocks, info); blocks.push(', __code__, __out__, {'); var lastName = null; for (var name in this.attrs) { if (lastName) blocks.push(','); lastName = name; var val = this.attrs[name]; blocks.push('"', name, '":'); addParts(val, '', blocks, info); } blocks.push('});'); //this.generateChildMarkup(topBlock, topOuts, blocks, info); }, generateDOM: function(path, blocks, args) { var embedName = 'e'+path.embedIndex++; this.generateNodePath(path, blocks); var valueName = 'd' + path.renderIndex++; var argsName = 'd' + path.renderIndex++; blocks.push(embedName + ' = __link__(node, ', valueName, ', ', argsName, ');'); return embedName; } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * FBL.DomplateLoop.prototype = copyObject(FBL.DomplateTag.prototype, /** @lends FBL.DomplateLoop.prototype */ { merge: function(args, oldTag) { this.varName = oldTag ? oldTag.varName : args[0]; this.iter = oldTag ? oldTag.iter : parseValue(args[1]); this.vars = []; this.children = oldTag ? copyArray(oldTag.children) : []; var offset = Math.min(args.length, 2); parseChildren(args, offset, this.vars, this.children); return creator(this, DomplateLoop); }, getVarNames: function(names) { if (this.iter instanceof Parts) names.push(this.iter.parts[0].name); DomplateTag.prototype.getVarNames.apply(this, [names]); }, generateMarkup: function(topBlock, topOuts, blocks, info) { this.addCode(topBlock, topOuts, blocks); var iterName; if (this.iter instanceof Parts) { var part = this.iter.parts[0]; iterName = part.name; if (part.format) { for (var i = 0; i < part.format.length; ++i) iterName = part.format[i] + "(" + iterName + ")"; } } else iterName = this.iter; blocks.push('__loop__.apply(this, [', iterName, ', __out__, function(', this.varName, ', __out__) {'); this.generateChildMarkup(topBlock, topOuts, blocks, info); this.addCode(topBlock, topOuts, blocks); blocks.push('}]);'); }, generateDOM: function(path, blocks, args) { var iterName = 'd'+path.renderIndex++; var counterName = 'i'+path.loopIndex; var loopName = 'l'+path.loopIndex++; if (!path.length) path.push(-1, 0); var preIndex = path.renderIndex; path.renderIndex = 0; var nodeCount = 0; var subBlocks = []; var basePath = path[path.length-1]; for (var i = 0; i < this.children.length; ++i) { path[path.length-1] = basePath+'+'+loopName+'+'+nodeCount; var child = this.children[i]; if (isTag(child)) nodeCount += '+' + child.tag.generateDOM(path, subBlocks, args); else nodeCount += '+1'; } path[path.length-1] = basePath+'+'+loopName; blocks.push(loopName,' = __loop__.apply(this, [', iterName, ', function(', counterName,',',loopName); for (var i = 0; i < path.renderIndex; ++i) blocks.push(',d'+i); blocks.push(') {'); blocks.push(subBlocks.join("")); blocks.push('return ', nodeCount, ';'); blocks.push('}]);'); path.renderIndex = preIndex; return loopName; } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** @class */ function Variable(name, format) { this.name = name; this.format = format; } /** @class */ function Parts(parts) { this.parts = parts; } // ************************************************************************************************ function parseParts(str) { var re = /\$([_A-Za-z][_A-Za-z0-9.|]*)/g; var index = 0; var parts = []; var m; while (m = re.exec(str)) { var pre = str.substr(index, (re.lastIndex-m[0].length)-index); if (pre) parts.push(pre); var expr = m[1].split("|"); parts.push(new Variable(expr[0], expr.slice(1))); index = re.lastIndex; } if (!index) return str; var post = str.substr(index); if (post) parts.push(post); return new Parts(parts); } function parseValue(val) { return typeof(val) == 'string' ? parseParts(val) : val; } function parseChildren(args, offset, vars, children) { for (var i = offset; i < args.length; ++i) { var val = parseValue(args[i]); children.push(val); readPartNames(val, vars); } } function readPartNames(val, vars) { if (val instanceof Parts) { for (var i = 0; i < val.parts.length; ++i) { var part = val.parts[i]; if (part instanceof Variable) vars.push(part.name); } } } function generateArg(val, path, args) { if (val instanceof Parts) { var vals = []; for (var i = 0; i < val.parts.length; ++i) { var part = val.parts[i]; if (part instanceof Variable) { var varName = 'd'+path.renderIndex++; if (part.format) { for (var j = 0; j < part.format.length; ++j) varName = part.format[j] + '(' + varName + ')'; } vals.push(varName); } else vals.push('"'+part.replace(/"/g, '\\"')+'"'); } return vals.join('+'); } else { args.push(val); return 's' + path.staticIndex++; } } function addParts(val, delim, block, info, escapeIt) { var vals = []; if (val instanceof Parts) { for (var i = 0; i < val.parts.length; ++i) { var part = val.parts[i]; if (part instanceof Variable) { var partName = part.name; if (part.format) { for (var j = 0; j < part.format.length; ++j) partName = part.format[j] + "(" + partName + ")"; } if (escapeIt) vals.push("__escape__(" + partName + ")"); else vals.push(partName); } else vals.push('"'+ part + '"'); } } else if (isTag(val)) { info.args.push(val); vals.push('s'+info.argIndex++); } else vals.push('"'+ val + '"'); var parts = vals.join(delim); if (parts) block.push(delim, parts); } function isTag(obj) { return (typeof(obj) == "function" || obj instanceof Function) && !!obj.tag; } function creator(tag, cons) { var fn = new Function( "var tag = arguments.callee.tag;" + "var cons = arguments.callee.cons;" + "var newTag = new cons();" + "return newTag.merge(arguments, tag);"); fn.tag = tag; fn.cons = cons; extend(fn, Renderer); return fn; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * function copyArray(oldArray) { var ary = []; if (oldArray) for (var i = 0; i < oldArray.length; ++i) ary.push(oldArray[i]); return ary; } function copyObject(l, r) { var m = {}; extend(m, l); extend(m, r); return m; } function extend(l, r) { for (var n in r) l[n] = r[n]; } function addEvent(object, name, handler) { if (document.all) object.attachEvent("on"+name, handler); else object.addEventListener(name, handler, false); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** @class */ function ArrayIterator(array) { var index = -1; this.next = function() { if (++index >= array.length) throw StopIteration; return array[index]; }; } /** @class */ function StopIteration() {} FBL.$break = function() { throw StopIteration; }; // ************************************************************************************************ /** @namespace */ var Renderer = { renderHTML: function(args, outputs, self) { var code = []; var markupArgs = [code, this.tag.context, args, outputs]; markupArgs.push.apply(markupArgs, this.tag.markupArgs); this.tag.renderMarkup.apply(self ? self : this.tag.subject, markupArgs); return code.join(""); }, insertRows: function(args, before, self) { this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); var doc = before.ownerDocument; var div = doc.createElement("div"); div.innerHTML = "<table><tbody>"+html+"</tbody></table>"; var tbody = div.firstChild.firstChild; var parent = before.tagName == "TR" ? before.parentNode : before; var after = before.tagName == "TR" ? before.nextSibling : null; var firstRow = tbody.firstChild, lastRow; while (tbody.firstChild) { lastRow = tbody.firstChild; if (after) parent.insertBefore(lastRow, after); else parent.appendChild(lastRow); } var offset = 0; if (before.tagName == "TR") { var node = firstRow.parentNode.firstChild; for (; node && node != firstRow; node = node.nextSibling) ++offset; } var domArgs = [firstRow, this.tag.context, offset]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); this.tag.renderDOM.apply(self ? self : this.tag.subject, domArgs); return [firstRow, lastRow]; }, insertBefore: function(args, before, self) { return this.insertNode(args, before.ownerDocument, before, false, self); }, insertAfter: function(args, after, self) { return this.insertNode(args, after.ownerDocument, after, true, self); }, insertNode: function(args, doc, element, isAfter, self) { if (!args) args = {}; this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); //if (FBTrace.DBG_DOM) // FBTrace.sysout("domplate.insertNode html: "+html+"\n"); var doc = element.ownerDocument; if (!womb || womb.ownerDocument != doc) womb = doc.createElement("div"); womb.innerHTML = html; var root = womb.firstChild; if (isAfter) { while (womb.firstChild) if (element.nextSibling) element.parentNode.insertBefore(womb.firstChild, element.nextSibling); else element.parentNode.appendChild(womb.firstChild); } else { while (womb.lastChild) element.parentNode.insertBefore(womb.lastChild, element); } var domArgs = [root, this.tag.context, 0]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); //if (FBTrace.DBG_DOM) // FBTrace.sysout("domplate.insertNode domArgs:", domArgs); this.tag.renderDOM.apply(self ? self : this.tag.subject, domArgs); return root; }, /**/ /* insertAfter: function(args, before, self) { this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); var doc = before.ownerDocument; if (!womb || womb.ownerDocument != doc) womb = doc.createElement("div"); womb.innerHTML = html; var root = womb.firstChild; while (womb.firstChild) if (before.nextSibling) before.parentNode.insertBefore(womb.firstChild, before.nextSibling); else before.parentNode.appendChild(womb.firstChild); var domArgs = [root, this.tag.context, 0]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); this.tag.renderDOM.apply(self ? self : (this.tag.subject ? this.tag.subject : null), domArgs); return root; }, /**/ replace: function(args, parent, self) { this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); var root; if (parent.nodeType == 1) { parent.innerHTML = html; root = parent.firstChild; } else { if (!parent || parent.nodeType != 9) parent = document; if (!womb || womb.ownerDocument != parent) womb = parent.createElement("div"); womb.innerHTML = html; root = womb.firstChild; //womb.removeChild(root); } var domArgs = [root, this.tag.context, 0]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); this.tag.renderDOM.apply(self ? self : this.tag.subject, domArgs); return root; }, append: function(args, parent, self) { this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate.append html: "+html+"\n"); if (!womb || womb.ownerDocument != parent.ownerDocument) womb = parent.ownerDocument.createElement("div"); womb.innerHTML = html; // TODO: xxxpedro domplate port to Firebug var root = womb.firstChild; while (womb.firstChild) parent.appendChild(womb.firstChild); // clearing element reference to avoid reference error in IE8 when switching contexts womb = null; var domArgs = [root, this.tag.context, 0]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); //if (FBTrace.DBG_DOM) FBTrace.dumpProperties("domplate append domArgs:", domArgs); this.tag.renderDOM.apply(self ? self : this.tag.subject, domArgs); return root; } }; // ************************************************************************************************ function defineTags() { for (var i = 0; i < arguments.length; ++i) { var tagName = arguments[i]; var fn = new Function("var newTag = new arguments.callee.DomplateTag('"+tagName+"'); return newTag.merge(arguments);"); fn.DomplateTag = DomplateTag; var fnName = tagName.toUpperCase(); FBL[fnName] = fn; } } defineTags( "a", "button", "br", "canvas", "code", "col", "colgroup", "div", "fieldset", "form", "h1", "h2", "h3", "hr", "img", "input", "label", "legend", "li", "ol", "optgroup", "option", "p", "pre", "select", "span", "strong", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "tr", "tt", "ul", "iframe" ); })(); /* See license.txt for terms of usage */ var FirebugReps = FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Common Tags var OBJECTBOX = this.OBJECTBOX = SPAN({"class": "objectBox objectBox-$className"}); var OBJECTBLOCK = this.OBJECTBLOCK = DIV({"class": "objectBox objectBox-$className"}); var OBJECTLINK = this.OBJECTLINK = isIE6 ? // IE6 object link representation A({ "class": "objectLink objectLink-$className a11yFocus", href: "javascript:void(0)", // workaround to show XPath (a better approach would use the tooltip on mouseover, // so the XPath information would be calculated dynamically, but we need to create // a tooltip class/wrapper around Menu or InfoTip) title: "$object|FBL.getElementXPath", _repObject: "$object" }) : // Other browsers A({ "class": "objectLink objectLink-$className a11yFocus", // workaround to show XPath (a better approach would use the tooltip on mouseover, // so the XPath information would be calculated dynamically, but we need to create // a tooltip class/wrapper around Menu or InfoTip) title: "$object|FBL.getElementXPath", _repObject: "$object" }); // ************************************************************************************************ this.Undefined = domplate(Firebug.Rep, { tag: OBJECTBOX("undefined"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "undefined", supportsObject: function(object, type) { return type == "undefined"; } }); // ************************************************************************************************ this.Null = domplate(Firebug.Rep, { tag: OBJECTBOX("null"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "null", supportsObject: function(object, type) { return object == null; } }); // ************************************************************************************************ this.Nada = domplate(Firebug.Rep, { tag: SPAN(""), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "nada" }); // ************************************************************************************************ this.Number = domplate(Firebug.Rep, { tag: OBJECTBOX("$object"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "number", supportsObject: function(object, type) { return type == "boolean" || type == "number"; } }); // ************************************************************************************************ this.String = domplate(Firebug.Rep, { tag: OBJECTBOX("&quot;$object&quot;"), shortTag: OBJECTBOX("&quot;$object|cropString&quot;"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "string", supportsObject: function(object, type) { return type == "string"; } }); // ************************************************************************************************ this.Text = domplate(Firebug.Rep, { tag: OBJECTBOX("$object"), shortTag: OBJECTBOX("$object|cropString"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "text" }); // ************************************************************************************************ this.Caption = domplate(Firebug.Rep, { tag: SPAN({"class": "caption"}, "$object") }); // ************************************************************************************************ this.Warning = domplate(Firebug.Rep, { tag: DIV({"class": "warning focusRow", role : 'listitem'}, "$object|STR") }); // ************************************************************************************************ this.Func = domplate(Firebug.Rep, { tag: OBJECTLINK("$object|summarizeFunction"), summarizeFunction: function(fn) { var fnRegex = /function ([^(]+\([^)]*\)) \{/; var fnText = safeToString(fn); var m = fnRegex.exec(fnText); return m ? m[1] : "function()"; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copySource: function(fn) { copyToClipboard(safeToString(fn)); }, monitor: function(fn, script, monitored) { if (monitored) Firebug.Debugger.unmonitorScript(fn, script, "monitor"); else Firebug.Debugger.monitorScript(fn, script, "monitor"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "function", supportsObject: function(object, type) { return isFunction(object); }, inspectObject: function(fn, context) { var sourceLink = findSourceForFunction(fn, context); if (sourceLink) Firebug.chrome.select(sourceLink); if (FBTrace.DBG_FUNCTION_NAME) FBTrace.sysout("reps.function.inspectObject selected sourceLink is ", sourceLink); }, getTooltip: function(fn, context) { var script = findScriptForFunctionInContext(context, fn); if (script) return $STRF("Line", [normalizeURL(script.fileName), script.baseLineNumber]); else if (fn.toString) return fn.toString(); }, getTitle: function(fn, context) { var name = fn.name ? fn.name : "function"; return name + "()"; }, getContextMenuItems: function(fn, target, context, script) { if (!script) script = findScriptForFunctionInContext(context, fn); if (!script) return; var scriptInfo = getSourceFileAndLineByScript(context, script); var monitored = scriptInfo ? fbs.isMonitored(scriptInfo.sourceFile.href, scriptInfo.lineNo) : false; var name = script ? getFunctionName(script, context) : fn.name; return [ {label: "CopySource", command: bindFixed(this.copySource, this, fn) }, "-", {label: $STRF("ShowCallsInConsole", [name]), nol10n: true, type: "checkbox", checked: monitored, command: bindFixed(this.monitor, this, fn, script, monitored) } ]; } }); // ************************************************************************************************ /* this.jsdScript = domplate(Firebug.Rep, { copySource: function(script) { var fn = script.functionObject.getWrappedValue(); return FirebugReps.Func.copySource(fn); }, monitor: function(fn, script, monitored) { fn = script.functionObject.getWrappedValue(); return FirebugReps.Func.monitor(fn, script, monitored); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "jsdScript", inspectable: false, supportsObject: function(object, type) { return object instanceof jsdIScript; }, inspectObject: function(script, context) { var sourceLink = getSourceLinkForScript(script, context); if (sourceLink) Firebug.chrome.select(sourceLink); }, getRealObject: function(script, context) { return script; }, getTooltip: function(script) { return $STRF("jsdIScript", [script.tag]); }, getTitle: function(script, context) { var fn = script.functionObject.getWrappedValue(); return FirebugReps.Func.getTitle(fn, context); }, getContextMenuItems: function(script, target, context) { var fn = script.functionObject.getWrappedValue(); var scriptInfo = getSourceFileAndLineByScript(context, script); var monitored = scriptInfo ? fbs.isMonitored(scriptInfo.sourceFile.href, scriptInfo.lineNo) : false; var name = getFunctionName(script, context); return [ {label: "CopySource", command: bindFixed(this.copySource, this, script) }, "-", {label: $STRF("ShowCallsInConsole", [name]), nol10n: true, type: "checkbox", checked: monitored, command: bindFixed(this.monitor, this, fn, script, monitored) } ]; } }); /**/ //************************************************************************************************ this.Obj = domplate(Firebug.Rep, { tag: OBJECTLINK( SPAN({"class": "objectTitle"}, "$object|getTitle "), SPAN({"class": "objectProps"}, SPAN({"class": "objectLeftBrace", role: "presentation"}, "{"), FOR("prop", "$object|propIterator", SPAN({"class": "objectPropName", role: "presentation"}, "$prop.name"), SPAN({"class": "objectEqual", role: "presentation"}, "$prop.equal"), TAG("$prop.tag", {object: "$prop.object"}), SPAN({"class": "objectComma", role: "presentation"}, "$prop.delim") ), SPAN({"class": "objectRightBrace"}, "}") ) ), propNumberTag: SPAN({"class": "objectProp-number"}, "$object"), propStringTag: SPAN({"class": "objectProp-string"}, "&quot;$object&quot;"), propObjectTag: SPAN({"class": "objectProp-object"}, "$object"), propIterator: function (object) { ///Firebug.ObjectShortIteratorMax; var maxLength = 55; // default max length for long representation if (!object) return []; var props = []; var length = 0; var numProperties = 0; var numPropertiesShown = 0; var maxLengthReached = false; var lib = this; var propRepsMap = { "boolean": this.propNumberTag, "number": this.propNumberTag, "string": this.propStringTag, "object": this.propObjectTag }; try { var title = Firebug.Rep.getTitle(object); length += title.length; for (var name in object) { var value; try { value = object[name]; } catch (exc) { continue; } var type = typeof(value); if (type == "boolean" || type == "number" || (type == "string" && value) || (type == "object" && value && value.toString)) { var tag = propRepsMap[type]; var value = (type == "object") ? Firebug.getRep(value).getTitle(value) : value + ""; length += name.length + value.length + 4; if (length <= maxLength) { props.push({ tag: tag, name: name, object: value, equal: "=", delim: ", " }); numPropertiesShown++; } else maxLengthReached = true; } numProperties++; if (maxLengthReached && numProperties > numPropertiesShown) break; } if (numProperties > numPropertiesShown) { props.push({ object: "...", //xxxHonza localization tag: FirebugReps.Caption.tag, name: "", equal:"", delim:"" }); } else if (props.length > 0) { props[props.length-1].delim = ''; } } catch (exc) { // Sometimes we get exceptions when trying to read from certain objects, like // StorageList, but don't let that gum up the works // XXXjjb also History.previous fails because object is a web-page object which does not have // permission to read the history } return props; }, fb_1_6_propIterator: function (object, max) { max = max || 3; if (!object) return []; var props = []; var len = 0, count = 0; try { for (var name in object) { var value; try { value = object[name]; } catch (exc) { continue; } var t = typeof(value); if (t == "boolean" || t == "number" || (t == "string" && value) || (t == "object" && value && value.toString)) { var rep = Firebug.getRep(value); var tag = rep.shortTag || rep.tag; if (t == "object") { value = rep.getTitle(value); tag = rep.titleTag; } count++; if (count <= max) props.push({tag: tag, name: name, object: value, equal: "=", delim: ", "}); else break; } } if (count > max) { props[Math.max(1,max-1)] = { object: "more...", //xxxHonza localization tag: FirebugReps.Caption.tag, name: "", equal:"", delim:"" }; } else if (props.length > 0) { props[props.length-1].delim = ''; } } catch (exc) { // Sometimes we get exceptions when trying to read from certain objects, like // StorageList, but don't let that gum up the works // XXXjjb also History.previous fails because object is a web-page object which does not have // permission to read the history } return props; }, /* propIterator: function (object) { if (!object) return []; var props = []; var len = 0; try { for (var name in object) { var val; try { val = object[name]; } catch (exc) { continue; } var t = typeof val; if (t == "boolean" || t == "number" || (t == "string" && val) || (t == "object" && !isFunction(val) && val && val.toString)) { var title = (t == "object") ? Firebug.getRep(val).getTitle(val) : val+""; len += name.length + title.length + 1; if (len < 50) props.push({name: name, value: title}); else break; } } } catch (exc) { // Sometimes we get exceptions when trying to read from certain objects, like // StorageList, but don't let that gum up the works // XXXjjb also History.previous fails because object is a web-page object which does not have // permission to read the history } return props; }, /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object, type) { return true; } }); // ************************************************************************************************ this.Arr = domplate(Firebug.Rep, { tag: OBJECTBOX({_repObject: "$object"}, SPAN({"class": "arrayLeftBracket", role : "presentation"}, "["), FOR("item", "$object|arrayIterator", TAG("$item.tag", {object: "$item.object"}), SPAN({"class": "arrayComma", role : "presentation"}, "$item.delim") ), SPAN({"class": "arrayRightBracket", role : "presentation"}, "]") ), shortTag: OBJECTBOX({_repObject: "$object"}, SPAN({"class": "arrayLeftBracket", role : "presentation"}, "["), FOR("item", "$object|shortArrayIterator", TAG("$item.tag", {object: "$item.object"}), SPAN({"class": "arrayComma", role : "presentation"}, "$item.delim") ), // TODO: xxxpedro - confirm this on Firebug //FOR("prop", "$object|shortPropIterator", // " $prop.name=", // SPAN({"class": "objectPropValue"}, "$prop.value|cropString") //), SPAN({"class": "arrayRightBracket"}, "]") ), arrayIterator: function(array) { var items = []; for (var i = 0; i < array.length; ++i) { var value = array[i]; var rep = Firebug.getRep(value); var tag = rep.shortTag ? rep.shortTag : rep.tag; var delim = (i == array.length-1 ? "" : ", "); items.push({object: value, tag: tag, delim: delim}); } return items; }, shortArrayIterator: function(array) { var items = []; for (var i = 0; i < array.length && i < 3; ++i) { var value = array[i]; var rep = Firebug.getRep(value); var tag = rep.shortTag ? rep.shortTag : rep.tag; var delim = (i == array.length-1 ? "" : ", "); items.push({object: value, tag: tag, delim: delim}); } if (array.length > 3) items.push({object: (array.length-3) + " more...", tag: FirebugReps.Caption.tag, delim: ""}); return items; }, shortPropIterator: this.Obj.propIterator, getItemIndex: function(child) { var arrayIndex = 0; for (child = child.previousSibling; child; child = child.previousSibling) { if (child.repObject) ++arrayIndex; } return arrayIndex; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "array", supportsObject: function(object) { return this.isArray(object); }, // http://code.google.com/p/fbug/issues/detail?id=874 // BEGIN Yahoo BSD Source (modified here) YAHOO.lang.isArray, YUI 2.2.2 June 2007 isArray: function(obj) { try { if (!obj) return false; else if (isIE && !isFunction(obj) && typeof obj == "object" && isFinite(obj.length) && obj.nodeType != 8) return true; else if (isFinite(obj.length) && isFunction(obj.splice)) return true; else if (isFinite(obj.length) && isFunction(obj.callee)) // arguments return true; else if (instanceOf(obj, "HTMLCollection")) return true; else if (instanceOf(obj, "NodeList")) return true; else return false; } catch(exc) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout("isArray FAILS:", exc); /* Something weird: without the try/catch, OOM, with no exception?? */ FBTrace.sysout("isArray Fails on obj", obj); } } return false; }, // END Yahoo BSD SOURCE See license below. getTitle: function(object, context) { return "[" + object.length + "]"; } }); // ************************************************************************************************ this.Property = domplate(Firebug.Rep, { supportsObject: function(object) { return object instanceof Property; }, getRealObject: function(prop, context) { return prop.object[prop.name]; }, getTitle: function(prop, context) { return prop.name; } }); // ************************************************************************************************ this.NetFile = domplate(this.Obj, { supportsObject: function(object) { return object instanceof Firebug.NetFile; }, browseObject: function(file, context) { openNewTab(file.href); return true; }, getRealObject: function(file, context) { return null; } }); // ************************************************************************************************ this.Except = domplate(Firebug.Rep, { tag: OBJECTBOX({_repObject: "$object"}, "$object.message"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "exception", supportsObject: function(object) { return object instanceof ErrorCopy; } }); // ************************************************************************************************ this.Element = domplate(Firebug.Rep, { tag: OBJECTLINK( "&lt;", SPAN({"class": "nodeTag"}, "$object.nodeName|toLowerCase"), FOR("attr", "$object|attrIterator", "&nbsp;$attr.nodeName=&quot;", SPAN({"class": "nodeValue"}, "$attr.nodeValue"), "&quot;" ), "&gt;" ), shortTag: OBJECTLINK( SPAN({"class": "$object|getVisible"}, SPAN({"class": "selectorTag"}, "$object|getSelectorTag"), SPAN({"class": "selectorId"}, "$object|getSelectorId"), SPAN({"class": "selectorClass"}, "$object|getSelectorClass"), SPAN({"class": "selectorValue"}, "$object|getValue") ) ), getVisible: function(elt) { return isVisible(elt) ? "" : "selectorHidden"; }, getSelectorTag: function(elt) { return elt.nodeName.toLowerCase(); }, getSelectorId: function(elt) { return elt.id ? "#" + elt.id : ""; }, getSelectorClass: function(elt) { return elt.className ? "." + elt.className.split(" ")[0] : ""; }, getValue: function(elt) { // TODO: xxxpedro return ""; var value; if (elt instanceof HTMLImageElement) value = getFileName(elt.src); else if (elt instanceof HTMLAnchorElement) value = getFileName(elt.href); else if (elt instanceof HTMLInputElement) value = elt.value; else if (elt instanceof HTMLFormElement) value = getFileName(elt.action); else if (elt instanceof HTMLScriptElement) value = getFileName(elt.src); return value ? " " + cropString(value, 20) : ""; }, attrIterator: function(elt) { var attrs = []; var idAttr, classAttr; if (elt.attributes) { for (var i = 0; i < elt.attributes.length; ++i) { var attr = elt.attributes[i]; // we must check if the attribute is specified otherwise IE will show them if (!attr.specified || attr.nodeName && attr.nodeName.indexOf("firebug-") != -1) continue; else if (attr.nodeName == "id") idAttr = attr; else if (attr.nodeName == "class") classAttr = attr; else if (attr.nodeName == "style") attrs.push({ nodeName: attr.nodeName, nodeValue: attr.nodeValue || // IE won't recognize the attr.nodeValue of <style> nodes ... // and will return CSS property names in upper case, so we need to convert them elt.style.cssText.replace(/([^\s]+)\s*:/g, function(m,g){return g.toLowerCase()+":"}) }); else attrs.push(attr); } } if (classAttr) attrs.splice(0, 0, classAttr); if (idAttr) attrs.splice(0, 0, idAttr); return attrs; }, shortAttrIterator: function(elt) { var attrs = []; if (elt.attributes) { for (var i = 0; i < elt.attributes.length; ++i) { var attr = elt.attributes[i]; if (attr.nodeName == "id" || attr.nodeName == "class") attrs.push(attr); } } return attrs; }, getHidden: function(elt) { return isVisible(elt) ? "" : "nodeHidden"; }, getXPath: function(elt) { return getElementTreeXPath(elt); }, // TODO: xxxpedro remove this? getNodeText: function(element) { var text = element.textContent; if (Firebug.showFullTextNodes) return text; else return cropString(text, 50); }, /**/ getNodeTextGroups: function(element) { var text = element.textContent; if (!Firebug.showFullTextNodes) { text=cropString(text,50); } var escapeGroups=[]; if (Firebug.showTextNodesWithWhitespace) escapeGroups.push({ 'group': 'whitespace', 'class': 'nodeWhiteSpace', 'extra': { '\t': '_Tab', '\n': '_Para', ' ' : '_Space' } }); if (Firebug.showTextNodesWithEntities) escapeGroups.push({ 'group':'text', 'class':'nodeTextEntity', 'extra':{} }); if (escapeGroups.length) return escapeGroupsForEntities(text, escapeGroups); else return [{str:text,'class':'',extra:''}]; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copyHTML: function(elt) { var html = getElementXML(elt); copyToClipboard(html); }, copyInnerHTML: function(elt) { copyToClipboard(elt.innerHTML); }, copyXPath: function(elt) { var xpath = getElementXPath(elt); copyToClipboard(xpath); }, persistor: function(context, xpath) { var elts = xpath ? getElementsByXPath(context.window.document, xpath) : null; return elts && elts.length ? elts[0] : null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "element", supportsObject: function(object) { //return object instanceof Element || object.nodeType == 1 && typeof object.nodeName == "string"; return instanceOf(object, "Element"); }, browseObject: function(elt, context) { var tag = elt.nodeName.toLowerCase(); if (tag == "script") openNewTab(elt.src); else if (tag == "link") openNewTab(elt.href); else if (tag == "a") openNewTab(elt.href); else if (tag == "img") openNewTab(elt.src); return true; }, persistObject: function(elt, context) { var xpath = getElementXPath(elt); return bind(this.persistor, top, xpath); }, getTitle: function(element, context) { return getElementCSSSelector(element); }, getTooltip: function(elt) { return this.getXPath(elt); }, getContextMenuItems: function(elt, target, context) { var monitored = areEventsMonitored(elt, null, context); return [ {label: "CopyHTML", command: bindFixed(this.copyHTML, this, elt) }, {label: "CopyInnerHTML", command: bindFixed(this.copyInnerHTML, this, elt) }, {label: "CopyXPath", command: bindFixed(this.copyXPath, this, elt) }, "-", {label: "ShowEventsInConsole", type: "checkbox", checked: monitored, command: bindFixed(toggleMonitorEvents, FBL, elt, null, monitored, context) }, "-", {label: "ScrollIntoView", command: bindFixed(elt.scrollIntoView, elt) } ]; } }); // ************************************************************************************************ this.TextNode = domplate(Firebug.Rep, { tag: OBJECTLINK( "&lt;", SPAN({"class": "nodeTag"}, "TextNode"), "&nbsp;textContent=&quot;", SPAN({"class": "nodeValue"}, "$object.textContent|cropString"), "&quot;", "&gt;" ), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "textNode", supportsObject: function(object) { return object instanceof Text; } }); // ************************************************************************************************ this.Document = domplate(Firebug.Rep, { tag: OBJECTLINK("Document ", SPAN({"class": "objectPropValue"}, "$object|getLocation")), getLocation: function(doc) { return doc.location ? getFileName(doc.location.href) : ""; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object) { //return object instanceof Document || object instanceof XMLDocument; return instanceOf(object, "Document"); }, browseObject: function(doc, context) { openNewTab(doc.location.href); return true; }, persistObject: function(doc, context) { return this.persistor; }, persistor: function(context) { return context.window.document; }, getTitle: function(win, context) { return "document"; }, getTooltip: function(doc) { return doc.location.href; } }); // ************************************************************************************************ this.StyleSheet = domplate(Firebug.Rep, { tag: OBJECTLINK("StyleSheet ", SPAN({"class": "objectPropValue"}, "$object|getLocation")), getLocation: function(styleSheet) { return getFileName(styleSheet.href); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copyURL: function(styleSheet) { copyToClipboard(styleSheet.href); }, openInTab: function(styleSheet) { openNewTab(styleSheet.href); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object) { //return object instanceof CSSStyleSheet; return instanceOf(object, "CSSStyleSheet"); }, browseObject: function(styleSheet, context) { openNewTab(styleSheet.href); return true; }, persistObject: function(styleSheet, context) { return bind(this.persistor, top, styleSheet.href); }, getTooltip: function(styleSheet) { return styleSheet.href; }, getContextMenuItems: function(styleSheet, target, context) { return [ {label: "CopyLocation", command: bindFixed(this.copyURL, this, styleSheet) }, "-", {label: "OpenInTab", command: bindFixed(this.openInTab, this, styleSheet) } ]; }, persistor: function(context, href) { return getStyleSheetByHref(href, context); } }); // ************************************************************************************************ this.Window = domplate(Firebug.Rep, { tag: OBJECTLINK("Window ", SPAN({"class": "objectPropValue"}, "$object|getLocation")), getLocation: function(win) { try { return (win && win.location && !win.closed) ? getFileName(win.location.href) : ""; } catch (exc) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("reps.Window window closed?"); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object) { return instanceOf(object, "Window"); }, browseObject: function(win, context) { openNewTab(win.location.href); return true; }, persistObject: function(win, context) { return this.persistor; }, persistor: function(context) { return context.window; }, getTitle: function(win, context) { return "window"; }, getTooltip: function(win) { if (win && !win.closed) return win.location.href; } }); // ************************************************************************************************ this.Event = domplate(Firebug.Rep, { tag: TAG("$copyEventTag", {object: "$object|copyEvent"}), copyEventTag: OBJECTLINK("$object|summarizeEvent"), summarizeEvent: function(event) { var info = [event.type, ' ']; var eventFamily = getEventFamily(event.type); if (eventFamily == "mouse") info.push("clientX=", event.clientX, ", clientY=", event.clientY); else if (eventFamily == "key") info.push("charCode=", event.charCode, ", keyCode=", event.keyCode); return info.join(""); }, copyEvent: function(event) { return new EventCopy(event); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object) { //return object instanceof Event || object instanceof EventCopy; return instanceOf(object, "Event") || instanceOf(object, "EventCopy"); }, getTitle: function(event, context) { return "Event " + event.type; } }); // ************************************************************************************************ this.SourceLink = domplate(Firebug.Rep, { tag: OBJECTLINK({$collapsed: "$object|hideSourceLink"}, "$object|getSourceLinkTitle"), hideSourceLink: function(sourceLink) { return sourceLink ? sourceLink.href.indexOf("XPCSafeJSObjectWrapper") != -1 : true; }, getSourceLinkTitle: function(sourceLink) { if (!sourceLink) return ""; try { var fileName = getFileName(sourceLink.href); fileName = decodeURIComponent(fileName); fileName = cropString(fileName, 17); } catch(exc) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("reps.getSourceLinkTitle decodeURIComponent fails for \'"+fileName+"\': "+exc, exc); } return typeof sourceLink.line == "number" ? fileName + " (line " + sourceLink.line + ")" : fileName; // TODO: xxxpedro //return $STRF("Line", [fileName, sourceLink.line]); }, copyLink: function(sourceLink) { copyToClipboard(sourceLink.href); }, openInTab: function(sourceLink) { openNewTab(sourceLink.href); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "sourceLink", supportsObject: function(object) { return object instanceof SourceLink; }, getTooltip: function(sourceLink) { return decodeURI(sourceLink.href); }, inspectObject: function(sourceLink, context) { if (sourceLink.type == "js") { var scriptFile = getSourceFileByHref(sourceLink.href, context); if (scriptFile) return Firebug.chrome.select(sourceLink); } else if (sourceLink.type == "css") { // If an object is defined, treat it as the highest priority for // inspect actions if (sourceLink.object) { Firebug.chrome.select(sourceLink.object); return; } var stylesheet = getStyleSheetByHref(sourceLink.href, context); if (stylesheet) { var ownerNode = stylesheet.ownerNode; if (ownerNode) { Firebug.chrome.select(sourceLink, "html"); return; } var panel = context.getPanel("stylesheet"); if (panel && panel.getRuleByLine(stylesheet, sourceLink.line)) return Firebug.chrome.select(sourceLink); } } // Fallback is to just open the view-source window on the file viewSource(sourceLink.href, sourceLink.line); }, browseObject: function(sourceLink, context) { openNewTab(sourceLink.href); return true; }, getContextMenuItems: function(sourceLink, target, context) { return [ {label: "CopyLocation", command: bindFixed(this.copyLink, this, sourceLink) }, "-", {label: "OpenInTab", command: bindFixed(this.openInTab, this, sourceLink) } ]; } }); // ************************************************************************************************ this.SourceFile = domplate(this.SourceLink, { tag: OBJECTLINK({$collapsed: "$object|hideSourceLink"}, "$object|getSourceLinkTitle"), persistor: function(context, href) { return getSourceFileByHref(href, context); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "sourceFile", supportsObject: function(object) { return object instanceof SourceFile; }, persistObject: function(sourceFile) { return bind(this.persistor, top, sourceFile.href); }, browseObject: function(sourceLink, context) { }, getTooltip: function(sourceFile) { return sourceFile.href; } }); // ************************************************************************************************ this.StackFrame = domplate(Firebug.Rep, // XXXjjb Since the repObject is fn the stack does not have correct line numbers { tag: OBJECTBLOCK( A({"class": "objectLink objectLink-function focusRow a11yFocus", _repObject: "$object.fn"}, "$object|getCallName"), " ( ", FOR("arg", "$object|argIterator", TAG("$arg.tag", {object: "$arg.value"}), SPAN({"class": "arrayComma"}, "$arg.delim") ), " )", SPAN({"class": "objectLink-sourceLink objectLink"}, "$object|getSourceLinkTitle") ), getCallName: function(frame) { //TODO: xxxpedro reps StackFrame return frame.name || "anonymous"; //return getFunctionName(frame.script, frame.context); }, getSourceLinkTitle: function(frame) { //TODO: xxxpedro reps StackFrame var fileName = cropString(getFileName(frame.href), 20); return fileName + (frame.lineNo ? " (line " + frame.lineNo + ")" : ""); var fileName = cropString(getFileName(frame.href), 17); return $STRF("Line", [fileName, frame.lineNo]); }, argIterator: function(frame) { if (!frame.args) return []; var items = []; for (var i = 0; i < frame.args.length; ++i) { var arg = frame.args[i]; if (!arg) break; var rep = Firebug.getRep(arg.value); var tag = rep.shortTag ? rep.shortTag : rep.tag; var delim = (i == frame.args.length-1 ? "" : ", "); items.push({name: arg.name, value: arg.value, tag: tag, delim: delim}); } return items; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "stackFrame", supportsObject: function(object) { return object instanceof StackFrame; }, inspectObject: function(stackFrame, context) { var sourceLink = new SourceLink(stackFrame.href, stackFrame.lineNo, "js"); Firebug.chrome.select(sourceLink); }, getTooltip: function(stackFrame, context) { return $STRF("Line", [stackFrame.href, stackFrame.lineNo]); } }); // ************************************************************************************************ this.StackTrace = domplate(Firebug.Rep, { tag: FOR("frame", "$object.frames focusRow", TAG(this.StackFrame.tag, {object: "$frame"}) ), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "stackTrace", supportsObject: function(object) { return object instanceof StackTrace; } }); // ************************************************************************************************ this.jsdStackFrame = domplate(Firebug.Rep, { inspectable: false, supportsObject: function(object) { return (object instanceof jsdIStackFrame) && (object.isValid); }, getTitle: function(frame, context) { if (!frame.isValid) return "(invalid frame)"; // XXXjjb avoid frame.script == null return getFunctionName(frame.script, context); }, getTooltip: function(frame, context) { if (!frame.isValid) return "(invalid frame)"; // XXXjjb avoid frame.script == null var sourceInfo = FBL.getSourceFileAndLineByScript(context, frame.script, frame); if (sourceInfo) return $STRF("Line", [sourceInfo.sourceFile.href, sourceInfo.lineNo]); else return $STRF("Line", [frame.script.fileName, frame.line]); }, getContextMenuItems: function(frame, target, context) { var fn = frame.script.functionObject.getWrappedValue(); return FirebugReps.Func.getContextMenuItems(fn, target, context, frame.script); } }); // ************************************************************************************************ this.ErrorMessage = domplate(Firebug.Rep, { tag: OBJECTBOX({ $hasTwisty: "$object|hasStackTrace", $hasBreakSwitch: "$object|hasBreakSwitch", $breakForError: "$object|hasErrorBreak", _repObject: "$object", _stackTrace: "$object|getLastErrorStackTrace", onclick: "$onToggleError"}, DIV({"class": "errorTitle a11yFocus", role : 'checkbox', 'aria-checked' : 'false'}, "$object.message|getMessage" ), DIV({"class": "errorTrace"}), DIV({"class": "errorSourceBox errorSource-$object|getSourceType"}, IMG({"class": "errorBreak a11yFocus", src:"blank.gif", role : 'checkbox', 'aria-checked':'false', title: "Break on this error"}), A({"class": "errorSource a11yFocus"}, "$object|getLine") ), TAG(this.SourceLink.tag, {object: "$object|getSourceLink"}) ), getLastErrorStackTrace: function(error) { return error.trace; }, hasStackTrace: function(error) { var url = error.href.toString(); var fromCommandLine = (url.indexOf("XPCSafeJSObjectWrapper") != -1); return !fromCommandLine && error.trace; }, hasBreakSwitch: function(error) { return error.href && error.lineNo > 0; }, hasErrorBreak: function(error) { return fbs.hasErrorBreakpoint(error.href, error.lineNo); }, getMessage: function(message) { var re = /\[Exception... "(.*?)" nsresult:/; var m = re.exec(message); return m ? m[1] : message; }, getLine: function(error) { if (error.category == "js") { if (error.source) return cropString(error.source, 80); else if (error.href && error.href.indexOf("XPCSafeJSObjectWrapper") == -1) return cropString(error.getSourceLine(), 80); } }, getSourceLink: function(error) { var ext = error.category == "css" ? "css" : "js"; return error.lineNo ? new SourceLink(error.href, error.lineNo, ext) : null; }, getSourceType: function(error) { // Errors occurring inside of HTML event handlers look like "foo.html (line 1)" // so let's try to skip those if (error.source) return "syntax"; else if (error.lineNo == 1 && getFileExtension(error.href) != "js") return "none"; else if (error.category == "css") return "none"; else if (!error.href || !error.lineNo) return "none"; else return "exec"; }, onToggleError: function(event) { var target = event.currentTarget; if (hasClass(event.target, "errorBreak")) { this.breakOnThisError(target.repObject); } else if (hasClass(event.target, "errorSource")) { var panel = Firebug.getElementPanel(event.target); this.inspectObject(target.repObject, panel.context); } else if (hasClass(event.target, "errorTitle")) { var traceBox = target.childNodes[1]; toggleClass(target, "opened"); event.target.setAttribute('aria-checked', hasClass(target, "opened")); if (hasClass(target, "opened")) { if (target.stackTrace) var node = FirebugReps.StackTrace.tag.append({object: target.stackTrace}, traceBox); if (Firebug.A11yModel.enabled) { var panel = Firebug.getElementPanel(event.target); dispatch([Firebug.A11yModel], "onLogRowContentCreated", [panel , traceBox]); } } else clearNode(traceBox); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copyError: function(error) { var message = [ this.getMessage(error.message), error.href, "Line " + error.lineNo ]; copyToClipboard(message.join("\n")); }, breakOnThisError: function(error) { if (this.hasErrorBreak(error)) Firebug.Debugger.clearErrorBreakpoint(error.href, error.lineNo); else Firebug.Debugger.setErrorBreakpoint(error.href, error.lineNo); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "errorMessage", inspectable: false, supportsObject: function(object) { return object instanceof ErrorMessage; }, inspectObject: function(error, context) { var sourceLink = this.getSourceLink(error); FirebugReps.SourceLink.inspectObject(sourceLink, context); }, getContextMenuItems: function(error, target, context) { var breakOnThisError = this.hasErrorBreak(error); var items = [ {label: "CopyError", command: bindFixed(this.copyError, this, error) } ]; if (error.category == "css") { items.push( "-", {label: "BreakOnThisError", type: "checkbox", checked: breakOnThisError, command: bindFixed(this.breakOnThisError, this, error) }, optionMenu("BreakOnAllErrors", "breakOnErrors") ); } return items; } }); // ************************************************************************************************ this.Assert = domplate(Firebug.Rep, { tag: DIV( DIV({"class": "errorTitle"}), DIV({"class": "assertDescription"}) ), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "assert", inspectObject: function(error, context) { var sourceLink = this.getSourceLink(error); Firebug.chrome.select(sourceLink); }, getContextMenuItems: function(error, target, context) { var breakOnThisError = this.hasErrorBreak(error); return [ {label: "CopyError", command: bindFixed(this.copyError, this, error) }, "-", {label: "BreakOnThisError", type: "checkbox", checked: breakOnThisError, command: bindFixed(this.breakOnThisError, this, error) }, {label: "BreakOnAllErrors", type: "checkbox", checked: Firebug.breakOnErrors, command: bindFixed(this.breakOnAllErrors, this, error) } ]; } }); // ************************************************************************************************ this.SourceText = domplate(Firebug.Rep, { tag: DIV( FOR("line", "$object|lineIterator", DIV({"class": "sourceRow", role : "presentation"}, SPAN({"class": "sourceLine", role : "presentation"}, "$line.lineNo"), SPAN({"class": "sourceRowText", role : "presentation"}, "$line.text") ) ) ), lineIterator: function(sourceText) { var maxLineNoChars = (sourceText.lines.length + "").length; var list = []; for (var i = 0; i < sourceText.lines.length; ++i) { // Make sure all line numbers are the same width (with a fixed-width font) var lineNo = (i+1) + ""; while (lineNo.length < maxLineNoChars) lineNo = " " + lineNo; list.push({lineNo: lineNo, text: sourceText.lines[i]}); } return list; }, getHTML: function(sourceText) { return getSourceLineRange(sourceText, 1, sourceText.lines.length); } }); //************************************************************************************************ this.nsIDOMHistory = domplate(Firebug.Rep, { tag:OBJECTBOX({onclick: "$showHistory"}, OBJECTLINK("$object|summarizeHistory") ), className: "nsIDOMHistory", summarizeHistory: function(history) { try { var items = history.length; return items + " history entries"; } catch(exc) { return "object does not support history (nsIDOMHistory)"; } }, showHistory: function(history) { try { var items = history.length; // if this throws, then unsupported Firebug.chrome.select(history); } catch (exc) { } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * supportsObject: function(object, type) { return (object instanceof Ci.nsIDOMHistory); } }); // ************************************************************************************************ this.ApplicationCache = domplate(Firebug.Rep, { tag:OBJECTBOX({onclick: "$showApplicationCache"}, OBJECTLINK("$object|summarizeCache") ), summarizeCache: function(applicationCache) { try { return applicationCache.length + " items in offline cache"; } catch(exc) { return "https://bugzilla.mozilla.org/show_bug.cgi?id=422264"; } }, showApplicationCache: function(event) { openNewTab("https://bugzilla.mozilla.org/show_bug.cgi?id=422264"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "applicationCache", supportsObject: function(object, type) { if (Ci.nsIDOMOfflineResourceList) return (object instanceof Ci.nsIDOMOfflineResourceList); } }); this.Storage = domplate(Firebug.Rep, { tag: OBJECTBOX({onclick: "$show"}, OBJECTLINK("$object|summarize")), summarize: function(storage) { return storage.length +" items in Storage"; }, show: function(storage) { openNewTab("http://dev.w3.org/html5/webstorage/#storage-0"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "Storage", supportsObject: function(object, type) { return (object instanceof Storage); } }); // ************************************************************************************************ Firebug.registerRep( //this.nsIDOMHistory, // make this early to avoid exceptions this.Undefined, this.Null, this.Number, this.String, this.Window, //this.ApplicationCache, // must come before Arr (array) else exceptions. //this.ErrorMessage, this.Element, //this.TextNode, this.Document, this.StyleSheet, this.Event, //this.SourceLink, //this.SourceFile, //this.StackTrace, //this.StackFrame, //this.jsdStackFrame, //this.jsdScript, //this.NetFile, this.Property, this.Except, this.Arr ); Firebug.setDefaultReps(this.Func, this.Obj); }}); // ************************************************************************************************ /* * The following is http://developer.yahoo.com/yui/license.txt and applies to only code labeled "Yahoo BSD Source" * in only this file reps.js. John J. Barton June 2007. * Software License Agreement (BSD License) Copyright (c) 2006, Yahoo! Inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * / */ /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants var saveTimeout = 400; var pageAmount = 10; // ************************************************************************************************ // Globals var currentTarget = null; var currentGroup = null; var currentPanel = null; var currentEditor = null; var defaultEditor = null; var originalClassName = null; var originalValue = null; var defaultValue = null; var previousValue = null; var invalidEditor = false; var ignoreNextInput = false; // ************************************************************************************************ Firebug.Editor = extend(Firebug.Module, { supportsStopEvent: true, dispatchName: "editor", tabCharacter: " ", startEditing: function(target, value, editor) { this.stopEditing(); if (hasClass(target, "insertBefore") || hasClass(target, "insertAfter")) return; var panel = Firebug.getElementPanel(target); if (!panel.editable) return; if (FBTrace.DBG_EDITOR) FBTrace.sysout("editor.startEditing " + value, target); defaultValue = target.getAttribute("defaultValue"); if (value == undefined) { var textContent = isIE ? "innerText" : "textContent"; value = target[textContent]; if (value == defaultValue) value = ""; } originalValue = previousValue = value; invalidEditor = false; currentTarget = target; currentPanel = panel; currentGroup = getAncestorByClass(target, "editGroup"); currentPanel.editing = true; var panelEditor = currentPanel.getEditor(target, value); currentEditor = editor ? editor : panelEditor; if (!currentEditor) currentEditor = getDefaultEditor(currentPanel); var inlineParent = getInlineParent(target); var targetSize = getOffsetSize(inlineParent); setClass(panel.panelNode, "editing"); setClass(target, "editing"); if (currentGroup) setClass(currentGroup, "editing"); currentEditor.show(target, currentPanel, value, targetSize); //dispatch(this.fbListeners, "onBeginEditing", [currentPanel, currentEditor, target, value]); currentEditor.beginEditing(target, value); if (FBTrace.DBG_EDITOR) FBTrace.sysout("Editor start panel "+currentPanel.name); this.attachListeners(currentEditor, panel.context); }, stopEditing: function(cancel) { if (!currentTarget) return; if (FBTrace.DBG_EDITOR) FBTrace.sysout("editor.stopEditing cancel:" + cancel+" saveTimeout: "+this.saveTimeout); clearTimeout(this.saveTimeout); delete this.saveTimeout; this.detachListeners(currentEditor, currentPanel.context); removeClass(currentPanel.panelNode, "editing"); removeClass(currentTarget, "editing"); if (currentGroup) removeClass(currentGroup, "editing"); var value = currentEditor.getValue(); if (value == defaultValue) value = ""; var removeGroup = currentEditor.endEditing(currentTarget, value, cancel); try { if (cancel) { //dispatch([Firebug.A11yModel], 'onInlineEditorClose', [currentPanel, currentTarget, removeGroup && !originalValue]); if (value != originalValue) this.saveEditAndNotifyListeners(currentTarget, originalValue, previousValue); if (removeGroup && !originalValue && currentGroup) currentGroup.parentNode.removeChild(currentGroup); } else if (!value) { this.saveEditAndNotifyListeners(currentTarget, null, previousValue); if (removeGroup && currentGroup) currentGroup.parentNode.removeChild(currentGroup); } else this.save(value); } catch (exc) { //throw exc.message; //ERROR(exc); } currentEditor.hide(); currentPanel.editing = false; //dispatch(this.fbListeners, "onStopEdit", [currentPanel, currentEditor, currentTarget]); //if (FBTrace.DBG_EDITOR) // FBTrace.sysout("Editor stop panel "+currentPanel.name); currentTarget = null; currentGroup = null; currentPanel = null; currentEditor = null; originalValue = null; invalidEditor = false; return value; }, cancelEditing: function() { return this.stopEditing(true); }, update: function(saveNow) { if (this.saveTimeout) clearTimeout(this.saveTimeout); invalidEditor = true; currentEditor.layout(); if (saveNow) this.save(); else { var context = currentPanel.context; this.saveTimeout = context.setTimeout(bindFixed(this.save, this), saveTimeout); if (FBTrace.DBG_EDITOR) FBTrace.sysout("editor.update saveTimeout: "+this.saveTimeout); } }, save: function(value) { if (!invalidEditor) return; if (value == undefined) value = currentEditor.getValue(); if (FBTrace.DBG_EDITOR) FBTrace.sysout("editor.save saveTimeout: "+this.saveTimeout+" currentPanel: "+(currentPanel?currentPanel.name:"null")); try { this.saveEditAndNotifyListeners(currentTarget, value, previousValue); previousValue = value; invalidEditor = false; } catch (exc) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("editor.save FAILS "+exc, exc); } }, saveEditAndNotifyListeners: function(currentTarget, value, previousValue) { currentEditor.saveEdit(currentTarget, value, previousValue); //dispatch(this.fbListeners, "onSaveEdit", [currentPanel, currentEditor, currentTarget, value, previousValue]); }, setEditTarget: function(element) { if (!element) { dispatch([Firebug.A11yModel], 'onInlineEditorClose', [currentPanel, currentTarget, true]); this.stopEditing(); } else if (hasClass(element, "insertBefore")) this.insertRow(element, "before"); else if (hasClass(element, "insertAfter")) this.insertRow(element, "after"); else this.startEditing(element); }, tabNextEditor: function() { if (!currentTarget) return; var value = currentEditor.getValue(); var nextEditable = currentTarget; do { nextEditable = !value && currentGroup ? getNextOutsider(nextEditable, currentGroup) : getNextByClass(nextEditable, "editable"); } while (nextEditable && !nextEditable.offsetHeight); this.setEditTarget(nextEditable); }, tabPreviousEditor: function() { if (!currentTarget) return; var value = currentEditor.getValue(); var prevEditable = currentTarget; do { prevEditable = !value && currentGroup ? getPreviousOutsider(prevEditable, currentGroup) : getPreviousByClass(prevEditable, "editable"); } while (prevEditable && !prevEditable.offsetHeight); this.setEditTarget(prevEditable); }, insertRow: function(relative, insertWhere) { var group = relative || getAncestorByClass(currentTarget, "editGroup") || currentTarget; var value = this.stopEditing(); currentPanel = Firebug.getElementPanel(group); currentEditor = currentPanel.getEditor(group, value); if (!currentEditor) currentEditor = getDefaultEditor(currentPanel); currentGroup = currentEditor.insertNewRow(group, insertWhere); if (!currentGroup) return; var editable = hasClass(currentGroup, "editable") ? currentGroup : getNextByClass(currentGroup, "editable"); if (editable) this.setEditTarget(editable); }, insertRowForObject: function(relative) { var container = getAncestorByClass(relative, "insertInto"); if (container) { relative = getChildByClass(container, "insertBefore"); if (relative) this.insertRow(relative, "before"); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * attachListeners: function(editor, context) { var win = isIE ? currentTarget.ownerDocument.parentWindow : currentTarget.ownerDocument.defaultView; addEvent(win, "resize", this.onResize); addEvent(win, "blur", this.onBlur); var chrome = Firebug.chrome; this.listeners = [ chrome.keyCodeListen("ESCAPE", null, bind(this.cancelEditing, this)) ]; if (editor.arrowCompletion) { this.listeners.push( chrome.keyCodeListen("UP", null, bindFixed(editor.completeValue, editor, -1)), chrome.keyCodeListen("DOWN", null, bindFixed(editor.completeValue, editor, 1)), chrome.keyCodeListen("PAGE_UP", null, bindFixed(editor.completeValue, editor, -pageAmount)), chrome.keyCodeListen("PAGE_DOWN", null, bindFixed(editor.completeValue, editor, pageAmount)) ); } if (currentEditor.tabNavigation) { this.listeners.push( chrome.keyCodeListen("RETURN", null, bind(this.tabNextEditor, this)), chrome.keyCodeListen("RETURN", isControl, bind(this.insertRow, this, null, "after")), chrome.keyCodeListen("TAB", null, bind(this.tabNextEditor, this)), chrome.keyCodeListen("TAB", isShift, bind(this.tabPreviousEditor, this)) ); } else if (currentEditor.multiLine) { this.listeners.push( chrome.keyCodeListen("TAB", null, insertTab) ); } else { this.listeners.push( chrome.keyCodeListen("RETURN", null, bindFixed(this.stopEditing, this)) ); if (currentEditor.tabCompletion) { this.listeners.push( chrome.keyCodeListen("TAB", null, bind(editor.completeValue, editor, 1)), chrome.keyCodeListen("TAB", isShift, bind(editor.completeValue, editor, -1)) ); } } }, detachListeners: function(editor, context) { if (!this.listeners) return; var win = isIE ? currentTarget.ownerDocument.parentWindow : currentTarget.ownerDocument.defaultView; removeEvent(win, "resize", this.onResize); removeEvent(win, "blur", this.onBlur); var chrome = Firebug.chrome; if (chrome) { for (var i = 0; i < this.listeners.length; ++i) chrome.keyIgnore(this.listeners[i]); } delete this.listeners; }, onResize: function(event) { currentEditor.layout(true); }, onBlur: function(event) { if (currentEditor.enterOnBlur && isAncestor(event.target, currentEditor.box)) this.stopEditing(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Module initialize: function() { Firebug.Module.initialize.apply(this, arguments); this.onResize = bindFixed(this.onResize, this); this.onBlur = bind(this.onBlur, this); }, disable: function() { this.stopEditing(); }, showContext: function(browser, context) { this.stopEditing(); }, showPanel: function(browser, panel) { this.stopEditing(); } }); // ************************************************************************************************ // BaseEditor Firebug.BaseEditor = extend(Firebug.MeasureBox, { getValue: function() { }, setValue: function(value) { }, show: function(target, panel, value, textSize, targetSize) { }, hide: function() { }, layout: function(forceAll) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Support for context menus within inline editors. getContextMenuItems: function(target) { var items = []; items.push({label: "Cut", commandID: "cmd_cut"}); items.push({label: "Copy", commandID: "cmd_copy"}); items.push({label: "Paste", commandID: "cmd_paste"}); return items; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Editor Module listeners will get "onBeginEditing" just before this call beginEditing: function(target, value) { }, // Editor Module listeners will get "onSaveEdit" just after this call saveEdit: function(target, value, previousValue) { }, endEditing: function(target, value, cancel) { // Remove empty groups by default return true; }, insertNewRow: function(target, insertWhere) { } }); // ************************************************************************************************ // InlineEditor // basic inline editor attributes var inlineEditorAttributes = { "class": "textEditorInner", type: "text", spellcheck: "false", onkeypress: "$onKeyPress", onoverflow: "$onOverflow", oncontextmenu: "$onContextMenu" }; // IE does not support the oninput event, so we're using the onkeydown to signalize // the relevant keyboard events, and the onpropertychange to actually handle the // input event, which should happen after the onkeydown event is fired and after the // value of the input is updated, but before the onkeyup and before the input (with the // new value) is rendered if (isIE) { inlineEditorAttributes.onpropertychange = "$onInput"; inlineEditorAttributes.onkeydown = "$onKeyDown"; } // for other browsers we use the oninput event else { inlineEditorAttributes.oninput = "$onInput"; } Firebug.InlineEditor = function(doc) { this.initializeInline(doc); }; Firebug.InlineEditor.prototype = domplate(Firebug.BaseEditor, { enterOnBlur: true, outerMargin: 8, shadowExpand: 7, tag: DIV({"class": "inlineEditor"}, DIV({"class": "textEditorTop1"}, DIV({"class": "textEditorTop2"}) ), DIV({"class": "textEditorInner1"}, DIV({"class": "textEditorInner2"}, INPUT( inlineEditorAttributes ) ) ), DIV({"class": "textEditorBottom1"}, DIV({"class": "textEditorBottom2"}) ) ), inputTag : INPUT({"class": "textEditorInner", type: "text", /*oninput: "$onInput",*/ onkeypress: "$onKeyPress", onoverflow: "$onOverflow"} ), expanderTag: IMG({"class": "inlineExpander", src: "blank.gif"}), initialize: function() { this.fixedWidth = false; this.completeAsYouType = true; this.tabNavigation = true; this.multiLine = false; this.tabCompletion = false; this.arrowCompletion = true; this.noWrap = true; this.numeric = false; }, destroy: function() { this.destroyInput(); }, initializeInline: function(doc) { if (FBTrace.DBG_EDITOR) FBTrace.sysout("Firebug.InlineEditor initializeInline()"); //this.box = this.tag.replace({}, doc, this); this.box = this.tag.append({}, doc.body, this); //this.input = this.box.childNodes[1].firstChild.firstChild; // XXXjjb childNode[1] required this.input = this.box.getElementsByTagName("input")[0]; if (isIElt8) { this.input.style.top = "-8px"; } this.expander = this.expanderTag.replace({}, doc, this); this.initialize(); }, destroyInput: function() { // XXXjoe Need to remove input/keypress handlers to avoid leaks }, getValue: function() { return this.input.value; }, setValue: function(value) { // It's only a one-line editor, so new lines shouldn't be allowed return this.input.value = stripNewLines(value); }, show: function(target, panel, value, targetSize) { //dispatch([Firebug.A11yModel], "onInlineEditorShow", [panel, this]); this.target = target; this.panel = panel; this.targetSize = targetSize; // TODO: xxxpedro editor //this.targetOffset = getClientOffset(target); // Some browsers (IE, Google Chrome and Safari) will have problem trying to get the // offset values of invisible elements, or empty elements. So, in order to get the // correct values, we temporary inject a character in the innerHTML of the empty element, // then we get the offset values, and next, we restore the original innerHTML value. var innerHTML = target.innerHTML; var isEmptyElement = !innerHTML; if (isEmptyElement) target.innerHTML = "."; // Get the position of the target element (that is about to be edited) this.targetOffset = { x: target.offsetLeft, y: target.offsetTop }; // Restore the original innerHTML value of the empty element if (isEmptyElement) target.innerHTML = innerHTML; this.originalClassName = this.box.className; var classNames = target.className.split(" "); for (var i = 0; i < classNames.length; ++i) setClass(this.box, "editor-" + classNames[i]); // Make the editor match the target's font style copyTextStyles(target, this.box); this.setValue(value); if (this.fixedWidth) this.updateLayout(true); else { this.startMeasuring(target); this.textSize = this.measureInputText(value); // Correct the height of the box to make the funky CSS drop-shadow line up var parent = this.input.parentNode; if (hasClass(parent, "textEditorInner2")) { var yDiff = this.textSize.height - this.shadowExpand; // IE6 height offset if (isIE6) yDiff -= 2; parent.style.height = yDiff + "px"; parent.parentNode.style.height = yDiff + "px"; } this.updateLayout(true); } this.getAutoCompleter().reset(); if (isIElt8) panel.panelNode.appendChild(this.box); else target.offsetParent.appendChild(this.box); //console.log(target); //this.input.select(); // it's called bellow, with setTimeout if (isIE) { // reset input style this.input.style.fontFamily = "Monospace"; this.input.style.fontSize = "11px"; } // Insert the "expander" to cover the target element with white space if (!this.fixedWidth) { copyBoxStyles(target, this.expander); target.parentNode.replaceChild(this.expander, target); collapse(target, true); this.expander.parentNode.insertBefore(target, this.expander); } //TODO: xxxpedro //scrollIntoCenterView(this.box, null, true); // Display the editor after change its size and position to avoid flickering this.box.style.display = "block"; // we need to call input.focus() and input.select() with a timeout, // otherwise it won't work on all browsers due to timing issues var self = this; setTimeout(function(){ self.input.focus(); self.input.select(); },0); }, hide: function() { this.box.className = this.originalClassName; if (!this.fixedWidth) { this.stopMeasuring(); collapse(this.target, false); if (this.expander.parentNode) this.expander.parentNode.removeChild(this.expander); } if (this.box.parentNode) { ///setSelectionRange(this.input, 0, 0); this.input.blur(); this.box.parentNode.removeChild(this.box); } delete this.target; delete this.panel; }, layout: function(forceAll) { if (!this.fixedWidth) this.textSize = this.measureInputText(this.input.value); if (forceAll) this.targetOffset = getClientOffset(this.expander); this.updateLayout(false, forceAll); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * beginEditing: function(target, value) { }, saveEdit: function(target, value, previousValue) { }, endEditing: function(target, value, cancel) { // Remove empty groups by default return true; }, insertNewRow: function(target, insertWhere) { }, advanceToNext: function(target, charCode) { return false; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getAutoCompleteRange: function(value, offset) { }, getAutoCompleteList: function(preExpr, expr, postExpr) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getAutoCompleter: function() { if (!this.autoCompleter) { this.autoCompleter = new Firebug.AutoCompleter(null, bind(this.getAutoCompleteRange, this), bind(this.getAutoCompleteList, this), true, false); } return this.autoCompleter; }, completeValue: function(amt) { //console.log("completeValue"); var selectRangeCallback = this.getAutoCompleter().complete(currentPanel.context, this.input, true, amt < 0); if (selectRangeCallback) { Firebug.Editor.update(true); // We need to select the editor text after calling update in Safari/Chrome, // otherwise the text won't be selected if (isSafari) setTimeout(selectRangeCallback,0); else selectRangeCallback(); } else this.incrementValue(amt); }, incrementValue: function(amt) { var value = this.input.value; // TODO: xxxpedro editor if (isIE) var start = getInputSelectionStart(this.input), end = start; else var start = this.input.selectionStart, end = this.input.selectionEnd; //debugger; var range = this.getAutoCompleteRange(value, start); if (!range || range.type != "int") range = {start: 0, end: value.length-1}; var expr = value.substr(range.start, range.end-range.start+1); preExpr = value.substr(0, range.start); postExpr = value.substr(range.end+1); // See if the value is an integer, and if so increment it var intValue = parseInt(expr); if (!!intValue || intValue == 0) { var m = /\d+/.exec(expr); var digitPost = expr.substr(m.index+m[0].length); var completion = intValue-amt; this.input.value = preExpr + completion + digitPost + postExpr; setSelectionRange(this.input, start, end); Firebug.Editor.update(true); return true; } else return false; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onKeyPress: function(event) { //console.log("onKeyPress", event); if (event.keyCode == 27 && !this.completeAsYouType) { var reverted = this.getAutoCompleter().revert(this.input); if (reverted) cancelEvent(event); } else if (event.charCode && this.advanceToNext(this.target, event.charCode)) { Firebug.Editor.tabNextEditor(); cancelEvent(event); } else { if (this.numeric && event.charCode && (event.charCode < 48 || event.charCode > 57) && event.charCode != 45 && event.charCode != 46) FBL.cancelEvent(event); else { // If the user backspaces, don't autocomplete after the upcoming input event this.ignoreNextInput = event.keyCode == 8; } } }, onOverflow: function() { this.updateLayout(false, false, 3); }, onKeyDown: function(event) { //console.log("onKeyDown", event.keyCode); if (event.keyCode > 46 || event.keyCode == 32 || event.keyCode == 8) { this.keyDownPressed = true; } }, onInput: function(event) { //debugger; // skip not relevant onpropertychange calls on IE if (isIE) { if (event.propertyName != "value" || !isVisible(this.input) || !this.keyDownPressed) return; this.keyDownPressed = false; } //console.log("onInput", event); //console.trace(); var selectRangeCallback; if (this.ignoreNextInput) { this.ignoreNextInput = false; this.getAutoCompleter().reset(); } else if (this.completeAsYouType) selectRangeCallback = this.getAutoCompleter().complete(currentPanel.context, this.input, false); else this.getAutoCompleter().reset(); Firebug.Editor.update(); if (selectRangeCallback) { // We need to select the editor text after calling update in Safari/Chrome, // otherwise the text won't be selected if (isSafari) setTimeout(selectRangeCallback,0); else selectRangeCallback(); } }, onContextMenu: function(event) { cancelEvent(event); var popup = $("fbInlineEditorPopup"); FBL.eraseNode(popup); var target = event.target || event.srcElement; var menu = this.getContextMenuItems(target); if (menu) { for (var i = 0; i < menu.length; ++i) FBL.createMenuItem(popup, menu[i]); } if (!popup.firstChild) return false; popup.openPopupAtScreen(event.screenX, event.screenY, true); return true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * updateLayout: function(initial, forceAll, extraWidth) { if (this.fixedWidth) { this.box.style.left = (this.targetOffset.x) + "px"; this.box.style.top = (this.targetOffset.y) + "px"; var w = this.target.offsetWidth; var h = this.target.offsetHeight; this.input.style.width = w + "px"; this.input.style.height = (h-3) + "px"; } else { if (initial || forceAll) { this.box.style.left = this.targetOffset.x + "px"; this.box.style.top = this.targetOffset.y + "px"; } var approxTextWidth = this.textSize.width; var maxWidth = (currentPanel.panelNode.scrollWidth - this.targetOffset.x) - this.outerMargin; var wrapped = initial ? this.noWrap && this.targetSize.height > this.textSize.height+3 : this.noWrap && approxTextWidth > maxWidth; if (wrapped) { var style = isIE ? this.target.currentStyle : this.target.ownerDocument.defaultView.getComputedStyle(this.target, ""); targetMargin = parseInt(style.marginLeft) + parseInt(style.marginRight); // Make the width fit the remaining x-space from the offset to the far right approxTextWidth = maxWidth - targetMargin; this.input.style.width = "100%"; this.box.style.width = approxTextWidth + "px"; } else { // Make the input one character wider than the text value so that // typing does not ever cause the textbox to scroll var charWidth = this.measureInputText('m').width; // Sometimes we need to make the editor a little wider, specifically when // an overflow happens, otherwise it will scroll off some text on the left if (extraWidth) charWidth *= extraWidth; var inputWidth = approxTextWidth + charWidth; if (initial) { if (isIE) { // TODO: xxxpedro var xDiff = 13; this.box.style.width = (inputWidth + xDiff) + "px"; } else this.box.style.width = "auto"; } else { // TODO: xxxpedro var xDiff = isIE ? 13: this.box.scrollWidth - this.input.offsetWidth; this.box.style.width = (inputWidth + xDiff) + "px"; } this.input.style.width = inputWidth + "px"; } this.expander.style.width = approxTextWidth + "px"; this.expander.style.height = Math.max(this.textSize.height-3,0) + "px"; } if (forceAll) scrollIntoCenterView(this.box, null, true); } }); // ************************************************************************************************ // Autocompletion Firebug.AutoCompleter = function(getExprOffset, getRange, evaluator, selectMode, caseSensitive) { var candidates = null; var originalValue = null; var originalOffset = -1; var lastExpr = null; var lastOffset = -1; var exprOffset = 0; var lastIndex = 0; var preParsed = null; var preExpr = null; var postExpr = null; this.revert = function(textBox) { if (originalOffset != -1) { textBox.value = originalValue; setSelectionRange(textBox, originalOffset, originalOffset); this.reset(); return true; } else { this.reset(); return false; } }; this.reset = function() { candidates = null; originalValue = null; originalOffset = -1; lastExpr = null; lastOffset = 0; exprOffset = 0; }; this.complete = function(context, textBox, cycle, reverse) { //console.log("complete", context, textBox, cycle, reverse); // TODO: xxxpedro important port to firebug (variable leak) //var value = lastValue = textBox.value; var value = textBox.value; //var offset = textBox.selectionStart; var offset = getInputSelectionStart(textBox); // The result of selectionStart() in Safari/Chrome is 1 unit less than the result // in Firefox. Therefore, we need to manually adjust the value here. if (isSafari && !cycle && offset >= 0) offset++; if (!selectMode && originalOffset != -1) offset = originalOffset; if (!candidates || !cycle || offset != lastOffset) { originalOffset = offset; originalValue = value; // Find the part of the string that will be parsed var parseStart = getExprOffset ? getExprOffset(value, offset, context) : 0; preParsed = value.substr(0, parseStart); var parsed = value.substr(parseStart); // Find the part of the string that is being completed var range = getRange ? getRange(parsed, offset-parseStart, context) : null; if (!range) range = {start: 0, end: parsed.length-1 }; var expr = parsed.substr(range.start, range.end-range.start+1); preExpr = parsed.substr(0, range.start); postExpr = parsed.substr(range.end+1); exprOffset = parseStart + range.start; if (!cycle) { if (!expr) return; else if (lastExpr && lastExpr.indexOf(expr) != 0) { candidates = null; } else if (lastExpr && lastExpr.length >= expr.length) { candidates = null; lastExpr = expr; return; } } lastExpr = expr; lastOffset = offset; var searchExpr; // Check if the cursor is at the very right edge of the expression, or // somewhere in the middle of it if (expr && offset != parseStart+range.end+1) { if (cycle) { // We are in the middle of the expression, but we can // complete by cycling to the next item in the values // list after the expression offset = range.start; searchExpr = expr; expr = ""; } else { // We can't complete unless we are at the ridge edge return; } } var values = evaluator(preExpr, expr, postExpr, context); if (!values) return; if (expr) { // Filter the list of values to those which begin with expr. We // will then go on to complete the first value in the resulting list candidates = []; if (caseSensitive) { for (var i = 0; i < values.length; ++i) { var name = values[i]; if (name.indexOf && name.indexOf(expr) == 0) candidates.push(name); } } else { var lowerExpr = caseSensitive ? expr : expr.toLowerCase(); for (var i = 0; i < values.length; ++i) { var name = values[i]; if (name.indexOf && name.toLowerCase().indexOf(lowerExpr) == 0) candidates.push(name); } } lastIndex = reverse ? candidates.length-1 : 0; } else if (searchExpr) { var searchIndex = -1; // Find the first instance of searchExpr in the values list. We // will then complete the string that is found if (caseSensitive) { searchIndex = values.indexOf(expr); } else { var lowerExpr = searchExpr.toLowerCase(); for (var i = 0; i < values.length; ++i) { var name = values[i]; if (name && name.toLowerCase().indexOf(lowerExpr) == 0) { searchIndex = i; break; } } } // Nothing found, so there's nothing to complete to if (searchIndex == -1) return this.reset(); expr = searchExpr; candidates = cloneArray(values); lastIndex = searchIndex; } else { expr = ""; candidates = []; for (var i = 0; i < values.length; ++i) { if (values[i].substr) candidates.push(values[i]); } lastIndex = -1; } } if (cycle) { expr = lastExpr; lastIndex += reverse ? -1 : 1; } if (!candidates.length) return; if (lastIndex >= candidates.length) lastIndex = 0; else if (lastIndex < 0) lastIndex = candidates.length-1; var completion = candidates[lastIndex]; var preCompletion = expr.substr(0, offset-exprOffset); var postCompletion = completion.substr(offset-exprOffset); textBox.value = preParsed + preExpr + preCompletion + postCompletion + postExpr; var offsetEnd = preParsed.length + preExpr.length + completion.length; // TODO: xxxpedro remove the following commented code, if the lib.setSelectionRange() // is working well. /* if (textBox.setSelectionRange) { // we must select the range with a timeout, otherwise the text won't // be properly selected (because after this function executes, the editor's // input will be resized to fit the whole text) setTimeout(function(){ if (selectMode) textBox.setSelectionRange(offset, offsetEnd); else textBox.setSelectionRange(offsetEnd, offsetEnd); },0); } /**/ // we must select the range with a timeout, otherwise the text won't // be properly selected (because after this function executes, the editor's // input will be resized to fit the whole text) /* setTimeout(function(){ if (selectMode) setSelectionRange(textBox, offset, offsetEnd); else setSelectionRange(textBox, offsetEnd, offsetEnd); },0); return true; /**/ // The editor text should be selected only after calling the editor.update() // in Safari/Chrome, otherwise the text won't be selected. So, we're returning // a function to be called later (in the proper time for all browsers). // // TODO: xxxpedro see if we can move the editor.update() calls to here, and avoid // returning a closure. the complete() function seems to be called only twice in // editor.js. See if this function is called anywhere else (like css.js for example). return function(){ //console.log("autocomplete ", textBox, offset, offsetEnd); if (selectMode) setSelectionRange(textBox, offset, offsetEnd); else setSelectionRange(textBox, offsetEnd, offsetEnd); }; /**/ }; }; // ************************************************************************************************ // Local Helpers var getDefaultEditor = function getDefaultEditor(panel) { if (!defaultEditor) { var doc = panel.document; defaultEditor = new Firebug.InlineEditor(doc); } return defaultEditor; } /** * An outsider is the first element matching the stepper element that * is not an child of group. Elements tagged with insertBefore or insertAfter * classes are also excluded from these results unless they are the sibling * of group, relative to group's parent editGroup. This allows for the proper insertion * rows when groups are nested. */ var getOutsider = function getOutsider(element, group, stepper) { var parentGroup = getAncestorByClass(group.parentNode, "editGroup"); var next; do { next = stepper(next || element); } while (isAncestor(next, group) || isGroupInsert(next, parentGroup)); return next; } var isGroupInsert = function isGroupInsert(next, group) { return (!group || isAncestor(next, group)) && (hasClass(next, "insertBefore") || hasClass(next, "insertAfter")); } var getNextOutsider = function getNextOutsider(element, group) { return getOutsider(element, group, bind(getNextByClass, FBL, "editable")); } var getPreviousOutsider = function getPreviousOutsider(element, group) { return getOutsider(element, group, bind(getPreviousByClass, FBL, "editable")); } var getInlineParent = function getInlineParent(element) { var lastInline = element; for (; element; element = element.parentNode) { //var s = element.ownerDocument.defaultView.getComputedStyle(element, ""); var s = isIE ? element.currentStyle : element.ownerDocument.defaultView.getComputedStyle(element, ""); if (s.display != "inline") return lastInline; else lastInline = element; } return null; } var insertTab = function insertTab() { insertTextIntoElement(currentEditor.input, Firebug.Editor.tabCharacter); } // ************************************************************************************************ Firebug.registerModule(Firebug.Editor); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ if (Env.Options.disableXHRListener) return; // ************************************************************************************************ // XHRSpy var XHRSpy = function() { this.requestHeaders = []; this.responseHeaders = []; }; XHRSpy.prototype = { method: null, url: null, async: null, xhrRequest: null, href: null, loaded: false, logRow: null, responseText: null, requestHeaders: null, responseHeaders: null, sourceLink: null, // {href:"file.html", line: 22} getURL: function() { return this.href; } }; // ************************************************************************************************ // XMLHttpRequestWrapper var XMLHttpRequestWrapper = function(activeXObject) { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // XMLHttpRequestWrapper internal variables var xhrRequest = typeof activeXObject != "undefined" ? activeXObject : new _XMLHttpRequest(), spy = new XHRSpy(), self = this, reqType, reqUrl, reqStartTS; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // XMLHttpRequestWrapper internal methods var updateSelfPropertiesIgnore = { abort: 1, channel: 1, getAllResponseHeaders: 1, getInterface: 1, getResponseHeader: 1, mozBackgroundRequest: 1, multipart: 1, onreadystatechange: 1, open: 1, send: 1, setRequestHeader: 1 }; var updateSelfProperties = function() { if (supportsXHRIterator) { for (var propName in xhrRequest) { if (propName in updateSelfPropertiesIgnore) continue; try { var propValue = xhrRequest[propName]; if (propValue && !isFunction(propValue)) self[propName] = propValue; } catch(E) { //console.log(propName, E.message); } } } else { // will fail to read these xhrRequest properties if the request is not completed if (xhrRequest.readyState == 4) { self.status = xhrRequest.status; self.statusText = xhrRequest.statusText; self.responseText = xhrRequest.responseText; self.responseXML = xhrRequest.responseXML; } } }; var updateXHRPropertiesIgnore = { channel: 1, onreadystatechange: 1, readyState: 1, responseBody: 1, responseText: 1, responseXML: 1, status: 1, statusText: 1, upload: 1 }; var updateXHRProperties = function() { for (var propName in self) { if (propName in updateXHRPropertiesIgnore) continue; try { var propValue = self[propName]; if (propValue && !xhrRequest[propName]) { xhrRequest[propName] = propValue; } } catch(E) { //console.log(propName, E.message); } } }; var logXHR = function() { var row = Firebug.Console.log(spy, null, "spy", Firebug.Spy.XHR); if (row) { setClass(row, "loading"); spy.logRow = row; } }; var finishXHR = function() { var duration = new Date().getTime() - reqStartTS; var success = xhrRequest.status == 200; var responseHeadersText = xhrRequest.getAllResponseHeaders(); var responses = responseHeadersText ? responseHeadersText.split(/[\n\r]/) : []; var reHeader = /^(\S+):\s*(.*)/; for (var i=0, l=responses.length; i<l; i++) { var text = responses[i]; var match = text.match(reHeader); if (match) { var name = match[1]; var value = match[2]; // update the spy mimeType property so we can detect when to show // custom response viewers (such as HTML, XML or JSON viewer) if (name == "Content-Type") spy.mimeType = value; /* if (name == "Last Modified") { if (!spy.cacheEntry) spy.cacheEntry = []; spy.cacheEntry.push({ name: [name], value: [value] }); } /**/ spy.responseHeaders.push({ name: [name], value: [value] }); } } with({ row: spy.logRow, status: xhrRequest.status == 0 ? // if xhrRequest.status == 0 then accessing xhrRequest.statusText // will cause an error, so we must handle this case (Issue 3504) "" : xhrRequest.status + " " + xhrRequest.statusText, time: duration, success: success }) { setTimeout(function(){ spy.responseText = xhrRequest.responseText; // update row information to avoid "ethernal spinning gif" bug in IE row = row || spy.logRow; // if chrome document is not loaded, there will be no row yet, so just ignore if (!row) return; // update the XHR representation data handleRequestStatus(success, status, time); },200); } spy.loaded = true; /* // commented because they are being updated by the updateSelfProperties() function self.status = xhrRequest.status; self.statusText = xhrRequest.statusText; self.responseText = xhrRequest.responseText; self.responseXML = xhrRequest.responseXML; /**/ updateSelfProperties(); }; var handleStateChange = function() { //Firebug.Console.log(["onreadystatechange", xhrRequest.readyState, xhrRequest.readyState == 4 && xhrRequest.status]); self.readyState = xhrRequest.readyState; if (xhrRequest.readyState == 4) { finishXHR(); xhrRequest.onreadystatechange = function(){}; } //Firebug.Console.log(spy.url + ": " + xhrRequest.readyState); self.onreadystatechange(); }; // update the XHR representation data var handleRequestStatus = function(success, status, time) { var row = spy.logRow; FBL.removeClass(row, "loading"); if (!success) FBL.setClass(row, "error"); var item = FBL.$$(".spyStatus", row)[0]; item.innerHTML = status; if (time) { var item = FBL.$$(".spyTime", row)[0]; item.innerHTML = time + "ms"; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // XMLHttpRequestWrapper public properties and handlers this.readyState = 0; this.onreadystatechange = function(){}; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // XMLHttpRequestWrapper public methods this.open = function(method, url, async, user, password) { //Firebug.Console.log("xhrRequest open"); updateSelfProperties(); if (spy.loaded) spy = new XHRSpy(); spy.method = method; spy.url = url; spy.async = async; spy.href = url; spy.xhrRequest = xhrRequest; spy.urlParams = parseURLParamsArray(url); try { // xhrRequest.open.apply may not be available in IE if (supportsApply) xhrRequest.open.apply(xhrRequest, arguments); else xhrRequest.open(method, url, async, user, password); } catch(e) { } xhrRequest.onreadystatechange = handleStateChange; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.send = function(data) { //Firebug.Console.log("xhrRequest send"); spy.data = data; reqStartTS = new Date().getTime(); updateXHRProperties(); try { xhrRequest.send(data); } catch(e) { // TODO: xxxpedro XHR throws or not? //throw e; } finally { logXHR(); if (!spy.async) { self.readyState = xhrRequest.readyState; // sometimes an error happens when calling finishXHR() // Issue 3422: Firebug Lite breaks Google Instant Search try { finishXHR(); } catch(E) { } } } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.setRequestHeader = function(header, value) { spy.requestHeaders.push({name: [header], value: [value]}); return xhrRequest.setRequestHeader(header, value); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.abort = function() { xhrRequest.abort(); updateSelfProperties(); handleRequestStatus(false, "Aborted"); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.getResponseHeader = function(header) { return xhrRequest.getResponseHeader(header); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.getAllResponseHeaders = function() { return xhrRequest.getAllResponseHeaders(); }; /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Clone XHR object // xhrRequest.open.apply not available in IE and will throw an error in // IE6 by simply reading xhrRequest.open so we must sniff it var supportsApply = !isIE6 && xhrRequest && xhrRequest.open && typeof xhrRequest.open.apply != "undefined"; var numberOfXHRProperties = 0; for (var propName in xhrRequest) { numberOfXHRProperties++; if (propName in updateSelfPropertiesIgnore) continue; try { var propValue = xhrRequest[propName]; if (isFunction(propValue)) { if (typeof self[propName] == "undefined") { this[propName] = (function(name, xhr){ return supportsApply ? // if the browser supports apply function() { return xhr[name].apply(xhr, arguments); } : function(a,b,c,d,e) { return xhr[name](a,b,c,d,e); }; })(propName, xhrRequest); } } else this[propName] = propValue; } catch(E) { //console.log(propName, E.message); } } // IE6 does not support for (var prop in XHR) var supportsXHRIterator = numberOfXHRProperties > 0; /**/ return this; }; // ************************************************************************************************ // ActiveXObject Wrapper (IE6 only) var _ActiveXObject; var isIE6 = /msie 6/i.test(navigator.appVersion); if (isIE6) { _ActiveXObject = window.ActiveXObject; var xhrObjects = " MSXML2.XMLHTTP.5.0 MSXML2.XMLHTTP.4.0 MSXML2.XMLHTTP.3.0 MSXML2.XMLHTTP Microsoft.XMLHTTP "; window.ActiveXObject = function(name) { var error = null; try { var activeXObject = new _ActiveXObject(name); } catch(e) { error = e; } finally { if (!error) { if (xhrObjects.indexOf(" " + name + " ") != -1) return new XMLHttpRequestWrapper(activeXObject); else return activeXObject; } else throw error.message; } }; } // ************************************************************************************************ // Register the XMLHttpRequestWrapper for non-IE6 browsers if (!isIE6) { var _XMLHttpRequest = XMLHttpRequest; window.XMLHttpRequest = function() { return new XMLHttpRequestWrapper(); }; } //************************************************************************************************ FBL.getNativeXHRObject = function() { var xhrObj = false; try { xhrObj = new _XMLHttpRequest(); } catch(e) { var progid = [ "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ]; for ( var i=0; i < progid.length; ++i ) { try { xhrObj = new _ActiveXObject(progid[i]); } catch(e) { continue; } break; } } finally { return xhrObj; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var reIgnore = /about:|javascript:|resource:|chrome:|jar:/; var layoutInterval = 300; var indentWidth = 18; var cacheSession = null; var contexts = new Array(); var panelName = "net"; var maxQueueRequests = 500; //var panelBar1 = $("fbPanelBar1"); // chrome not available at startup var activeRequests = []; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var mimeExtensionMap = { "txt": "text/plain", "html": "text/html", "htm": "text/html", "xhtml": "text/html", "xml": "text/xml", "css": "text/css", "js": "application/x-javascript", "jss": "application/x-javascript", "jpg": "image/jpg", "jpeg": "image/jpeg", "gif": "image/gif", "png": "image/png", "bmp": "image/bmp", "swf": "application/x-shockwave-flash", "flv": "video/x-flv" }; var fileCategories = { "undefined": 1, "html": 1, "css": 1, "js": 1, "xhr": 1, "image": 1, "flash": 1, "txt": 1, "bin": 1 }; var textFileCategories = { "txt": 1, "html": 1, "xhr": 1, "css": 1, "js": 1 }; var binaryFileCategories = { "bin": 1, "flash": 1 }; var mimeCategoryMap = { "text/plain": "txt", "application/octet-stream": "bin", "text/html": "html", "text/xml": "html", "text/css": "css", "application/x-javascript": "js", "text/javascript": "js", "application/javascript" : "js", "image/jpeg": "image", "image/jpg": "image", "image/gif": "image", "image/png": "image", "image/bmp": "image", "application/x-shockwave-flash": "flash", "video/x-flv": "flash" }; var binaryCategoryMap = { "image": 1, "flash" : 1 }; // ************************************************************************************************ /** * @module Represents a module object for the Net panel. This object is derived * from <code>Firebug.ActivableModule</code> in order to support activation (enable/disable). * This allows to avoid (performance) expensive features if the functionality is not necessary * for the user. */ Firebug.NetMonitor = extend(Firebug.ActivableModule, { dispatchName: "netMonitor", clear: function(context) { // The user pressed a Clear button so, remove content of the panel... var panel = context.getPanel(panelName, true); if (panel) panel.clear(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Module initialize: function() { return; this.panelName = panelName; Firebug.ActivableModule.initialize.apply(this, arguments); if (Firebug.TraceModule) Firebug.TraceModule.addListener(this.TraceListener); // HTTP observer must be registered now (and not in monitorContext, since if a // page is opened in a new tab the top document request would be missed otherwise. NetHttpObserver.registerObserver(); NetHttpActivityObserver.registerObserver(); Firebug.Debugger.addListener(this.DebuggerListener); }, shutdown: function() { return; prefs.removeObserver(Firebug.prefDomain, this, false); if (Firebug.TraceModule) Firebug.TraceModule.removeListener(this.TraceListener); NetHttpObserver.unregisterObserver(); NetHttpActivityObserver.unregisterObserver(); Firebug.Debugger.removeListener(this.DebuggerListener); } }); /** * @domplate Represents a template that is used to reneder detailed info about a request. * This template is rendered when a request is expanded. */ Firebug.NetMonitor.NetInfoBody = domplate(Firebug.Rep, new Firebug.Listener(), { tag: DIV({"class": "netInfoBody", _repObject: "$file"}, TAG("$infoTabs", {file: "$file"}), TAG("$infoBodies", {file: "$file"}) ), infoTabs: DIV({"class": "netInfoTabs focusRow subFocusRow", "role": "tablist"}, A({"class": "netInfoParamsTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Params", $collapsed: "$file|hideParams"}, $STR("URLParameters") ), A({"class": "netInfoHeadersTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Headers"}, $STR("Headers") ), A({"class": "netInfoPostTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Post", $collapsed: "$file|hidePost"}, $STR("Post") ), A({"class": "netInfoPutTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Put", $collapsed: "$file|hidePut"}, $STR("Put") ), A({"class": "netInfoResponseTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Response", $collapsed: "$file|hideResponse"}, $STR("Response") ), A({"class": "netInfoCacheTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Cache", $collapsed: "$file|hideCache"}, $STR("Cache") ), A({"class": "netInfoHtmlTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Html", $collapsed: "$file|hideHtml"}, $STR("HTML") ) ), infoBodies: DIV({"class": "netInfoBodies outerFocusRow"}, TABLE({"class": "netInfoParamsText netInfoText netInfoParamsTable", "role": "tabpanel", cellpadding: 0, cellspacing: 0}, TBODY()), DIV({"class": "netInfoHeadersText netInfoText", "role": "tabpanel"}), DIV({"class": "netInfoPostText netInfoText", "role": "tabpanel"}), DIV({"class": "netInfoPutText netInfoText", "role": "tabpanel"}), PRE({"class": "netInfoResponseText netInfoText", "role": "tabpanel"}), DIV({"class": "netInfoCacheText netInfoText", "role": "tabpanel"}, TABLE({"class": "netInfoCacheTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("Cache")}) ) ), DIV({"class": "netInfoHtmlText netInfoText", "role": "tabpanel"}, IFRAME({"class": "netInfoHtmlPreview", "role": "document"}) ) ), headerDataTag: FOR("param", "$headers", TR({"role": "listitem"}, TD({"class": "netInfoParamName", "role": "presentation"}, TAG("$param|getNameTag", {param: "$param"}) ), TD({"class": "netInfoParamValue", "role": "list", "aria-label": "$param.name"}, FOR("line", "$param|getParamValueIterator", CODE({"class": "focusRow subFocusRow", "role": "listitem"}, "$line") ) ) ) ), customTab: A({"class": "netInfo$tabId\\Tab netInfoTab", onclick: "$onClickTab", view: "$tabId", "role": "tab"}, "$tabTitle" ), customBody: DIV({"class": "netInfo$tabId\\Text netInfoText", "role": "tabpanel"}), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * nameTag: SPAN("$param|getParamName"), nameWithTooltipTag: SPAN({title: "$param.name"}, "$param|getParamName"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getNameTag: function(param) { return (this.getParamName(param) == param.name) ? this.nameTag : this.nameWithTooltipTag; }, getParamName: function(param) { var limit = 25; var name = param.name; if (name.length > limit) name = name.substr(0, limit) + "..."; return name; }, getParamTitle: function(param) { var limit = 25; var name = param.name; if (name.length > limit) return name; return ""; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * hideParams: function(file) { return !file.urlParams || !file.urlParams.length; }, hidePost: function(file) { return file.method.toUpperCase() != "POST"; }, hidePut: function(file) { return file.method.toUpperCase() != "PUT"; }, hideResponse: function(file) { return false; //return file.category in binaryFileCategories; }, hideCache: function(file) { return true; //xxxHonza: I don't see any reason why not to display the cache also info for images. return !file.cacheEntry; // || file.category=="image"; }, hideHtml: function(file) { return (file.mimeType != "text/html") && (file.mimeType != "application/xhtml+xml"); }, onClickTab: function(event) { this.selectTab(event.currentTarget || event.srcElement); }, getParamValueIterator: function(param) { // TODO: xxxpedro console2 return param.value; // This value is inserted into CODE element and so, make sure the HTML isn't escaped (1210). // This is why the second parameter is true. // The CODE (with style white-space:pre) element preserves whitespaces so they are // displayed the same, as they come from the server (1194). // In case of a long header values of post parameters the value must be wrapped (2105). return wrapText(param.value, true); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * appendTab: function(netInfoBox, tabId, tabTitle) { // Create new tab and body. var args = {tabId: tabId, tabTitle: tabTitle}; ///this.customTab.append(args, netInfoBox.getElementsByClassName("netInfoTabs").item(0)); ///this.customBody.append(args, netInfoBox.getElementsByClassName("netInfoBodies").item(0)); this.customTab.append(args, $$(".netInfoTabs", netInfoBox)[0]); this.customBody.append(args, $$(".netInfoBodies", netInfoBox)[0]); }, selectTabByName: function(netInfoBox, tabName) { var tab = getChildByClass(netInfoBox, "netInfoTabs", "netInfo"+tabName+"Tab"); if (tab) this.selectTab(tab); }, selectTab: function(tab) { var view = tab.getAttribute("view"); var netInfoBox = getAncestorByClass(tab, "netInfoBody"); var selectedTab = netInfoBox.selectedTab; if (selectedTab) { //netInfoBox.selectedText.removeAttribute("selected"); removeClass(netInfoBox.selectedText, "netInfoTextSelected"); removeClass(selectedTab, "netInfoTabSelected"); //selectedTab.removeAttribute("selected"); selectedTab.setAttribute("aria-selected", "false"); } var textBodyName = "netInfo" + view + "Text"; selectedTab = netInfoBox.selectedTab = tab; netInfoBox.selectedText = $$("."+textBodyName, netInfoBox)[0]; //netInfoBox.selectedText = netInfoBox.getElementsByClassName(textBodyName).item(0); //netInfoBox.selectedText.setAttribute("selected", "true"); setClass(netInfoBox.selectedText, "netInfoTextSelected"); setClass(selectedTab, "netInfoTabSelected"); selectedTab.setAttribute("selected", "true"); selectedTab.setAttribute("aria-selected", "true"); var file = Firebug.getRepObject(netInfoBox); //var context = Firebug.getElementPanel(netInfoBox).context; var context = Firebug.chrome; this.updateInfo(netInfoBox, file, context); }, updateInfo: function(netInfoBox, file, context) { if (FBTrace.DBG_NET) FBTrace.sysout("net.updateInfo; file", file); if (!netInfoBox) { if (FBTrace.DBG_NET || FBTrace.DBG_ERRORS) FBTrace.sysout("net.updateInfo; ERROR netInfo == null " + file.href, file); return; } var tab = netInfoBox.selectedTab; if (hasClass(tab, "netInfoParamsTab")) { if (file.urlParams && !netInfoBox.urlParamsPresented) { netInfoBox.urlParamsPresented = true; this.insertHeaderRows(netInfoBox, file.urlParams, "Params"); } } else if (hasClass(tab, "netInfoHeadersTab")) { var headersText = $$(".netInfoHeadersText", netInfoBox)[0]; //var headersText = netInfoBox.getElementsByClassName("netInfoHeadersText").item(0); if (file.responseHeaders && !netInfoBox.responseHeadersPresented) { netInfoBox.responseHeadersPresented = true; NetInfoHeaders.renderHeaders(headersText, file.responseHeaders, "ResponseHeaders"); } if (file.requestHeaders && !netInfoBox.requestHeadersPresented) { netInfoBox.requestHeadersPresented = true; NetInfoHeaders.renderHeaders(headersText, file.requestHeaders, "RequestHeaders"); } } else if (hasClass(tab, "netInfoPostTab")) { if (!netInfoBox.postPresented) { netInfoBox.postPresented = true; //var postText = netInfoBox.getElementsByClassName("netInfoPostText").item(0); var postText = $$(".netInfoPostText", netInfoBox)[0]; NetInfoPostData.render(context, postText, file); } } else if (hasClass(tab, "netInfoPutTab")) { if (!netInfoBox.putPresented) { netInfoBox.putPresented = true; //var putText = netInfoBox.getElementsByClassName("netInfoPutText").item(0); var putText = $$(".netInfoPutText", netInfoBox)[0]; NetInfoPostData.render(context, putText, file); } } else if (hasClass(tab, "netInfoResponseTab") && file.loaded && !netInfoBox.responsePresented) { ///var responseTextBox = netInfoBox.getElementsByClassName("netInfoResponseText").item(0); var responseTextBox = $$(".netInfoResponseText", netInfoBox)[0]; if (file.category == "image") { netInfoBox.responsePresented = true; var responseImage = netInfoBox.ownerDocument.createElement("img"); responseImage.src = file.href; clearNode(responseTextBox); responseTextBox.appendChild(responseImage, responseTextBox); } else ///if (!(binaryCategoryMap.hasOwnProperty(file.category))) { this.setResponseText(file, netInfoBox, responseTextBox, context); } } else if (hasClass(tab, "netInfoCacheTab") && file.loaded && !netInfoBox.cachePresented) { var responseTextBox = netInfoBox.getElementsByClassName("netInfoCacheText").item(0); if (file.cacheEntry) { netInfoBox.cachePresented = true; this.insertHeaderRows(netInfoBox, file.cacheEntry, "Cache"); } } else if (hasClass(tab, "netInfoHtmlTab") && file.loaded && !netInfoBox.htmlPresented) { netInfoBox.htmlPresented = true; var text = Utils.getResponseText(file, context); ///var iframe = netInfoBox.getElementsByClassName("netInfoHtmlPreview").item(0); var iframe = $$(".netInfoHtmlPreview", netInfoBox)[0]; ///iframe.contentWindow.document.body.innerHTML = text; // TODO: xxxpedro net - remove scripts var reScript = /<script(.|\s)*?\/script>/gi; text = text.replace(reScript, ""); iframe.contentWindow.document.write(text); iframe.contentWindow.document.close(); } // Notify listeners about update so, content of custom tabs can be updated. dispatch(NetInfoBody.fbListeners, "updateTabBody", [netInfoBox, file, context]); }, setResponseText: function(file, netInfoBox, responseTextBox, context) { //********************************************** //********************************************** //********************************************** netInfoBox.responsePresented = true; // line breaks somehow are different in IE // make this only once in the initialization? we don't have net panels and modules yet. if (isIE) responseTextBox.style.whiteSpace = "nowrap"; responseTextBox[ typeof responseTextBox.textContent != "undefined" ? "textContent" : "innerText" ] = file.responseText; return; //********************************************** //********************************************** //********************************************** // Get response text and make sure it doesn't exceed the max limit. var text = Utils.getResponseText(file, context); var limit = Firebug.netDisplayedResponseLimit + 15; var limitReached = text ? (text.length > limit) : false; if (limitReached) text = text.substr(0, limit) + "..."; // Insert the response into the UI. if (text) insertWrappedText(text, responseTextBox); else insertWrappedText("", responseTextBox); // Append a message informing the user that the response isn't fully displayed. if (limitReached) { var object = { text: $STR("net.responseSizeLimitMessage"), onClickLink: function() { var panel = context.getPanel("net", true); panel.openResponseInTab(file); } }; Firebug.NetMonitor.ResponseSizeLimit.append(object, responseTextBox); } netInfoBox.responsePresented = true; if (FBTrace.DBG_NET) FBTrace.sysout("net.setResponseText; response text updated"); }, insertHeaderRows: function(netInfoBox, headers, tableName, rowName) { if (!headers.length) return; var headersTable = $$(".netInfo"+tableName+"Table", netInfoBox)[0]; //var headersTable = netInfoBox.getElementsByClassName("netInfo"+tableName+"Table").item(0); var tbody = getChildByClass(headersTable, "netInfo" + rowName + "Body"); if (!tbody) tbody = headersTable.firstChild; var titleRow = getChildByClass(tbody, "netInfo" + rowName + "Title"); this.headerDataTag.insertRows({headers: headers}, titleRow ? titleRow : tbody); removeClass(titleRow, "collapsed"); } }); var NetInfoBody = Firebug.NetMonitor.NetInfoBody; // ************************************************************************************************ /** * @domplate Used within the Net panel to display raw source of request and response headers * as well as pretty-formatted summary of these headers. */ Firebug.NetMonitor.NetInfoHeaders = domplate(Firebug.Rep, //new Firebug.Listener(), { tag: DIV({"class": "netInfoHeadersTable", "role": "tabpanel"}, DIV({"class": "netInfoHeadersGroup netInfoResponseHeadersTitle"}, SPAN($STR("ResponseHeaders")), SPAN({"class": "netHeadersViewSource response collapsed", onclick: "$onViewSource", _sourceDisplayed: false, _rowName: "ResponseHeaders"}, $STR("net.headers.view source") ) ), TABLE({cellpadding: 0, cellspacing: 0}, TBODY({"class": "netInfoResponseHeadersBody", "role": "list", "aria-label": $STR("ResponseHeaders")}) ), DIV({"class": "netInfoHeadersGroup netInfoRequestHeadersTitle"}, SPAN($STR("RequestHeaders")), SPAN({"class": "netHeadersViewSource request collapsed", onclick: "$onViewSource", _sourceDisplayed: false, _rowName: "RequestHeaders"}, $STR("net.headers.view source") ) ), TABLE({cellpadding: 0, cellspacing: 0}, TBODY({"class": "netInfoRequestHeadersBody", "role": "list", "aria-label": $STR("RequestHeaders")}) ) ), sourceTag: TR({"role": "presentation"}, TD({colspan: 2, "role": "presentation"}, PRE({"class": "source"}) ) ), onViewSource: function(event) { var target = event.target; var requestHeaders = (target.rowName == "RequestHeaders"); var netInfoBox = getAncestorByClass(target, "netInfoBody"); var file = netInfoBox.repObject; if (target.sourceDisplayed) { var headers = requestHeaders ? file.requestHeaders : file.responseHeaders; this.insertHeaderRows(netInfoBox, headers, target.rowName); target.innerHTML = $STR("net.headers.view source"); } else { var source = requestHeaders ? file.requestHeadersText : file.responseHeadersText; this.insertSource(netInfoBox, source, target.rowName); target.innerHTML = $STR("net.headers.pretty print"); } target.sourceDisplayed = !target.sourceDisplayed; cancelEvent(event); }, insertSource: function(netInfoBox, source, rowName) { // This breaks copy to clipboard. //if (source) // source = source.replace(/\r\n/gm, "<span style='color:lightgray'>\\r\\n</span>\r\n"); ///var tbody = netInfoBox.getElementsByClassName("netInfo" + rowName + "Body").item(0); var tbody = $$(".netInfo" + rowName + "Body", netInfoBox)[0]; var node = this.sourceTag.replace({}, tbody); ///var sourceNode = node.getElementsByClassName("source").item(0); var sourceNode = $$(".source", node)[0]; sourceNode.innerHTML = source; }, insertHeaderRows: function(netInfoBox, headers, rowName) { var headersTable = $$(".netInfoHeadersTable", netInfoBox)[0]; var tbody = $$(".netInfo" + rowName + "Body", headersTable)[0]; //var headersTable = netInfoBox.getElementsByClassName("netInfoHeadersTable").item(0); //var tbody = headersTable.getElementsByClassName("netInfo" + rowName + "Body").item(0); clearNode(tbody); if (!headers.length) return; NetInfoBody.headerDataTag.insertRows({headers: headers}, tbody); var titleRow = getChildByClass(headersTable, "netInfo" + rowName + "Title"); removeClass(titleRow, "collapsed"); }, init: function(parent) { var rootNode = this.tag.append({}, parent); var netInfoBox = getAncestorByClass(parent, "netInfoBody"); var file = netInfoBox.repObject; var viewSource; viewSource = $$(".request", rootNode)[0]; //viewSource = rootNode.getElementsByClassName("netHeadersViewSource request").item(0); if (file.requestHeadersText) removeClass(viewSource, "collapsed"); viewSource = $$(".response", rootNode)[0]; //viewSource = rootNode.getElementsByClassName("netHeadersViewSource response").item(0); if (file.responseHeadersText) removeClass(viewSource, "collapsed"); }, renderHeaders: function(parent, headers, rowName) { if (!parent.firstChild) this.init(parent); this.insertHeaderRows(parent, headers, rowName); } }); var NetInfoHeaders = Firebug.NetMonitor.NetInfoHeaders; // ************************************************************************************************ /** * @domplate Represents posted data within request info (the info, which is visible when * a request entry is expanded. This template renders content of the Post tab. */ Firebug.NetMonitor.NetInfoPostData = domplate(Firebug.Rep, /*new Firebug.Listener(),*/ { // application/x-www-form-urlencoded paramsTable: TABLE({"class": "netInfoPostParamsTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("net.label.Parameters")}, TR({"class": "netInfoPostParamsTitle", "role": "presentation"}, TD({colspan: 3, "role": "presentation"}, DIV({"class": "netInfoPostParams"}, $STR("net.label.Parameters"), SPAN({"class": "netInfoPostContentType"}, "application/x-www-form-urlencoded" ) ) ) ) ) ), // multipart/form-data partsTable: TABLE({"class": "netInfoPostPartsTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("net.label.Parts")}, TR({"class": "netInfoPostPartsTitle", "role": "presentation"}, TD({colspan: 2, "role":"presentation" }, DIV({"class": "netInfoPostParams"}, $STR("net.label.Parts"), SPAN({"class": "netInfoPostContentType"}, "multipart/form-data" ) ) ) ) ) ), // application/json jsonTable: TABLE({"class": "netInfoPostJSONTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, ///TBODY({"role": "list", "aria-label": $STR("jsonviewer.tab.JSON")}, TBODY({"role": "list", "aria-label": $STR("JSON")}, TR({"class": "netInfoPostJSONTitle", "role": "presentation"}, TD({"role": "presentation" }, DIV({"class": "netInfoPostParams"}, ///$STR("jsonviewer.tab.JSON") $STR("JSON") ) ) ), TR( TD({"class": "netInfoPostJSONBody"}) ) ) ), // application/xml xmlTable: TABLE({"class": "netInfoPostXMLTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("xmlviewer.tab.XML")}, TR({"class": "netInfoPostXMLTitle", "role": "presentation"}, TD({"role": "presentation" }, DIV({"class": "netInfoPostParams"}, $STR("xmlviewer.tab.XML") ) ) ), TR( TD({"class": "netInfoPostXMLBody"}) ) ) ), sourceTable: TABLE({"class": "netInfoPostSourceTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("net.label.Source")}, TR({"class": "netInfoPostSourceTitle", "role": "presentation"}, TD({colspan: 2, "role": "presentation"}, DIV({"class": "netInfoPostSource"}, $STR("net.label.Source") ) ) ) ) ), sourceBodyTag: TR({"role": "presentation"}, TD({colspan: 2, "role": "presentation"}, FOR("line", "$param|getParamValueIterator", CODE({"class":"focusRow subFocusRow" , "role": "listitem"},"$line") ) ) ), getParamValueIterator: function(param) { return NetInfoBody.getParamValueIterator(param); }, render: function(context, parentNode, file) { //debugger; var spy = getAncestorByClass(parentNode, "spyHead"); var spyObject = spy.repObject; var data = spyObject.data; ///var contentType = Utils.findHeader(file.requestHeaders, "content-type"); var contentType = file.mimeType; ///var text = Utils.getPostText(file, context, true); ///if (text == undefined) /// return; ///if (Utils.isURLEncodedRequest(file, context)) // fake Utils.isURLEncodedRequest identification if (contentType && contentType == "application/x-www-form-urlencoded" || data && data.indexOf("=") != -1) { ///var lines = text.split("\n"); ///var params = parseURLEncodedText(lines[lines.length-1]); var params = parseURLEncodedTextArray(data); if (params) this.insertParameters(parentNode, params); } ///if (Utils.isMultiPartRequest(file, context)) ///{ /// var data = this.parseMultiPartText(file, context); /// if (data) /// this.insertParts(parentNode, data); ///} // moved to the top ///var contentType = Utils.findHeader(file.requestHeaders, "content-type"); ///if (Firebug.JSONViewerModel.isJSON(contentType)) var jsonData = { responseText: data }; if (Firebug.JSONViewerModel.isJSON(contentType, data)) ///this.insertJSON(parentNode, file, context); this.insertJSON(parentNode, jsonData, context); ///if (Firebug.XMLViewerModel.isXML(contentType)) /// this.insertXML(parentNode, file, context); ///var postText = Utils.getPostText(file, context); ///postText = Utils.formatPostText(postText); var postText = data; if (postText) this.insertSource(parentNode, postText); }, insertParameters: function(parentNode, params) { if (!params || !params.length) return; var paramTable = this.paramsTable.append({object:{}}, parentNode); var row = $$(".netInfoPostParamsTitle", paramTable)[0]; //var paramTable = this.paramsTable.append(null, parentNode); //var row = paramTable.getElementsByClassName("netInfoPostParamsTitle").item(0); var tbody = paramTable.getElementsByTagName("tbody")[0]; NetInfoBody.headerDataTag.insertRows({headers: params}, row); }, insertParts: function(parentNode, data) { if (!data.params || !data.params.length) return; var partsTable = this.partsTable.append({object:{}}, parentNode); var row = $$(".netInfoPostPartsTitle", paramTable)[0]; //var partsTable = this.partsTable.append(null, parentNode); //var row = partsTable.getElementsByClassName("netInfoPostPartsTitle").item(0); NetInfoBody.headerDataTag.insertRows({headers: data.params}, row); }, insertJSON: function(parentNode, file, context) { ///var text = Utils.getPostText(file, context); var text = file.responseText; ///var data = parseJSONString(text, "http://" + file.request.originalURI.host); var data = parseJSONString(text); if (!data) return; ///var jsonTable = this.jsonTable.append(null, parentNode); var jsonTable = this.jsonTable.append({}, parentNode); ///var jsonBody = jsonTable.getElementsByClassName("netInfoPostJSONBody").item(0); var jsonBody = $$(".netInfoPostJSONBody", jsonTable)[0]; if (!this.toggles) this.toggles = {}; Firebug.DOMPanel.DirTable.tag.replace( {object: data, toggles: this.toggles}, jsonBody); }, insertXML: function(parentNode, file, context) { var text = Utils.getPostText(file, context); var jsonTable = this.xmlTable.append(null, parentNode); ///var jsonBody = jsonTable.getElementsByClassName("netInfoPostXMLBody").item(0); var jsonBody = $$(".netInfoPostXMLBody", jsonTable)[0]; Firebug.XMLViewerModel.insertXML(jsonBody, text); }, insertSource: function(parentNode, text) { var sourceTable = this.sourceTable.append({object:{}}, parentNode); var row = $$(".netInfoPostSourceTitle", sourceTable)[0]; //var sourceTable = this.sourceTable.append(null, parentNode); //var row = sourceTable.getElementsByClassName("netInfoPostSourceTitle").item(0); var param = {value: [text]}; this.sourceBodyTag.insertRows({param: param}, row); }, parseMultiPartText: function(file, context) { var text = Utils.getPostText(file, context); if (text == undefined) return null; FBTrace.sysout("net.parseMultiPartText; boundary: ", text); var boundary = text.match(/\s*boundary=\s*(.*)/)[1]; var divider = "\r\n\r\n"; var bodyStart = text.indexOf(divider); var body = text.substr(bodyStart + divider.length); var postData = {}; postData.mimeType = "multipart/form-data"; postData.params = []; var parts = body.split("--" + boundary); for (var i=0; i<parts.length; i++) { var part = parts[i].split(divider); if (part.length != 2) continue; var m = part[0].match(/\s*name=\"(.*)\"(;|$)/); postData.params.push({ name: (m && m.length > 1) ? m[1] : "", value: trim(part[1]) }); } return postData; } }); var NetInfoPostData = Firebug.NetMonitor.NetInfoPostData; // ************************************************************************************************ // TODO: xxxpedro net i18n var $STRP = function(a){return a;}; Firebug.NetMonitor.NetLimit = domplate(Firebug.Rep, { collapsed: true, tableTag: DIV( TABLE({width: "100%", cellpadding: 0, cellspacing: 0}, TBODY() ) ), limitTag: TR({"class": "netRow netLimitRow", $collapsed: "$isCollapsed"}, TD({"class": "netCol netLimitCol", colspan: 6}, TABLE({cellpadding: 0, cellspacing: 0}, TBODY( TR( TD( SPAN({"class": "netLimitLabel"}, $STRP("plural.Limit_Exceeded", [0]) ) ), TD({style: "width:100%"}), TD( BUTTON({"class": "netLimitButton", title: "$limitPrefsTitle", onclick: "$onPreferences"}, $STR("LimitPrefs") ) ), TD("&nbsp;") ) ) ) ) ), isCollapsed: function() { return this.collapsed; }, onPreferences: function(event) { openNewTab("about:config"); }, updateCounter: function(row) { removeClass(row, "collapsed"); // Update info within the limit row. var limitLabel = row.getElementsByClassName("netLimitLabel").item(0); limitLabel.firstChild.nodeValue = $STRP("plural.Limit_Exceeded", [row.limitInfo.totalCount]); }, createTable: function(parent, limitInfo) { var table = this.tableTag.replace({}, parent); var row = this.createRow(table.firstChild.firstChild, limitInfo); return [table, row]; }, createRow: function(parent, limitInfo) { var row = this.limitTag.insertRows(limitInfo, parent, this)[0]; row.limitInfo = limitInfo; return row; }, // nsIPrefObserver observe: function(subject, topic, data) { // We're observing preferences only. if (topic != "nsPref:changed") return; if (data.indexOf("net.logLimit") != -1) this.updateMaxLimit(); }, updateMaxLimit: function() { var value = Firebug.getPref(Firebug.prefDomain, "net.logLimit"); maxQueueRequests = value ? value : maxQueueRequests; } }); var NetLimit = Firebug.NetMonitor.NetLimit; // ************************************************************************************************ Firebug.NetMonitor.ResponseSizeLimit = domplate(Firebug.Rep, { tag: DIV({"class": "netInfoResponseSizeLimit"}, SPAN("$object.beforeLink"), A({"class": "objectLink", onclick: "$onClickLink"}, "$object.linkText" ), SPAN("$object.afterLink") ), reLink: /^(.*)<a>(.*)<\/a>(.*$)/, append: function(obj, parent) { var m = obj.text.match(this.reLink); return this.tag.append({onClickLink: obj.onClickLink, object: { beforeLink: m[1], linkText: m[2], afterLink: m[3] }}, parent, this); } }); // ************************************************************************************************ // ************************************************************************************************ Firebug.NetMonitor.Utils = { findHeader: function(headers, name) { if (!headers) return null; name = name.toLowerCase(); for (var i = 0; i < headers.length; ++i) { var headerName = headers[i].name.toLowerCase(); if (headerName == name) return headers[i].value; } }, formatPostText: function(text) { if (text instanceof XMLDocument) return getElementXML(text.documentElement); else return text; }, getPostText: function(file, context, noLimit) { if (!file.postText) { file.postText = readPostTextFromRequest(file.request, context); if (!file.postText && context) file.postText = readPostTextFromPage(file.href, context); } if (!file.postText) return file.postText; var limit = Firebug.netDisplayedPostBodyLimit; if (file.postText.length > limit && !noLimit) { return cropString(file.postText, limit, "\n\n... " + $STR("net.postDataSizeLimitMessage") + " ...\n\n"); } return file.postText; }, getResponseText: function(file, context) { // The response can be also empty string so, check agains "undefined". return (typeof(file.responseText) != "undefined")? file.responseText : context.sourceCache.loadText(file.href, file.method, file); }, isURLEncodedRequest: function(file, context) { var text = Utils.getPostText(file, context); if (text && text.toLowerCase().indexOf("content-type: application/x-www-form-urlencoded") == 0) return true; // The header value doesn't have to be always exactly "application/x-www-form-urlencoded", // there can be even charset specified. So, use indexOf rather than just "==". var headerValue = Utils.findHeader(file.requestHeaders, "content-type"); if (headerValue && headerValue.indexOf("application/x-www-form-urlencoded") == 0) return true; return false; }, isMultiPartRequest: function(file, context) { var text = Utils.getPostText(file, context); if (text && text.toLowerCase().indexOf("content-type: multipart/form-data") == 0) return true; return false; }, getMimeType: function(mimeType, uri) { if (!mimeType || !(mimeCategoryMap.hasOwnProperty(mimeType))) { var ext = getFileExtension(uri); if (!ext) return mimeType; else { var extMimeType = mimeExtensionMap[ext.toLowerCase()]; return extMimeType ? extMimeType : mimeType; } } else return mimeType; }, getDateFromSeconds: function(s) { var d = new Date(); d.setTime(s*1000); return d; }, getHttpHeaders: function(request, file) { try { var http = QI(request, Ci.nsIHttpChannel); file.status = request.responseStatus; // xxxHonza: is there any problem to do this in requestedFile method? file.method = http.requestMethod; file.urlParams = parseURLParams(file.href); file.mimeType = Utils.getMimeType(request.contentType, request.name); if (!file.responseHeaders && Firebug.collectHttpHeaders) { var requestHeaders = [], responseHeaders = []; http.visitRequestHeaders({ visitHeader: function(name, value) { requestHeaders.push({name: name, value: value}); } }); http.visitResponseHeaders({ visitHeader: function(name, value) { responseHeaders.push({name: name, value: value}); } }); file.requestHeaders = requestHeaders; file.responseHeaders = responseHeaders; } } catch (exc) { // An exception can be throwed e.g. when the request is aborted and // request.responseStatus is accessed. if (FBTrace.DBG_ERRORS) FBTrace.sysout("net.getHttpHeaders FAILS " + file.href, exc); } }, isXHR: function(request) { try { var callbacks = request.notificationCallbacks; var xhrRequest = callbacks ? callbacks.getInterface(Ci.nsIXMLHttpRequest) : null; if (FBTrace.DBG_NET) FBTrace.sysout("net.isXHR; " + (xhrRequest != null) + ", " + safeGetName(request)); return (xhrRequest != null); } catch (exc) { } return false; }, getFileCategory: function(file) { if (file.category) { if (FBTrace.DBG_NET) FBTrace.sysout("net.getFileCategory; current: " + file.category + " for: " + file.href, file); return file.category; } if (file.isXHR) { if (FBTrace.DBG_NET) FBTrace.sysout("net.getFileCategory; XHR for: " + file.href, file); return file.category = "xhr"; } if (!file.mimeType) { var ext = getFileExtension(file.href); if (ext) file.mimeType = mimeExtensionMap[ext.toLowerCase()]; } /*if (FBTrace.DBG_NET) FBTrace.sysout("net.getFileCategory; " + mimeCategoryMap[file.mimeType] + ", mimeType: " + file.mimeType + " for: " + file.href, file);*/ if (!file.mimeType) return ""; // Solve cases when charset is also specified, eg "text/html; charset=UTF-8". var mimeType = file.mimeType; if (mimeType) mimeType = mimeType.split(";")[0]; return (file.category = mimeCategoryMap[mimeType]); } }; var Utils = Firebug.NetMonitor.Utils; // ************************************************************************************************ //Firebug.registerRep(Firebug.NetMonitor.NetRequestTable); //Firebug.registerActivableModule(Firebug.NetMonitor); //Firebug.registerPanel(NetPanel); Firebug.registerModule(Firebug.NetMonitor); //Firebug.registerRep(Firebug.NetMonitor.BreakpointRep); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants //const Cc = Components.classes; //const Ci = Components.interfaces; // List of contexts with XHR spy attached. var contexts = []; // ************************************************************************************************ // Spy Module /** * @module Represents a XHR Spy module. The main purpose of the XHR Spy feature is to monitor * XHR activity of the current page and create appropriate log into the Console panel. * This feature can be controlled by an option <i>Show XMLHttpRequests</i> (from within the * console panel). * * The module is responsible for attaching/detaching a HTTP Observers when Firebug is * activated/deactivated for a site. */ Firebug.Spy = extend(Firebug.Module, /** @lends Firebug.Spy */ { dispatchName: "spy", initialize: function() { if (Firebug.TraceModule) Firebug.TraceModule.addListener(this.TraceListener); Firebug.Module.initialize.apply(this, arguments); }, shutdown: function() { Firebug.Module.shutdown.apply(this, arguments); if (Firebug.TraceModule) Firebug.TraceModule.removeListener(this.TraceListener); }, initContext: function(context) { context.spies = []; if (Firebug.showXMLHttpRequests && Firebug.Console.isAlwaysEnabled()) this.attachObserver(context, context.window); if (FBTrace.DBG_SPY) FBTrace.sysout("spy.initContext " + contexts.length + " ", context.getName()); }, destroyContext: function(context) { // For any spies that are in progress, remove our listeners so that they don't leak this.detachObserver(context, null); if (FBTrace.DBG_SPY && context.spies.length) FBTrace.sysout("spy.destroyContext; ERROR There are leaking Spies (" + context.spies.length + ") " + context.getName()); delete context.spies; if (FBTrace.DBG_SPY) FBTrace.sysout("spy.destroyContext " + contexts.length + " ", context.getName()); }, watchWindow: function(context, win) { if (Firebug.showXMLHttpRequests && Firebug.Console.isAlwaysEnabled()) this.attachObserver(context, win); }, unwatchWindow: function(context, win) { try { // This make sure that the existing context is properly removed from "contexts" array. this.detachObserver(context, win); } catch (ex) { // Get exceptions here sometimes, so let's just ignore them // since the window is going away anyhow ERROR(ex); } }, updateOption: function(name, value) { // XXXjjb Honza, if Console.isEnabled(context) false, then this can't be called, // but somehow seems not correct if (name == "showXMLHttpRequests") { var tach = value ? this.attachObserver : this.detachObserver; for (var i = 0; i < TabWatcher.contexts.length; ++i) { var context = TabWatcher.contexts[i]; iterateWindows(context.window, function(win) { tach.apply(this, [context, win]); }); } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Attaching Spy to XHR requests. /** * Returns false if Spy should not be attached to XHRs executed by the specified window. */ skipSpy: function(win) { if (!win) return true; // Don't attach spy to chrome. var uri = safeGetWindowLocation(win); if (uri && (uri.indexOf("about:") == 0 || uri.indexOf("chrome:") == 0)) return true; }, attachObserver: function(context, win) { if (Firebug.Spy.skipSpy(win)) return; for (var i=0; i<contexts.length; ++i) { if ((contexts[i].context == context) && (contexts[i].win == win)) return; } // Register HTTP observers only once. if (contexts.length == 0) { httpObserver.addObserver(SpyHttpObserver, "firebug-http-event", false); SpyHttpActivityObserver.registerObserver(); } contexts.push({context: context, win: win}); if (FBTrace.DBG_SPY) FBTrace.sysout("spy.attachObserver (HTTP) " + contexts.length + " ", context.getName()); }, detachObserver: function(context, win) { for (var i=0; i<contexts.length; ++i) { if (contexts[i].context == context) { if (win && (contexts[i].win != win)) continue; contexts.splice(i, 1); // If no context is using spy, remvove the (only one) HTTP observer. if (contexts.length == 0) { httpObserver.removeObserver(SpyHttpObserver, "firebug-http-event"); SpyHttpActivityObserver.unregisterObserver(); } if (FBTrace.DBG_SPY) FBTrace.sysout("spy.detachObserver (HTTP) " + contexts.length + " ", context.getName()); return; } } }, /** * Return XHR object that is associated with specified request <i>nsIHttpChannel</i>. * Returns null if the request doesn't represent XHR. */ getXHR: function(request) { // Does also query-interface for nsIHttpChannel. if (!(request instanceof Ci.nsIHttpChannel)) return null; try { var callbacks = request.notificationCallbacks; return (callbacks ? callbacks.getInterface(Ci.nsIXMLHttpRequest) : null); } catch (exc) { if (exc.name == "NS_NOINTERFACE") { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.getXHR; Request is not nsIXMLHttpRequest: " + safeGetRequestName(request)); } } return null; } }); // ************************************************************************************************ /* function getSpyForXHR(request, xhrRequest, context, noCreate) { var spy = null; // Iterate all existing spy objects in this context and look for one that is // already created for this request. var length = context.spies.length; for (var i=0; i<length; i++) { spy = context.spies[i]; if (spy.request == request) return spy; } if (noCreate) return null; spy = new Firebug.Spy.XMLHttpRequestSpy(request, xhrRequest, context); context.spies.push(spy); var name = request.URI.asciiSpec; var origName = request.originalURI.asciiSpec; // Attach spy only to the original request. Notice that there can be more network requests // made by the same XHR if redirects are involved. if (name == origName) spy.attach(); if (FBTrace.DBG_SPY) FBTrace.sysout("spy.getSpyForXHR; New spy object created (" + (name == origName ? "new XHR" : "redirected XHR") + ") for: " + name, spy); return spy; } /**/ // ************************************************************************************************ /** * @class This class represents a Spy object that is attached to XHR. This object * registers various listeners into the XHR in order to monitor various events fired * during the request process (onLoad, onAbort, etc.) */ /* Firebug.Spy.XMLHttpRequestSpy = function(request, xhrRequest, context) { this.request = request; this.xhrRequest = xhrRequest; this.context = context; this.responseText = ""; // For compatibility with the Net templates. this.isXHR = true; // Support for activity-observer this.transactionStarted = false; this.transactionClosed = false; }; /**/ //Firebug.Spy.XMLHttpRequestSpy.prototype = /** @lends Firebug.Spy.XMLHttpRequestSpy */ /* { attach: function() { var spy = this; this.onReadyStateChange = function(event) { onHTTPSpyReadyStateChange(spy, event); }; this.onLoad = function() { onHTTPSpyLoad(spy); }; this.onError = function() { onHTTPSpyError(spy); }; this.onAbort = function() { onHTTPSpyAbort(spy); }; // xxxHonza: #502959 is still failing on Fx 3.5 // Use activity distributor to identify 3.6 if (SpyHttpActivityObserver.getActivityDistributor()) { this.onreadystatechange = this.xhrRequest.onreadystatechange; this.xhrRequest.onreadystatechange = this.onReadyStateChange; } this.xhrRequest.addEventListener("load", this.onLoad, false); this.xhrRequest.addEventListener("error", this.onError, false); this.xhrRequest.addEventListener("abort", this.onAbort, false); // xxxHonza: should be removed from FB 3.6 if (!SpyHttpActivityObserver.getActivityDistributor()) this.context.sourceCache.addListener(this); }, detach: function() { // Bubble out if already detached. if (!this.onLoad) return; // If the activity distributor is available, let's detach it when the XHR // transaction is closed. Since, in case of multipart XHRs the onLoad method // (readyState == 4) can be called mutliple times. // Keep in mind: // 1) It can happen that that the TRANSACTION_CLOSE event comes before // the onLoad (if the XHR is made as part of the page load) so, detach if // it's already closed. // 2) In case of immediate cache responses, the transaction doesn't have to // be started at all (or the activity observer is no available in Firefox 3.5). // So, also detach in this case. if (this.transactionStarted && !this.transactionClosed) return; if (FBTrace.DBG_SPY) FBTrace.sysout("spy.detach; " + this.href); // Remove itself from the list of active spies. remove(this.context.spies, this); if (this.onreadystatechange) this.xhrRequest.onreadystatechange = this.onreadystatechange; try { this.xhrRequest.removeEventListener("load", this.onLoad, false); } catch (e) {} try { this.xhrRequest.removeEventListener("error", this.onError, false); } catch (e) {} try { this.xhrRequest.removeEventListener("abort", this.onAbort, false); } catch (e) {} this.onreadystatechange = null; this.onLoad = null; this.onError = null; this.onAbort = null; // xxxHonza: shouuld be removed from FB 1.6 if (!SpyHttpActivityObserver.getActivityDistributor()) this.context.sourceCache.removeListener(this); }, getURL: function() { return this.xhrRequest.channel ? this.xhrRequest.channel.name : this.href; }, // Cache listener onStopRequest: function(context, request, responseText) { if (!responseText) return; if (request == this.request) this.responseText = responseText; }, }; /**/ // ************************************************************************************************ /* function onHTTPSpyReadyStateChange(spy, event) { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.onHTTPSpyReadyStateChange " + spy.xhrRequest.readyState + " (multipart: " + spy.xhrRequest.multipart + ")"); // Remember just in case spy is detached (readyState == 4). var originalHandler = spy.onreadystatechange; // Force response text to be updated in the UI (in case the console entry // has been already expanded and the response tab selected). if (spy.logRow && spy.xhrRequest.readyState >= 3) { var netInfoBox = getChildByClass(spy.logRow, "spyHead", "netInfoBody"); if (netInfoBox) { netInfoBox.htmlPresented = false; netInfoBox.responsePresented = false; } } // If the request is loading update the end time. if (spy.xhrRequest.readyState == 3) { spy.responseTime = spy.endTime - spy.sendTime; updateTime(spy); } // Request loaded. Get all the info from the request now, just in case the // XHR would be aborted in the original onReadyStateChange handler. if (spy.xhrRequest.readyState == 4) { // Cumulate response so, multipart response content is properly displayed. if (SpyHttpActivityObserver.getActivityDistributor()) spy.responseText += spy.xhrRequest.responseText; else { // xxxHonza: remove from FB 1.6 if (!spy.responseText) spy.responseText = spy.xhrRequest.responseText; } // The XHR is loaded now (used also by the activity observer). spy.loaded = true; // Update UI. updateHttpSpyInfo(spy); // Notify Net pane about a request beeing loaded. // xxxHonza: I don't think this is necessary. var netProgress = spy.context.netProgress; if (netProgress) netProgress.post(netProgress.stopFile, [spy.request, spy.endTime, spy.postText, spy.responseText]); // Notify registered listeners about finish of the XHR. dispatch(Firebug.Spy.fbListeners, "onLoad", [spy.context, spy]); } // Pass the event to the original page handler. callPageHandler(spy, event, originalHandler); } function onHTTPSpyLoad(spy) { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.onHTTPSpyLoad: " + spy.href, spy); // Detach must be done in onLoad (not in onreadystatechange) otherwise // onAbort would not be handled. spy.detach(); // xxxHonza: Still needed for Fx 3.5 (#502959) if (!SpyHttpActivityObserver.getActivityDistributor()) onHTTPSpyReadyStateChange(spy, null); } function onHTTPSpyError(spy) { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.onHTTPSpyError; " + spy.href, spy); spy.detach(); spy.loaded = true; if (spy.logRow) { removeClass(spy.logRow, "loading"); setClass(spy.logRow, "error"); } } function onHTTPSpyAbort(spy) { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.onHTTPSpyAbort: " + spy.href, spy); spy.detach(); spy.loaded = true; if (spy.logRow) { removeClass(spy.logRow, "loading"); setClass(spy.logRow, "error"); } spy.statusText = "Aborted"; updateLogRow(spy); // Notify Net pane about a request beeing aborted. // xxxHonza: the net panel shoud find out this itself. var netProgress = spy.context.netProgress; if (netProgress) netProgress.post(netProgress.abortFile, [spy.request, spy.endTime, spy.postText, spy.responseText]); } /**/ // ************************************************************************************************ /** * @domplate Represents a template for XHRs logged in the Console panel. The body of the * log (displayed when expanded) is rendered using {@link Firebug.NetMonitor.NetInfoBody}. */ Firebug.Spy.XHR = domplate(Firebug.Rep, /** @lends Firebug.Spy.XHR */ { tag: DIV({"class": "spyHead", _repObject: "$object"}, TABLE({"class": "spyHeadTable focusRow outerFocusRow", cellpadding: 0, cellspacing: 0, "role": "listitem", "aria-expanded": "false"}, TBODY({"role": "presentation"}, TR({"class": "spyRow"}, TD({"class": "spyTitleCol spyCol", onclick: "$onToggleBody"}, DIV({"class": "spyTitle"}, "$object|getCaption" ), DIV({"class": "spyFullTitle spyTitle"}, "$object|getFullUri" ) ), TD({"class": "spyCol"}, DIV({"class": "spyStatus"}, "$object|getStatus") ), TD({"class": "spyCol"}, SPAN({"class": "spyIcon"}) ), TD({"class": "spyCol"}, SPAN({"class": "spyTime"}) ), TD({"class": "spyCol"}, TAG(FirebugReps.SourceLink.tag, {object: "$object.sourceLink"}) ) ) ) ) ), getCaption: function(spy) { return spy.method.toUpperCase() + " " + cropString(spy.getURL(), 100); }, getFullUri: function(spy) { return spy.method.toUpperCase() + " " + spy.getURL(); }, getStatus: function(spy) { var text = ""; if (spy.statusCode) text += spy.statusCode + " "; if (spy.statusText) return text += spy.statusText; return text; }, onToggleBody: function(event) { var target = event.currentTarget || event.srcElement; var logRow = getAncestorByClass(target, "logRow-spy"); if (isLeftClick(event)) { toggleClass(logRow, "opened"); var spy = getChildByClass(logRow, "spyHead").repObject; var spyHeadTable = getAncestorByClass(target, "spyHeadTable"); if (hasClass(logRow, "opened")) { updateHttpSpyInfo(spy, logRow); if (spyHeadTable) spyHeadTable.setAttribute('aria-expanded', 'true'); } else { //var netInfoBox = getChildByClass(spy.logRow, "spyHead", "netInfoBody"); //dispatch(Firebug.NetMonitor.NetInfoBody.fbListeners, "destroyTabBody", [netInfoBox, spy]); //if (spyHeadTable) // spyHeadTable.setAttribute('aria-expanded', 'false'); } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copyURL: function(spy) { copyToClipboard(spy.getURL()); }, copyParams: function(spy) { var text = spy.postText; if (!text) return; var url = reEncodeURL(spy, text, true); copyToClipboard(url); }, copyResponse: function(spy) { copyToClipboard(spy.responseText); }, openInTab: function(spy) { openNewTab(spy.getURL(), spy.postText); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * supportsObject: function(object) { // TODO: xxxpedro spy xhr return false; return object instanceof Firebug.Spy.XMLHttpRequestSpy; }, browseObject: function(spy, context) { var url = spy.getURL(); openNewTab(url); return true; }, getRealObject: function(spy, context) { return spy.xhrRequest; }, getContextMenuItems: function(spy) { var items = [ {label: "CopyLocation", command: bindFixed(this.copyURL, this, spy) } ]; if (spy.postText) { items.push( {label: "CopyLocationParameters", command: bindFixed(this.copyParams, this, spy) } ); } items.push( {label: "CopyResponse", command: bindFixed(this.copyResponse, this, spy) }, "-", {label: "OpenInTab", command: bindFixed(this.openInTab, this, spy) } ); return items; } }); // ************************************************************************************************ function updateTime(spy) { var timeBox = spy.logRow.getElementsByClassName("spyTime").item(0); if (spy.responseTime) timeBox.textContent = " " + formatTime(spy.responseTime); } function updateLogRow(spy) { updateTime(spy); var statusBox = spy.logRow.getElementsByClassName("spyStatus").item(0); statusBox.textContent = Firebug.Spy.XHR.getStatus(spy); removeClass(spy.logRow, "loading"); setClass(spy.logRow, "loaded"); try { var errorRange = Math.floor(spy.xhrRequest.status/100); if (errorRange == 4 || errorRange == 5) setClass(spy.logRow, "error"); } catch (exc) { } } var updateHttpSpyInfo = function updateHttpSpyInfo(spy, logRow) { if (!spy.logRow && logRow) spy.logRow = logRow; if (!spy.logRow || !hasClass(spy.logRow, "opened")) return; if (!spy.params) //spy.params = parseURLParams(spy.href+""); spy.params = parseURLParams(spy.href+""); if (!spy.requestHeaders) spy.requestHeaders = getRequestHeaders(spy); if (!spy.responseHeaders && spy.loaded) spy.responseHeaders = getResponseHeaders(spy); var template = Firebug.NetMonitor.NetInfoBody; var netInfoBox = getChildByClass(spy.logRow, "spyHead", "netInfoBody"); if (!netInfoBox) { var head = getChildByClass(spy.logRow, "spyHead"); netInfoBox = template.tag.append({"file": spy}, head); dispatch(template.fbListeners, "initTabBody", [netInfoBox, spy]); template.selectTabByName(netInfoBox, "Response"); } else { template.updateInfo(netInfoBox, spy, spy.context); } }; // ************************************************************************************************ function getRequestHeaders(spy) { var headers = []; var channel = spy.xhrRequest.channel; if (channel instanceof Ci.nsIHttpChannel) { channel.visitRequestHeaders({ visitHeader: function(name, value) { headers.push({name: name, value: value}); } }); } return headers; } function getResponseHeaders(spy) { var headers = []; try { var channel = spy.xhrRequest.channel; if (channel instanceof Ci.nsIHttpChannel) { channel.visitResponseHeaders({ visitHeader: function(name, value) { headers.push({name: name, value: value}); } }); } } catch (exc) { if (FBTrace.DBG_SPY || FBTrace.DBG_ERRORS) FBTrace.sysout("spy.getResponseHeaders; EXCEPTION " + safeGetRequestName(spy.request), exc); } return headers; } // ************************************************************************************************ // Registration Firebug.registerModule(Firebug.Spy); //Firebug.registerRep(Firebug.Spy.XHR); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // List of JSON content types. var contentTypes = { // TODO: create issue: jsonViewer will not try to evaluate the contents of the requested file // if the content-type is set to "text/plain" //"text/plain": 1, "text/javascript": 1, "text/x-javascript": 1, "text/json": 1, "text/x-json": 1, "application/json": 1, "application/x-json": 1, "application/javascript": 1, "application/x-javascript": 1, "application/json-rpc": 1 }; // ************************************************************************************************ // Model implementation Firebug.JSONViewerModel = extend(Firebug.Module, { dispatchName: "jsonViewer", initialize: function() { Firebug.NetMonitor.NetInfoBody.addListener(this); // Used by Firebug.DOMPanel.DirTable domplate. this.toggles = {}; }, shutdown: function() { Firebug.NetMonitor.NetInfoBody.removeListener(this); }, initTabBody: function(infoBox, file) { if (FBTrace.DBG_JSONVIEWER) FBTrace.sysout("jsonviewer.initTabBody", infoBox); // Let listeners to parse the JSON. dispatch(this.fbListeners, "onParseJSON", [file]); // The JSON is still no there, try to parse most common cases. if (!file.jsonObject) { ///if (this.isJSON(safeGetContentType(file.request), file.responseText)) if (this.isJSON(file.mimeType, file.responseText)) file.jsonObject = this.parseJSON(file); } // The jsonObject is created so, the JSON tab can be displayed. if (file.jsonObject && hasProperties(file.jsonObject)) { Firebug.NetMonitor.NetInfoBody.appendTab(infoBox, "JSON", ///$STR("jsonviewer.tab.JSON")); $STR("JSON")); if (FBTrace.DBG_JSONVIEWER) FBTrace.sysout("jsonviewer.initTabBody; JSON object available " + (typeof(file.jsonObject) != "undefined"), file.jsonObject); } }, isJSON: function(contentType, data) { // Workaround for JSON responses without proper content type // Let's consider all responses starting with "{" as JSON. In the worst // case there will be an exception when parsing. This means that no-JSON // responses (and post data) (with "{") can be parsed unnecessarily, // which represents a little overhead, but this happens only if the request // is actually expanded by the user in the UI (Net & Console panels). ///var responseText = data ? trimLeft(data) : null; ///if (responseText && responseText.indexOf("{") == 0) /// return true; var responseText = data ? trim(data) : null; if (responseText && responseText.indexOf("{") == 0) return true; if (!contentType) return false; contentType = contentType.split(";")[0]; contentType = trim(contentType); return contentTypes[contentType]; }, // Update listener for TabView updateTabBody: function(infoBox, file, context) { var tab = infoBox.selectedTab; ///var tabBody = infoBox.getElementsByClassName("netInfoJSONText").item(0); var tabBody = $$(".netInfoJSONText", infoBox)[0]; if (!hasClass(tab, "netInfoJSONTab") || tabBody.updated) return; tabBody.updated = true; if (file.jsonObject) { Firebug.DOMPanel.DirTable.tag.replace( {object: file.jsonObject, toggles: this.toggles}, tabBody); } }, parseJSON: function(file) { var jsonString = new String(file.responseText); ///return parseJSONString(jsonString, "http://" + file.request.originalURI.host); return parseJSONString(jsonString); } }); // ************************************************************************************************ // Registration Firebug.registerModule(Firebug.JSONViewerModel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants // List of XML related content types. var xmlContentTypes = [ "text/xml", "application/xml", "application/xhtml+xml", "application/rss+xml", "application/atom+xml",, "application/vnd.mozilla.maybe.feed", "application/rdf+xml", "application/vnd.mozilla.xul+xml" ]; // ************************************************************************************************ // Model implementation /** * @module Implements viewer for XML based network responses. In order to create a new * tab wihin network request detail, a listener is registered into * <code>Firebug.NetMonitor.NetInfoBody</code> object. */ Firebug.XMLViewerModel = extend(Firebug.Module, { dispatchName: "xmlViewer", initialize: function() { ///Firebug.ActivableModule.initialize.apply(this, arguments); Firebug.Module.initialize.apply(this, arguments); Firebug.NetMonitor.NetInfoBody.addListener(this); }, shutdown: function() { ///Firebug.ActivableModule.shutdown.apply(this, arguments); Firebug.Module.shutdown.apply(this, arguments); Firebug.NetMonitor.NetInfoBody.removeListener(this); }, /** * Check response's content-type and if it's a XML, create a new tab with XML preview. */ initTabBody: function(infoBox, file) { if (FBTrace.DBG_XMLVIEWER) FBTrace.sysout("xmlviewer.initTabBody", infoBox); // If the response is XML let's display a pretty preview. ///if (this.isXML(safeGetContentType(file.request))) if (this.isXML(file.mimeType, file.responseText)) { Firebug.NetMonitor.NetInfoBody.appendTab(infoBox, "XML", ///$STR("xmlviewer.tab.XML")); $STR("XML")); if (FBTrace.DBG_XMLVIEWER) FBTrace.sysout("xmlviewer.initTabBody; XML response available"); } }, isXML: function(contentType) { if (!contentType) return false; // Look if the response is XML based. for (var i=0; i<xmlContentTypes.length; i++) { if (contentType.indexOf(xmlContentTypes[i]) == 0) return true; } return false; }, /** * Parse XML response and render pretty printed preview. */ updateTabBody: function(infoBox, file, context) { var tab = infoBox.selectedTab; ///var tabBody = infoBox.getElementsByClassName("netInfoXMLText").item(0); var tabBody = $$(".netInfoXMLText", infoBox)[0]; if (!hasClass(tab, "netInfoXMLTab") || tabBody.updated) return; tabBody.updated = true; this.insertXML(tabBody, Firebug.NetMonitor.Utils.getResponseText(file, context)); }, insertXML: function(parentNode, text) { var xmlText = text.replace(/^\s*<?.+?>\s*/, ""); var div = parentNode.ownerDocument.createElement("div"); div.innerHTML = xmlText; var root = div.getElementsByTagName("*")[0]; /*** var parser = CCIN("@mozilla.org/xmlextras/domparser;1", "nsIDOMParser"); var doc = parser.parseFromString(text, "text/xml"); var root = doc.documentElement; // Error handling var nsURI = "http://www.mozilla.org/newlayout/xml/parsererror.xml"; if (root.namespaceURI == nsURI && root.nodeName == "parsererror") { this.ParseError.tag.replace({error: { message: root.firstChild.nodeValue, source: root.lastChild.textContent }}, parentNode); return; } /**/ if (FBTrace.DBG_XMLVIEWER) FBTrace.sysout("xmlviewer.updateTabBody; XML response parsed", doc); // Override getHidden in these templates. The parsed XML documen is // hidden, but we want to display it using 'visible' styling. /* var templates = [ Firebug.HTMLPanel.CompleteElement, Firebug.HTMLPanel.Element, Firebug.HTMLPanel.TextElement, Firebug.HTMLPanel.EmptyElement, Firebug.HTMLPanel.XEmptyElement, ]; var originals = []; for (var i=0; i<templates.length; i++) { originals[i] = templates[i].getHidden; templates[i].getHidden = function() { return ""; } } /**/ // Generate XML preview. ///Firebug.HTMLPanel.CompleteElement.tag.replace({object: doc.documentElement}, parentNode); // TODO: xxxpedro html3 ///Firebug.HTMLPanel.CompleteElement.tag.replace({object: root}, parentNode); var html = []; Firebug.Reps.appendNode(root, html); parentNode.innerHTML = html.join(""); /* for (var i=0; i<originals.length; i++) templates[i].getHidden = originals[i];/**/ } }); // ************************************************************************************************ // Domplate /** * @domplate Represents a template for displaying XML parser errors. Used by * <code>Firebug.XMLViewerModel</code>. */ Firebug.XMLViewerModel.ParseError = domplate(Firebug.Rep, { tag: DIV({"class": "xmlInfoError"}, DIV({"class": "xmlInfoErrorMsg"}, "$error.message"), PRE({"class": "xmlInfoErrorSource"}, "$error|getSource") ), getSource: function(error) { var parts = error.source.split("\n"); if (parts.length != 2) return error.source; var limit = 50; var column = parts[1].length; if (column >= limit) { parts[0] = "..." + parts[0].substr(column - limit); parts[1] = "..." + parts[1].substr(column - limit); } if (parts[0].length > 80) parts[0] = parts[0].substr(0, 80) + "..."; return parts.join("\n"); } }); // ************************************************************************************************ // Registration Firebug.registerModule(Firebug.XMLViewerModel); }}); /* See license.txt for terms of usage */ // next-generation Console Panel (will override consoje.js) FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Constants /* const Cc = Components.classes; const Ci = Components.interfaces; const nsIPrefBranch2 = Ci.nsIPrefBranch2; const PrefService = Cc["@mozilla.org/preferences-service;1"]; const prefs = PrefService.getService(nsIPrefBranch2); /**/ /* // new offline message handler o = {x:1,y:2}; r = Firebug.getRep(o); r.tag.tag.compile(); outputs = []; html = r.tag.renderHTML({object:o}, outputs); // finish rendering the template (the DOM part) target = $("build"); target.innerHTML = html; root = target.firstChild; domArgs = [root, r.tag.context, 0]; domArgs.push.apply(domArgs, r.tag.domArgs); domArgs.push.apply(domArgs, outputs); r.tag.tag.renderDOM.apply(self ? self : r.tag.subject, domArgs); */ var consoleQueue = []; var lastHighlightedObject; var FirebugContext = Env.browser; // ************************************************************************************************ var maxQueueRequests = 500; // ************************************************************************************************ Firebug.ConsoleBase = { log: function(object, context, className, rep, noThrottle, sourceLink) { //dispatch(this.fbListeners,"log",[context, object, className, sourceLink]); return this.logRow(appendObject, object, context, className, rep, sourceLink, noThrottle); }, logFormatted: function(objects, context, className, noThrottle, sourceLink) { //dispatch(this.fbListeners,"logFormatted",[context, objects, className, sourceLink]); return this.logRow(appendFormatted, objects, context, className, null, sourceLink, noThrottle); }, openGroup: function(objects, context, className, rep, noThrottle, sourceLink, noPush) { return this.logRow(appendOpenGroup, objects, context, className, rep, sourceLink, noThrottle); }, closeGroup: function(context, noThrottle) { return this.logRow(appendCloseGroup, null, context, null, null, null, noThrottle, true); }, logRow: function(appender, objects, context, className, rep, sourceLink, noThrottle, noRow) { // TODO: xxxpedro console console2 noThrottle = true; // xxxpedro forced because there is no TabContext yet if (!context) context = FirebugContext; if (FBTrace.DBG_ERRORS && !context) FBTrace.sysout("Console.logRow has no context, skipping objects", objects); if (!context) return; if (noThrottle || !context) { var panel = this.getPanel(context); if (panel) { var row = panel.append(appender, objects, className, rep, sourceLink, noRow); var container = panel.panelNode; // TODO: xxxpedro what is this? console console2 /* var template = Firebug.NetMonitor.NetLimit; while (container.childNodes.length > maxQueueRequests + 1) { clearDomplate(container.firstChild.nextSibling); container.removeChild(container.firstChild.nextSibling); panel.limit.limitInfo.totalCount++; template.updateCounter(panel.limit); } dispatch([Firebug.A11yModel], "onLogRowCreated", [panel , row]); /**/ return row; } else { consoleQueue.push([appender, objects, context, className, rep, sourceLink, noThrottle, noRow]); } } else { if (!context.throttle) { //FBTrace.sysout("console.logRow has not context.throttle! "); return; } var args = [appender, objects, context, className, rep, sourceLink, true, noRow]; context.throttle(this.logRow, this, args); } }, appendFormatted: function(args, row, context) { if (!context) context = FirebugContext; var panel = this.getPanel(context); panel.appendFormatted(args, row); }, clear: function(context) { if (!context) //context = FirebugContext; context = Firebug.context; /* if (context) Firebug.Errors.clear(context); /**/ var panel = this.getPanel(context, true); if (panel) { panel.clear(); } }, // Override to direct output to your panel getPanel: function(context, noCreate) { //return context.getPanel("console", noCreate); // TODO: xxxpedro console console2 return Firebug.chrome ? Firebug.chrome.getPanel("Console") : null; } }; // ************************************************************************************************ //TODO: xxxpedro //var ActivableConsole = extend(Firebug.ActivableModule, Firebug.ConsoleBase); var ActivableConsole = extend(Firebug.ConsoleBase, { isAlwaysEnabled: function() { return true; } }); Firebug.Console = Firebug.Console = extend(ActivableConsole, //Firebug.Console = extend(ActivableConsole, { dispatchName: "console", error: function() { Firebug.Console.logFormatted(arguments, Firebug.browser, "error"); }, flush: function() { dispatch(this.fbListeners,"flush",[]); for (var i=0, length=consoleQueue.length; i<length; i++) { var args = consoleQueue[i]; this.logRow.apply(this, args); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Module showPanel: function(browser, panel) { }, getFirebugConsoleElement: function(context, win) { var element = win.document.getElementById("_firebugConsole"); if (!element) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("getFirebugConsoleElement forcing element"); var elementForcer = "(function(){var r=null; try { r = window._getFirebugConsoleElement();}catch(exc){r=exc;} return r;})();"; // we could just add the elements here if (context.stopped) Firebug.Console.injector.evaluateConsoleScript(context); // todo evaluate consoleForcer on stack else var r = Firebug.CommandLine.evaluateInWebPage(elementForcer, context, win); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("getFirebugConsoleElement forcing element result "+r, r); var element = win.document.getElementById("_firebugConsole"); if (!element) // elementForce fails { if (FBTrace.DBG_ERRORS) FBTrace.sysout("console.getFirebugConsoleElement: no _firebugConsole in win:", win); Firebug.Console.logFormatted(["Firebug cannot find _firebugConsole element", r, win], context, "error", true); } } return element; }, isReadyElsePreparing: function(context, win) // this is the only code that should call injector.attachIfNeeded { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.isReadyElsePreparing, win is " + (win?"an argument: ":"null, context.window: ") + (win?win.location:context.window.location), (win?win:context.window)); if (win) return this.injector.attachIfNeeded(context, win); else { var attached = true; for (var i = 0; i < context.windows.length; i++) attached = attached && this.injector.attachIfNeeded(context, context.windows[i]); // already in the list above attached = attached && this.injector.attachIfNeeded(context, context.window); if (context.windows.indexOf(context.window) == -1) FBTrace.sysout("isReadyElsePreparing ***************** context.window not in context.windows"); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.isReadyElsePreparing attached to "+context.windows.length+" and returns "+attached); return attached; } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends ActivableModule initialize: function() { this.panelName = "console"; //TODO: xxxpedro //Firebug.ActivableModule.initialize.apply(this, arguments); //Firebug.Debugger.addListener(this); }, enable: function() { if (Firebug.Console.isAlwaysEnabled()) this.watchForErrors(); }, disable: function() { if (Firebug.Console.isAlwaysEnabled()) this.unwatchForErrors(); }, initContext: function(context, persistedState) { Firebug.ActivableModule.initContext.apply(this, arguments); context.consoleReloadWarning = true; // mark as need to warn. }, loadedContext: function(context) { for (var url in context.sourceFileMap) return; // if there are any sourceFiles, then do nothing // else we saw no JS, so the reload warning it not needed. this.clearReloadWarning(context); }, clearReloadWarning: function(context) // remove the warning about reloading. { if (context.consoleReloadWarning) { var panel = context.getPanel(this.panelName); panel.clearReloadWarning(); delete context.consoleReloadWarning; } }, togglePersist: function(context) { var panel = context.getPanel(this.panelName); panel.persistContent = panel.persistContent ? false : true; Firebug.chrome.setGlobalAttribute("cmd_togglePersistConsole", "checked", panel.persistContent); }, showContext: function(browser, context) { Firebug.chrome.setGlobalAttribute("cmd_clearConsole", "disabled", !context); Firebug.ActivableModule.showContext.apply(this, arguments); }, destroyContext: function(context, persistedState) { Firebug.Console.injector.detachConsole(context, context.window); // TODO iterate windows? }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onPanelEnable: function(panelName) { if (panelName != this.panelName) // we don't care about other panels return; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onPanelEnable**************"); this.watchForErrors(); Firebug.Debugger.addDependentModule(this); // we inject the console during JS compiles so we need jsd }, onPanelDisable: function(panelName) { if (panelName != this.panelName) // we don't care about other panels return; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onPanelDisable**************"); Firebug.Debugger.removeDependentModule(this); // we inject the console during JS compiles so we need jsd this.unwatchForErrors(); // Make sure possible errors coming from the page and displayed in the Firefox // status bar are removed. this.clear(); }, onSuspendFirebug: function() { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onSuspendFirebug\n"); if (Firebug.Console.isAlwaysEnabled()) this.unwatchForErrors(); }, onResumeFirebug: function() { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onResumeFirebug\n"); if (Firebug.Console.isAlwaysEnabled()) this.watchForErrors(); }, watchForErrors: function() { Firebug.Errors.checkEnabled(); $('fbStatusIcon').setAttribute("console", "on"); }, unwatchForErrors: function() { Firebug.Errors.checkEnabled(); $('fbStatusIcon').removeAttribute("console"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Firebug.Debugger listener onMonitorScript: function(context, frame) { Firebug.Console.log(frame, context); }, onFunctionCall: function(context, frame, depth, calling) { if (calling) Firebug.Console.openGroup([frame, "depth:"+depth], context); else Firebug.Console.closeGroup(context); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * logRow: function(appender, objects, context, className, rep, sourceLink, noThrottle, noRow) { if (!context) context = FirebugContext; if (FBTrace.DBG_WINDOWS && !context) FBTrace.sysout("Console.logRow: no context \n"); if (this.isAlwaysEnabled()) return Firebug.ConsoleBase.logRow.apply(this, arguments); } }); Firebug.ConsoleListener = { log: function(context, object, className, sourceLink) { }, logFormatted: function(context, objects, className, sourceLink) { } }; // ************************************************************************************************ Firebug.ConsolePanel = function () {} // XXjjb attach Firebug so this panel can be extended. //TODO: xxxpedro //Firebug.ConsolePanel.prototype = extend(Firebug.ActivablePanel, Firebug.ConsolePanel.prototype = extend(Firebug.Panel, { wasScrolledToBottom: false, messageCount: 0, lastLogTime: 0, groups: null, limit: null, append: function(appender, objects, className, rep, sourceLink, noRow) { var container = this.getTopContainer(); if (noRow) { appender.apply(this, [objects]); } else { // xxxHonza: Don't update the this.wasScrolledToBottom flag now. // At the beginning (when the first log is created) the isScrolledToBottom // always returns true. //if (this.panelNode.offsetHeight) // this.wasScrolledToBottom = isScrolledToBottom(this.panelNode); var row = this.createRow("logRow", className); appender.apply(this, [objects, row, rep]); if (sourceLink) FirebugReps.SourceLink.tag.append({object: sourceLink}, row); container.appendChild(row); this.filterLogRow(row, this.wasScrolledToBottom); if (this.wasScrolledToBottom) scrollToBottom(this.panelNode); return row; } }, clear: function() { if (this.panelNode) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("ConsolePanel.clear"); clearNode(this.panelNode); this.insertLogLimit(this.context); } }, insertLogLimit: function() { // Create limit row. This row is the first in the list of entries // and initially hidden. It's displayed as soon as the number of // entries reaches the limit. var row = this.createRow("limitRow"); var limitInfo = { totalCount: 0, limitPrefsTitle: $STRF("LimitPrefsTitle", [Firebug.prefDomain+".console.logLimit"]) }; //TODO: xxxpedro console net limit!? return; var netLimitRep = Firebug.NetMonitor.NetLimit; var nodes = netLimitRep.createTable(row, limitInfo); this.limit = nodes[1]; var container = this.panelNode; container.insertBefore(nodes[0], container.firstChild); }, insertReloadWarning: function() { // put the message in, we will clear if the window console is injected. this.warningRow = this.append(appendObject, $STR("message.Reload to activate window console"), "info"); }, clearReloadWarning: function() { if (this.warningRow) { this.warningRow.parentNode.removeChild(this.warningRow); delete this.warningRow; } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * appendObject: function(object, row, rep) { if (!rep) rep = Firebug.getRep(object); return rep.tag.append({object: object}, row); }, appendFormatted: function(objects, row, rep) { if (!objects || !objects.length) return; function logText(text, row) { var node = row.ownerDocument.createTextNode(text); row.appendChild(node); } var format = objects[0]; var objIndex = 0; if (typeof(format) != "string") { format = ""; objIndex = -1; } else // a string { if (objects.length === 1) // then we have only a string... { if (format.length < 1) { // ...and it has no characters. logText("(an empty string)", row); return; } } } var parts = parseFormat(format); var trialIndex = objIndex; for (var i= 0; i < parts.length; i++) { var part = parts[i]; if (part && typeof(part) == "object") { if (++trialIndex > objects.length) // then too few parameters for format, assume unformatted. { format = ""; objIndex = -1; parts.length = 0; break; } } } for (var i = 0; i < parts.length; ++i) { var part = parts[i]; if (part && typeof(part) == "object") { var object = objects[++objIndex]; if (typeof(object) != "undefined") this.appendObject(object, row, part.rep); else this.appendObject(part.type, row, FirebugReps.Text); } else FirebugReps.Text.tag.append({object: part}, row); } for (var i = objIndex+1; i < objects.length; ++i) { logText(" ", row); var object = objects[i]; if (typeof(object) == "string") FirebugReps.Text.tag.append({object: object}, row); else this.appendObject(object, row); } }, appendOpenGroup: function(objects, row, rep) { if (!this.groups) this.groups = []; setClass(row, "logGroup"); setClass(row, "opened"); var innerRow = this.createRow("logRow"); setClass(innerRow, "logGroupLabel"); if (rep) rep.tag.replace({"objects": objects}, innerRow); else this.appendFormatted(objects, innerRow, rep); row.appendChild(innerRow); //dispatch([Firebug.A11yModel], 'onLogRowCreated', [this, innerRow]); var groupBody = this.createRow("logGroupBody"); row.appendChild(groupBody); groupBody.setAttribute('role', 'group'); this.groups.push(groupBody); addEvent(innerRow, "mousedown", function(event) { if (isLeftClick(event)) { //console.log(event.currentTarget == event.target); var target = event.target || event.srcElement; target = getAncestorByClass(target, "logGroupLabel"); var groupRow = target.parentNode; if (hasClass(groupRow, "opened")) { removeClass(groupRow, "opened"); target.setAttribute('aria-expanded', 'false'); } else { setClass(groupRow, "opened"); target.setAttribute('aria-expanded', 'true'); } } }); }, appendCloseGroup: function(object, row, rep) { if (this.groups) this.groups.pop(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // TODO: xxxpedro console2 onMouseMove: function(event) { if (!Firebug.Inspector) return; var target = event.srcElement || event.target; var object = getAncestorByClass(target, "objectLink-element"); object = object ? object.repObject : null; if(object && instanceOf(object, "Element") && object.nodeType == 1) { if(object != lastHighlightedObject) { Firebug.Inspector.drawBoxModel(object); object = lastHighlightedObject; } } else Firebug.Inspector.hideBoxModel(); }, onMouseDown: function(event) { var target = event.srcElement || event.target; var object = getAncestorByClass(target, "objectLink"); var repObject = object ? object.repObject : null; if (!repObject) { return; } if (hasClass(object, "objectLink-object")) { Firebug.chrome.selectPanel("DOM"); Firebug.chrome.getPanel("DOM").select(repObject, true); } else if (hasClass(object, "objectLink-element")) { Firebug.chrome.selectPanel("HTML"); Firebug.chrome.getPanel("HTML").select(repObject, true); } /* if(object && instanceOf(object, "Element") && object.nodeType == 1) { if(object != lastHighlightedObject) { Firebug.Inspector.drawBoxModel(object); object = lastHighlightedObject; } } else Firebug.Inspector.hideBoxModel(); /**/ }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "Console", title: "Console", //searchable: true, //breakable: true, //editable: false, options: { hasCommandLine: true, hasToolButtons: true, isPreRendered: true }, create: function() { Firebug.Panel.create.apply(this, arguments); this.context = Firebug.browser.window; this.document = Firebug.chrome.document; this.onMouseMove = bind(this.onMouseMove, this); this.onMouseDown = bind(this.onMouseDown, this); this.clearButton = new Button({ element: $("fbConsole_btClear"), owner: Firebug.Console, onClick: Firebug.Console.clear }); }, initialize: function() { Firebug.Panel.initialize.apply(this, arguments); // loads persisted content //Firebug.ActivablePanel.initialize.apply(this, arguments); // loads persisted content if (!this.persistedContent && Firebug.Console.isAlwaysEnabled()) { this.insertLogLimit(this.context); // Initialize log limit and listen for changes. this.updateMaxLimit(); if (this.context.consoleReloadWarning) // we have not yet injected the console this.insertReloadWarning(); } //Firebug.Console.injector.install(Firebug.browser.window); addEvent(this.panelNode, "mouseover", this.onMouseMove); addEvent(this.panelNode, "mousedown", this.onMouseDown); this.clearButton.initialize(); //consolex.trace(); //TODO: xxxpedro remove this /* Firebug.Console.openGroup(["asd"], null, "group", null, false); Firebug.Console.log("asd"); Firebug.Console.log("asd"); Firebug.Console.log("asd"); /**/ //TODO: xxxpedro preferences prefs //prefs.addObserver(Firebug.prefDomain, this, false); }, initializeNode : function() { //dispatch([Firebug.A11yModel], 'onInitializeNode', [this]); if (FBTrace.DBG_CONSOLE) { this.onScroller = bind(this.onScroll, this); addEvent(this.panelNode, "scroll", this.onScroller); } this.onResizer = bind(this.onResize, this); this.resizeEventTarget = Firebug.chrome.$('fbContentBox'); addEvent(this.resizeEventTarget, "resize", this.onResizer); }, destroyNode : function() { //dispatch([Firebug.A11yModel], 'onDestroyNode', [this]); if (this.onScroller) removeEvent(this.panelNode, "scroll", this.onScroller); //removeEvent(this.resizeEventTarget, "resize", this.onResizer); }, shutdown: function() { //TODO: xxxpedro console console2 this.clearButton.shutdown(); removeEvent(this.panelNode, "mousemove", this.onMouseMove); removeEvent(this.panelNode, "mousedown", this.onMouseDown); this.destroyNode(); Firebug.Panel.shutdown.apply(this, arguments); //TODO: xxxpedro preferences prefs //prefs.removeObserver(Firebug.prefDomain, this, false); }, ishow: function(state) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.panel show; " + this.context.getName(), state); var enabled = Firebug.Console.isAlwaysEnabled(); if (enabled) { Firebug.Console.disabledPanelPage.hide(this); this.showCommandLine(true); this.showToolbarButtons("fbConsoleButtons", true); Firebug.chrome.setGlobalAttribute("cmd_togglePersistConsole", "checked", this.persistContent); if (state && state.wasScrolledToBottom) { this.wasScrolledToBottom = state.wasScrolledToBottom; delete state.wasScrolledToBottom; } if (this.wasScrolledToBottom) scrollToBottom(this.panelNode); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.show ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", " + this.context.getName()); } else { this.hide(state); Firebug.Console.disabledPanelPage.show(this); } }, ihide: function(state) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.panel hide; " + this.context.getName(), state); this.showToolbarButtons("fbConsoleButtons", false); this.showCommandLine(false); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.hide ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", " + this.context.getName()); }, destroy: function(state) { if (this.panelNode.offsetHeight) this.wasScrolledToBottom = isScrolledToBottom(this.panelNode); if (state) state.wasScrolledToBottom = this.wasScrolledToBottom; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.destroy ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", " + this.context.getName()); }, shouldBreakOnNext: function() { // xxxHonza: shouldn't the breakOnErrors be context related? // xxxJJB, yes, but we can't support it because we can't yet tell // which window the error is on. return Firebug.getPref(Firebug.servicePrefDomain, "breakOnErrors"); }, getBreakOnNextTooltip: function(enabled) { return (enabled ? $STR("console.Disable Break On All Errors") : $STR("console.Break On All Errors")); }, enablePanel: function(module) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.ConsolePanel.enablePanel; " + this.context.getName()); Firebug.ActivablePanel.enablePanel.apply(this, arguments); this.showCommandLine(true); if (this.wasScrolledToBottom) scrollToBottom(this.panelNode); }, disablePanel: function(module) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.ConsolePanel.disablePanel; " + this.context.getName()); Firebug.ActivablePanel.disablePanel.apply(this, arguments); this.showCommandLine(false); }, getOptionsMenuItems: function() { return [ optionMenu("ShowJavaScriptErrors", "showJSErrors"), optionMenu("ShowJavaScriptWarnings", "showJSWarnings"), optionMenu("ShowCSSErrors", "showCSSErrors"), optionMenu("ShowXMLErrors", "showXMLErrors"), optionMenu("ShowXMLHttpRequests", "showXMLHttpRequests"), optionMenu("ShowChromeErrors", "showChromeErrors"), optionMenu("ShowChromeMessages", "showChromeMessages"), optionMenu("ShowExternalErrors", "showExternalErrors"), optionMenu("ShowNetworkErrors", "showNetworkErrors"), this.getShowStackTraceMenuItem(), this.getStrictOptionMenuItem(), "-", optionMenu("LargeCommandLine", "largeCommandLine") ]; }, getShowStackTraceMenuItem: function() { var menuItem = serviceOptionMenu("ShowStackTrace", "showStackTrace"); if (FirebugContext && !Firebug.Debugger.isAlwaysEnabled()) menuItem.disabled = true; return menuItem; }, getStrictOptionMenuItem: function() { var strictDomain = "javascript.options"; var strictName = "strict"; var strictValue = prefs.getBoolPref(strictDomain+"."+strictName); return {label: "JavascriptOptionsStrict", type: "checkbox", checked: strictValue, command: bindFixed(Firebug.setPref, Firebug, strictDomain, strictName, !strictValue) }; }, getBreakOnMenuItems: function() { //xxxHonza: no BON options for now. /*return [ optionMenu("console.option.Persist Break On Error", "persistBreakOnError") ];*/ return []; }, search: function(text) { if (!text) return; // Make previously visible nodes invisible again if (this.matchSet) { for (var i in this.matchSet) removeClass(this.matchSet[i], "matched"); } this.matchSet = []; function findRow(node) { return getAncestorByClass(node, "logRow"); } var search = new TextSearch(this.panelNode, findRow); var logRow = search.find(text); if (!logRow) { dispatch([Firebug.A11yModel], 'onConsoleSearchMatchFound', [this, text, []]); return false; } for (; logRow; logRow = search.findNext()) { setClass(logRow, "matched"); this.matchSet.push(logRow); } dispatch([Firebug.A11yModel], 'onConsoleSearchMatchFound', [this, text, this.matchSet]); return true; }, breakOnNext: function(breaking) { Firebug.setPref(Firebug.servicePrefDomain, "breakOnErrors", breaking); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // private createRow: function(rowName, className) { var elt = this.document.createElement("div"); elt.className = rowName + (className ? " " + rowName + "-" + className : ""); return elt; }, getTopContainer: function() { if (this.groups && this.groups.length) return this.groups[this.groups.length-1]; else return this.panelNode; }, filterLogRow: function(logRow, scrolledToBottom) { if (this.searchText) { setClass(logRow, "matching"); setClass(logRow, "matched"); // Search after a delay because we must wait for a frame to be created for // the new logRow so that the finder will be able to locate it setTimeout(bindFixed(function() { if (this.searchFilter(this.searchText, logRow)) this.matchSet.push(logRow); else removeClass(logRow, "matched"); removeClass(logRow, "matching"); if (scrolledToBottom) scrollToBottom(this.panelNode); }, this), 100); } }, searchFilter: function(text, logRow) { var count = this.panelNode.childNodes.length; var searchRange = this.document.createRange(); searchRange.setStart(this.panelNode, 0); searchRange.setEnd(this.panelNode, count); var startPt = this.document.createRange(); startPt.setStartBefore(logRow); var endPt = this.document.createRange(); endPt.setStartAfter(logRow); return finder.Find(text, searchRange, startPt, endPt) != null; }, // nsIPrefObserver observe: function(subject, topic, data) { // We're observing preferences only. if (topic != "nsPref:changed") return; // xxxHonza check this out. var prefDomain = "Firebug.extension."; var prefName = data.substr(prefDomain.length); if (prefName == "console.logLimit") this.updateMaxLimit(); }, updateMaxLimit: function() { var value = 1000; //TODO: xxxpedro preferences log limit? //var value = Firebug.getPref(Firebug.prefDomain, "console.logLimit"); maxQueueRequests = value ? value : maxQueueRequests; }, showCommandLine: function(shouldShow) { //TODO: xxxpedro show command line important return; if (shouldShow) { collapse(Firebug.chrome.$("fbCommandBox"), false); Firebug.CommandLine.setMultiLine(Firebug.largeCommandLine, Firebug.chrome); } else { // Make sure that entire content of the Console panel is hidden when // the panel is disabled. Firebug.CommandLine.setMultiLine(false, Firebug.chrome, Firebug.largeCommandLine); collapse(Firebug.chrome.$("fbCommandBox"), true); } }, onScroll: function(event) { // Update the scroll position flag if the position changes. this.wasScrolledToBottom = FBL.isScrolledToBottom(this.panelNode); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onScroll ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", wasScrolledToBottom: " + this.context.getName(), event); }, onResize: function(event) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onResize ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", offsetHeight: " + this.panelNode.offsetHeight + ", scrollTop: " + this.panelNode.scrollTop + ", scrollHeight: " + this.panelNode.scrollHeight + ", " + this.context.getName(), event); if (this.wasScrolledToBottom) scrollToBottom(this.panelNode); } }); // ************************************************************************************************ function parseFormat(format) { var parts = []; if (format.length <= 0) return parts; var reg = /((^%|.%)(\d+)?(\.)([a-zA-Z]))|((^%|.%)([a-zA-Z]))/; for (var m = reg.exec(format); m; m = reg.exec(format)) { if (m[0].substr(0, 2) == "%%") { parts.push(format.substr(0, m.index)); parts.push(m[0].substr(1)); } else { var type = m[8] ? m[8] : m[5]; var precision = m[3] ? parseInt(m[3]) : (m[4] == "." ? -1 : 0); var rep = null; switch (type) { case "s": rep = FirebugReps.Text; break; case "f": case "i": case "d": rep = FirebugReps.Number; break; case "o": rep = null; break; } parts.push(format.substr(0, m[0][0] == "%" ? m.index : m.index+1)); parts.push({rep: rep, precision: precision, type: ("%" + type)}); } format = format.substr(m.index+m[0].length); } parts.push(format); return parts; } // ************************************************************************************************ var appendObject = Firebug.ConsolePanel.prototype.appendObject; var appendFormatted = Firebug.ConsolePanel.prototype.appendFormatted; var appendOpenGroup = Firebug.ConsolePanel.prototype.appendOpenGroup; var appendCloseGroup = Firebug.ConsolePanel.prototype.appendCloseGroup; // ************************************************************************************************ //Firebug.registerActivableModule(Firebug.Console); Firebug.registerModule(Firebug.Console); Firebug.registerPanel(Firebug.ConsolePanel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants //const Cc = Components.classes; //const Ci = Components.interfaces; var frameCounters = {}; var traceRecursion = 0; Firebug.Console.injector = { install: function(context) { var win = context.window; var consoleHandler = new FirebugConsoleHandler(context, win); var properties = [ "log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupCollapsed", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd", "clear", "open", "close" ]; var Handler = function(name) { var c = consoleHandler; var f = consoleHandler[name]; return function(){return f.apply(c,arguments);}; }; var installer = function(c) { for (var i=0, l=properties.length; i<l; i++) { var name = properties[i]; c[name] = new Handler(name); c.firebuglite = Firebug.version; } }; var sandbox; if (win.console) { if (Env.Options.overrideConsole) sandbox = new win.Function("arguments.callee.install(window.console={})"); else // if there's a console object and overrideConsole is false we should just quit return; } else { try { // try overriding the console object sandbox = new win.Function("arguments.callee.install(window.console={})"); } catch(E) { // if something goes wrong create the firebug object instead sandbox = new win.Function("arguments.callee.install(window.firebug={})"); } } sandbox.install = installer; sandbox(); }, isAttached: function(context, win) { if (win.wrappedJSObject) { var attached = (win.wrappedJSObject._getFirebugConsoleElement ? true : false); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.isAttached:"+attached+" to win.wrappedJSObject "+safeGetWindowLocation(win.wrappedJSObject)); return attached; } else { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.isAttached? to win "+win.location+" fnc:"+win._getFirebugConsoleElement); return (win._getFirebugConsoleElement ? true : false); } }, attachIfNeeded: function(context, win) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.attachIfNeeded has win "+(win? ((win.wrappedJSObject?"YES":"NO")+" wrappedJSObject"):"null") ); if (this.isAttached(context, win)) return true; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.attachIfNeeded found isAttached false "); this.attachConsoleInjector(context, win); this.addConsoleListener(context, win); Firebug.Console.clearReloadWarning(context); var attached = this.isAttached(context, win); if (attached) dispatch(Firebug.Console.fbListeners, "onConsoleInjected", [context, win]); return attached; }, attachConsoleInjector: function(context, win) { var consoleInjection = this.getConsoleInjectionScript(); // Do it all here. if (FBTrace.DBG_CONSOLE) FBTrace.sysout("attachConsoleInjector evaluating in "+win.location, consoleInjection); Firebug.CommandLine.evaluateInWebPage(consoleInjection, context, win); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("attachConsoleInjector evaluation completed for "+win.location); }, getConsoleInjectionScript: function() { if (!this.consoleInjectionScript) { var script = ""; script += "window.__defineGetter__('console', function() {\n"; script += " return (window._firebug ? window._firebug : window.loadFirebugConsole()); })\n\n"; script += "window.loadFirebugConsole = function() {\n"; script += "window._firebug = new _FirebugConsole();"; if (FBTrace.DBG_CONSOLE) script += " window.dump('loadFirebugConsole '+window.location+'\\n');\n"; script += " return window._firebug };\n"; var theFirebugConsoleScript = getResource("chrome://firebug/content/consoleInjected.js"); script += theFirebugConsoleScript; this.consoleInjectionScript = script; } return this.consoleInjectionScript; }, forceConsoleCompilationInPage: function(context, win) { if (!win) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("no win in forceConsoleCompilationInPage!"); return; } var consoleForcer = "window.loadFirebugConsole();"; if (context.stopped) Firebug.Console.injector.evaluateConsoleScript(context); // todo evaluate consoleForcer on stack else Firebug.CommandLine.evaluateInWebPage(consoleForcer, context, win); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("forceConsoleCompilationInPage "+win.location, consoleForcer); }, evaluateConsoleScript: function(context) { var scriptSource = this.getConsoleInjectionScript(); // TODO XXXjjb this should be getConsoleInjectionScript Firebug.Debugger.evaluate(scriptSource, context); }, addConsoleListener: function(context, win) { if (!context.activeConsoleHandlers) // then we have not been this way before context.activeConsoleHandlers = []; else { // we've been this way before... for (var i=0; i<context.activeConsoleHandlers.length; i++) { if (context.activeConsoleHandlers[i].window == win) { context.activeConsoleHandlers[i].detach(); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector addConsoleListener removed handler("+context.activeConsoleHandlers[i].handler_name+") from _firebugConsole in : "+win.location+"\n"); context.activeConsoleHandlers.splice(i,1); } } } // We need the element to attach our event listener. var element = Firebug.Console.getFirebugConsoleElement(context, win); if (element) element.setAttribute("FirebugVersion", Firebug.version); // Initialize Firebug version. else return false; var handler = new FirebugConsoleHandler(context, win); handler.attachTo(element); context.activeConsoleHandlers.push(handler); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector addConsoleListener attached handler("+handler.handler_name+") to _firebugConsole in : "+win.location+"\n"); return true; }, detachConsole: function(context, win) { if (win && win.document) { var element = win.document.getElementById("_firebugConsole"); if (element) element.parentNode.removeChild(element); } } }; var total_handlers = 0; var FirebugConsoleHandler = function FirebugConsoleHandler(context, win) { this.window = win; this.attachTo = function(element) { this.element = element; // When raised on our injected element, callback to Firebug and append to console this.boundHandler = bind(this.handleEvent, this); this.element.addEventListener('firebugAppendConsole', this.boundHandler, true); // capturing }; this.detach = function() { this.element.removeEventListener('firebugAppendConsole', this.boundHandler, true); }; this.handler_name = ++total_handlers; this.handleEvent = function(event) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("FirebugConsoleHandler("+this.handler_name+") "+event.target.getAttribute("methodName")+", event", event); if (!Firebug.CommandLine.CommandHandler.handle(event, this, win)) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("FirebugConsoleHandler", this); var methodName = event.target.getAttribute("methodName"); Firebug.Console.log($STRF("console.MethodNotSupported", [methodName])); } }; this.firebuglite = Firebug.version; this.init = function() { var consoleElement = win.document.getElementById('_firebugConsole'); consoleElement.setAttribute("FirebugVersion", Firebug.version); }; this.log = function() { logFormatted(arguments, "log"); }; this.debug = function() { logFormatted(arguments, "debug", true); }; this.info = function() { logFormatted(arguments, "info", true); }; this.warn = function() { logFormatted(arguments, "warn", true); }; this.error = function() { //TODO: xxxpedro console error //if (arguments.length == 1) //{ // logAssert("error", arguments); // add more info based on stack trace //} //else //{ //Firebug.Errors.increaseCount(context); logFormatted(arguments, "error", true); // user already added info //} }; this.exception = function() { logAssert("error", arguments); }; this.assert = function(x) { if (!x) { var rest = []; for (var i = 1; i < arguments.length; i++) rest.push(arguments[i]); logAssert("assert", rest); } }; this.dir = function(o) { Firebug.Console.log(o, context, "dir", Firebug.DOMPanel.DirTable); }; this.dirxml = function(o) { ///if (o instanceof Window) if (instanceOf(o, "Window")) o = o.document.documentElement; ///else if (o instanceof Document) else if (instanceOf(o, "Document")) o = o.documentElement; Firebug.Console.log(o, context, "dirxml", Firebug.HTMLPanel.SoloElement); }; this.group = function() { //TODO: xxxpedro; //var sourceLink = getStackLink(); var sourceLink = null; Firebug.Console.openGroup(arguments, null, "group", null, false, sourceLink); }; this.groupEnd = function() { Firebug.Console.closeGroup(context); }; this.groupCollapsed = function() { var sourceLink = getStackLink(); // noThrottle true is probably ok, openGroups will likely be short strings. var row = Firebug.Console.openGroup(arguments, null, "group", null, true, sourceLink); removeClass(row, "opened"); }; this.profile = function(title) { logFormatted(["console.profile() not supported."], "warn", true); //Firebug.Profiler.startProfiling(context, title); }; this.profileEnd = function() { logFormatted(["console.profile() not supported."], "warn", true); //Firebug.Profiler.stopProfiling(context); }; this.count = function(key) { // TODO: xxxpedro console2: is there a better way to find a unique ID for the coun() call? var frameId = "0"; //var frameId = FBL.getStackFrameId(); if (frameId) { if (!frameCounters) frameCounters = {}; if (key != undefined) frameId += key; var frameCounter = frameCounters[frameId]; if (!frameCounter) { var logRow = logFormatted(["0"], null, true, true); frameCounter = {logRow: logRow, count: 1}; frameCounters[frameId] = frameCounter; } else ++frameCounter.count; var label = key == undefined ? frameCounter.count : key + " " + frameCounter.count; frameCounter.logRow.firstChild.firstChild.nodeValue = label; } }; this.trace = function() { var getFuncName = function getFuncName (f) { if (f.getName instanceof Function) { return f.getName(); } if (f.name) // in FireFox, Function objects have a name property... { return f.name; } var name = f.toString().match(/function\s*([_$\w\d]*)/)[1]; return name || "anonymous"; }; var wasVisited = function(fn) { for (var i=0, l=frames.length; i<l; i++) { if (frames[i].fn == fn) { return true; } } return false; }; traceRecursion++; if (traceRecursion > 1) { traceRecursion--; return; } var frames = []; for (var fn = arguments.callee.caller.caller; fn; fn = fn.caller) { if (wasVisited(fn)) break; var args = []; for (var i = 0, l = fn.arguments.length; i < l; ++i) { args.push({value: fn.arguments[i]}); } frames.push({fn: fn, name: getFuncName(fn), args: args}); } // **************************************************************************************** try { (0)(); } catch(e) { var result = e; var stack = result.stack || // Firefox / Google Chrome result.stacktrace || // Opera ""; stack = stack.replace(/\n\r|\r\n/g, "\n"); // normalize line breaks var items = stack.split(/[\n\r]/); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Google Chrome if (FBL.isSafari) { //var reChromeStackItem = /^\s+at\s+([^\(]+)\s\((.*)\)$/; //var reChromeStackItem = /^\s+at\s+(.*)((?:http|https|ftp|file):\/\/.*)$/; var reChromeStackItem = /^\s+at\s+(.*)((?:http|https|ftp|file):\/\/.*)$/; var reChromeStackItemName = /\s*\($/; var reChromeStackItemValue = /^(.+)\:(\d+\:\d+)\)?$/; var framePos = 0; for (var i=4, length=items.length; i<length; i++, framePos++) { var frame = frames[framePos]; var item = items[i]; var match = item.match(reChromeStackItem); //Firebug.Console.log("["+ framePos +"]--------------------------"); //Firebug.Console.log(item); //Firebug.Console.log("................"); if (match) { var name = match[1]; if (name) { name = name.replace(reChromeStackItemName, ""); frame.name = name; } //Firebug.Console.log("name: "+name); var value = match[2].match(reChromeStackItemValue); if (value) { frame.href = value[1]; frame.lineNo = value[2]; //Firebug.Console.log("url: "+value[1]); //Firebug.Console.log("line: "+value[2]); } //else // Firebug.Console.log(match[2]); } } } /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * else if (FBL.isFirefox) { // Firefox var reFirefoxStackItem = /^(.*)@(.*)$/; var reFirefoxStackItemValue = /^(.+)\:(\d+)$/; var framePos = 0; for (var i=2, length=items.length; i<length; i++, framePos++) { var frame = frames[framePos] || {}; var item = items[i]; var match = item.match(reFirefoxStackItem); if (match) { var name = match[1]; //Firebug.Console.logFormatted("name: "+name); var value = match[2].match(reFirefoxStackItemValue); if (value) { frame.href = value[1]; frame.lineNo = value[2]; //Firebug.Console.log("href: "+ value[1]); //Firebug.Console.log("line: " + value[2]); } //else // Firebug.Console.logFormatted([match[2]]); } } } /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* else if (FBL.isOpera) { // Opera var reOperaStackItem = /^\s\s(?:\.\.\.\s\s)?Line\s(\d+)\sof\s(.+)$/; var reOperaStackItemValue = /^linked\sscript\s(.+)$/; for (var i=0, length=items.length; i<length; i+=2) { var item = items[i]; var match = item.match(reOperaStackItem); if (match) { //Firebug.Console.log(match[1]); var value = match[2].match(reOperaStackItemValue); if (value) { //Firebug.Console.log(value[1]); } //else // Firebug.Console.log(match[2]); //Firebug.Console.log("--------------------------"); } } } /**/ } //console.log(stack); //console.dir(frames); Firebug.Console.log({frames: frames}, context, "stackTrace", FirebugReps.StackTrace); traceRecursion--; }; this.trace_ok = function() { var getFuncName = function getFuncName (f) { if (f.getName instanceof Function) return f.getName(); if (f.name) // in FireFox, Function objects have a name property... return f.name; var name = f.toString().match(/function\s*([_$\w\d]*)/)[1]; return name || "anonymous"; }; var wasVisited = function(fn) { for (var i=0, l=frames.length; i<l; i++) { if (frames[i].fn == fn) return true; } return false; }; var frames = []; for (var fn = arguments.callee.caller; fn; fn = fn.caller) { if (wasVisited(fn)) break; var args = []; for (var i = 0, l = fn.arguments.length; i < l; ++i) { args.push({value: fn.arguments[i]}); } frames.push({fn: fn, name: getFuncName(fn), args: args}); } Firebug.Console.log({frames: frames}, context, "stackTrace", FirebugReps.StackTrace); }; this.clear = function() { Firebug.Console.clear(context); }; this.time = function(name, reset) { if (!name) return; var time = new Date().getTime(); if (!this.timeCounters) this.timeCounters = {}; var key = "KEY"+name.toString(); if (!reset && this.timeCounters[key]) return; this.timeCounters[key] = time; }; this.timeEnd = function(name) { var time = new Date().getTime(); if (!this.timeCounters) return; var key = "KEY"+name.toString(); var timeCounter = this.timeCounters[key]; if (timeCounter) { var diff = time - timeCounter; var label = name + ": " + diff + "ms"; this.info(label); delete this.timeCounters[key]; } return diff; }; // These functions are over-ridden by commandLine this.evaluated = function(result, context) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector.FirebugConsoleHandler evalutated default called", result); Firebug.Console.log(result, context); }; this.evaluateError = function(result, context) { Firebug.Console.log(result, context, "errorMessage"); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * function logFormatted(args, className, linkToSource, noThrottle) { var sourceLink = linkToSource ? getStackLink() : null; return Firebug.Console.logFormatted(args, context, className, noThrottle, sourceLink); } function logAssert(category, args) { Firebug.Errors.increaseCount(context); if (!args || !args.length || args.length == 0) var msg = [FBL.$STR("Assertion")]; else var msg = args[0]; if (Firebug.errorStackTrace) { var trace = Firebug.errorStackTrace; delete Firebug.errorStackTrace; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("logAssert trace from errorStackTrace", trace); } else if (msg.stack) { var trace = parseToStackTrace(msg.stack); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("logAssert trace from msg.stack", trace); } else { var trace = getJSDUserStack(); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("logAssert trace from getJSDUserStack", trace); } var errorObject = new FBL.ErrorMessage(msg, (msg.fileName?msg.fileName:win.location), (msg.lineNumber?msg.lineNumber:0), "", category, context, trace); if (trace && trace.frames && trace.frames[0]) errorObject.correctWithStackTrace(trace); errorObject.resetSource(); var objects = errorObject; if (args.length > 1) { objects = [errorObject]; for (var i = 1; i < args.length; i++) objects.push(args[i]); } var row = Firebug.Console.log(objects, context, "errorMessage", null, true); // noThrottle row.scrollIntoView(); } function getComponentsStackDump() { // Starting with our stack, walk back to the user-level code var frame = Components.stack; var userURL = win.location.href.toString(); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector.getComponentsStackDump initial stack for userURL "+userURL, frame); // Drop frames until we get into user code. while (frame && FBL.isSystemURL(frame.filename) ) frame = frame.caller; // Drop two more frames, the injected console function and firebugAppendConsole() if (frame) frame = frame.caller; if (frame) frame = frame.caller; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector.getComponentsStackDump final stack for userURL "+userURL, frame); return frame; } function getStackLink() { // TODO: xxxpedro console2 return; //return FBL.getFrameSourceLink(getComponentsStackDump()); } function getJSDUserStack() { var trace = FBL.getCurrentStackTrace(context); var frames = trace ? trace.frames : null; if (frames && (frames.length > 0) ) { var oldest = frames.length - 1; // 6 - 1 = 5 for (var i = 0; i < frames.length; i++) { if (frames[oldest - i].href.indexOf("chrome:") == 0) break; var fn = frames[oldest - i].fn + ""; if (fn && (fn.indexOf("_firebugEvalEvent") != -1) ) break; // command line } FBTrace.sysout("consoleInjector getJSDUserStack: "+frames.length+" oldest: "+oldest+" i: "+i+" i - oldest + 2: "+(i - oldest + 2), trace); trace.frames = trace.frames.slice(2 - i); // take the oldest frames, leave 2 behind they are injection code return trace; } else return "Firebug failed to get stack trace with any frames"; } }; // ************************************************************************************************ // Register console namespace FBL.registerConsole = function() { var win = Env.browser.window; Firebug.Console.injector.install(win); }; registerConsole(); }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals var commandPrefix = ">>>"; var reOpenBracket = /[\[\(\{]/; var reCloseBracket = /[\]\)\}]/; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var commandHistory = []; var commandPointer = -1; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var isAutoCompleting = null; var autoCompletePrefix = null; var autoCompleteExpr = null; var autoCompleteBuffer = null; var autoCompletePosition = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var fbCommandLine = null; var fbLargeCommandLine = null; var fbLargeCommandButtons = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var _completion = { window: [ "console" ], document: [ "getElementById", "getElementsByTagName" ] }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var _stack = function(command) { Firebug.context.persistedState.commandHistory.push(command); Firebug.context.persistedState.commandPointer = Firebug.context.persistedState.commandHistory.length; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ************************************************************************************************ // CommandLine Firebug.CommandLine = extend(Firebug.Module, { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * element: null, isMultiLine: false, isActive: false, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * initialize: function(doc) { this.clear = bind(this.clear, this); this.enter = bind(this.enter, this); this.onError = bind(this.onError, this); this.onKeyDown = bind(this.onKeyDown, this); this.onMultiLineKeyDown = bind(this.onMultiLineKeyDown, this); addEvent(Firebug.browser.window, "error", this.onError); addEvent(Firebug.chrome.window, "error", this.onError); }, shutdown: function(doc) { this.deactivate(); removeEvent(Firebug.browser.window, "error", this.onError); removeEvent(Firebug.chrome.window, "error", this.onError); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * activate: function(multiLine, hideToggleIcon, onRun) { defineCommandLineAPI(); Firebug.context.persistedState.commandHistory = Firebug.context.persistedState.commandHistory || []; Firebug.context.persistedState.commandPointer = Firebug.context.persistedState.commandPointer || -1; if (this.isActive) { if (this.isMultiLine == multiLine) return; this.deactivate(); } fbCommandLine = $("fbCommandLine"); fbLargeCommandLine = $("fbLargeCommandLine"); fbLargeCommandButtons = $("fbLargeCommandButtons"); if (multiLine) { onRun = onRun || this.enter; this.isMultiLine = true; this.element = fbLargeCommandLine; addEvent(this.element, "keydown", this.onMultiLineKeyDown); addEvent($("fbSmallCommandLineIcon"), "click", Firebug.chrome.hideLargeCommandLine); this.runButton = new Button({ element: $("fbCommand_btRun"), owner: Firebug.CommandLine, onClick: onRun }); this.runButton.initialize(); this.clearButton = new Button({ element: $("fbCommand_btClear"), owner: Firebug.CommandLine, onClick: this.clear }); this.clearButton.initialize(); } else { this.isMultiLine = false; this.element = fbCommandLine; if (!fbCommandLine) return; addEvent(this.element, "keydown", this.onKeyDown); } //Firebug.Console.log("activate", this.element); if (isOpera) fixOperaTabKey(this.element); if(this.lastValue) this.element.value = this.lastValue; this.isActive = true; }, deactivate: function() { if (!this.isActive) return; //Firebug.Console.log("deactivate", this.element); this.isActive = false; this.lastValue = this.element.value; if (this.isMultiLine) { removeEvent(this.element, "keydown", this.onMultiLineKeyDown); removeEvent($("fbSmallCommandLineIcon"), "click", Firebug.chrome.hideLargeCommandLine); this.runButton.destroy(); this.clearButton.destroy(); } else { removeEvent(this.element, "keydown", this.onKeyDown); } this.element = null; delete this.element; fbCommandLine = null; fbLargeCommandLine = null; fbLargeCommandButtons = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * focus: function() { this.element.focus(); }, blur: function() { this.element.blur(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * clear: function() { this.element.value = ""; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * evaluate: function(expr) { // TODO: need to register the API in console.firebug.commandLineAPI var api = "Firebug.CommandLine.API"; var result = Firebug.context.evaluate(expr, "window", api, Firebug.Console.error); return result; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * enter: function() { var command = this.element.value; if (!command) return; _stack(command); Firebug.Console.log(commandPrefix + " " + stripNewLines(command), Firebug.browser, "command", FirebugReps.Text); var result = this.evaluate(command); Firebug.Console.log(result); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * prevCommand: function() { if (Firebug.context.persistedState.commandPointer > 0 && Firebug.context.persistedState.commandHistory.length > 0) { this.element.value = Firebug.context.persistedState.commandHistory [--Firebug.context.persistedState.commandPointer]; } }, nextCommand: function() { var element = this.element; var limit = Firebug.context.persistedState.commandHistory.length -1; var i = Firebug.context.persistedState.commandPointer; if (i < limit) element.value = Firebug.context.persistedState.commandHistory [++Firebug.context.persistedState.commandPointer]; else if (i == limit) { ++Firebug.context.persistedState.commandPointer; element.value = ""; } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * autocomplete: function(reverse) { var element = this.element; var command = element.value; var offset = getExpressionOffset(command); var valBegin = offset ? command.substr(0, offset) : ""; var val = command.substr(offset); var buffer, obj, objName, commandBegin, result, prefix; // if it is the beginning of the completion if(!isAutoCompleting) { // group1 - command begin // group2 - base object // group3 - property prefix var reObj = /(.*[^_$\w\d\.])?((?:[_$\w][_$\w\d]*\.)*)([_$\w][_$\w\d]*)?$/; var r = reObj.exec(val); // parse command if (r[1] || r[2] || r[3]) { commandBegin = r[1] || ""; objName = r[2] || ""; prefix = r[3] || ""; } else if (val == "") { commandBegin = objName = prefix = ""; } else return; isAutoCompleting = true; // find base object if(objName == "") obj = window; else { objName = objName.replace(/\.$/, ""); var n = objName.split("."); var target = window, o; for (var i=0, ni; ni = n[i]; i++) { if (o = target[ni]) target = o; else { target = null; break; } } obj = target; } // map base object if(obj) { autoCompletePrefix = prefix; autoCompleteExpr = valBegin + commandBegin + (objName ? objName + "." : ""); autoCompletePosition = -1; buffer = autoCompleteBuffer = isIE ? _completion[objName || "window"] || [] : []; for(var p in obj) buffer.push(p); } // if it is the continuation of the last completion } else buffer = autoCompleteBuffer; if (buffer) { prefix = autoCompletePrefix; var diff = reverse ? -1 : 1; for(var i=autoCompletePosition+diff, l=buffer.length, bi; i>=0 && i<l; i+=diff) { bi = buffer[i]; if (bi.indexOf(prefix) == 0) { autoCompletePosition = i; result = bi; break; } } } if (result) element.value = autoCompleteExpr + result; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * setMultiLine: function(multiLine) { if (multiLine == this.isMultiLine) return; this.activate(multiLine); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onError: function(msg, href, lineNo) { href = href || ""; var lastSlash = href.lastIndexOf("/"); var fileName = lastSlash == -1 ? href : href.substr(lastSlash+1); var html = [ '<span class="errorMessage">', msg, '</span>', '<div class="objectBox-sourceLink">', fileName, ' (line ', lineNo, ')</div>' ]; // TODO: xxxpedro ajust to Console2 //Firebug.Console.writeRow(html, "error"); }, onKeyDown: function(e) { e = e || event; var code = e.keyCode; /*tab, shift, control, alt*/ if (code != 9 && code != 16 && code != 17 && code != 18) { isAutoCompleting = false; } if (code == 13 /* enter */) { this.enter(); this.clear(); } else if (code == 27 /* ESC */) { setTimeout(this.clear, 0); } else if (code == 38 /* up */) { this.prevCommand(); } else if (code == 40 /* down */) { this.nextCommand(); } else if (code == 9 /* tab */) { this.autocomplete(e.shiftKey); } else return; cancelEvent(e, true); return false; }, onMultiLineKeyDown: function(e) { e = e || event; var code = e.keyCode; if (code == 13 /* enter */ && e.ctrlKey) { this.enter(); } } }); Firebug.registerModule(Firebug.CommandLine); // ************************************************************************************************ // function getExpressionOffset(command) { // XXXjoe This is kind of a poor-man's JavaScript parser - trying // to find the start of the expression that the cursor is inside. // Not 100% fool proof, but hey... var bracketCount = 0; var start = command.length-1; for (; start >= 0; --start) { var c = command[start]; if ((c == "," || c == ";" || c == " ") && !bracketCount) break; if (reOpenBracket.test(c)) { if (bracketCount) --bracketCount; else break; } else if (reCloseBracket.test(c)) ++bracketCount; } return start + 1; } // ************************************************************************************************ // CommandLine API var CommandLineAPI = { $: function(id) { return Firebug.browser.document.getElementById(id); }, $$: function(selector, context) { context = context || Firebug.browser.document; return Firebug.Selector ? Firebug.Selector(selector, context) : Firebug.Console.error("Firebug.Selector module not loaded."); }, $0: null, $1: null, dir: function(o) { Firebug.Console.log(o, Firebug.context, "dir", Firebug.DOMPanel.DirTable); }, dirxml: function(o) { ///if (o instanceof Window) if (instanceOf(o, "Window")) o = o.document.documentElement; ///else if (o instanceof Document) else if (instanceOf(o, "Document")) o = o.documentElement; Firebug.Console.log(o, Firebug.context, "dirxml", Firebug.HTMLPanel.SoloElement); } }; // ************************************************************************************************ var defineCommandLineAPI = function defineCommandLineAPI() { Firebug.CommandLine.API = {}; for (var m in CommandLineAPI) if (!Env.browser.window[m]) Firebug.CommandLine.API[m] = CommandLineAPI[m]; var stack = FirebugChrome.htmlSelectionStack; if (stack) { Firebug.CommandLine.API.$0 = stack[0]; Firebug.CommandLine.API.$1 = stack[1]; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals var ElementCache = Firebug.Lite.Cache.Element; var cacheID = Firebug.Lite.Cache.ID; var ignoreHTMLProps = { // ignores the attributes injected by Sizzle, otherwise it will // be visible on IE (when enumerating element.attributes) sizcache: 1, sizset: 1 }; if (Firebug.ignoreFirebugElements) // ignores also the cache property injected by firebug ignoreHTMLProps[cacheID] = 1; // ************************************************************************************************ // HTML Module Firebug.HTML = extend(Firebug.Module, { appendTreeNode: function(nodeArray, html) { var reTrim = /^\s+|\s+$/g; if (!nodeArray.length) nodeArray = [nodeArray]; for (var n=0, node; node=nodeArray[n]; n++) { if (node.nodeType == 1) { if (Firebug.ignoreFirebugElements && node.firebugIgnore) continue; var uid = ElementCache(node); var child = node.childNodes; var childLength = child.length; var nodeName = node.nodeName.toLowerCase(); var nodeVisible = isVisible(node); var hasSingleTextChild = childLength == 1 && node.firstChild.nodeType == 3 && nodeName != "script" && nodeName != "style"; var nodeControl = !hasSingleTextChild && childLength > 0 ? ('<div class="nodeControl"></div>') : ''; // FIXME xxxpedro remove this //var isIE = false; if(isIE && nodeControl) html.push(nodeControl); if (typeof uid != 'undefined') html.push( '<div class="objectBox-element" ', 'id="', uid, '">', !isIE && nodeControl ? nodeControl: "", '<span ', cacheID, '="', uid, '" class="nodeBox', nodeVisible ? "" : " nodeHidden", '">&lt;<span class="nodeTag">', nodeName, '</span>' ); else html.push( '<div class="objectBox-element"><span class="nodeBox', nodeVisible ? "" : " nodeHidden", '">&lt;<span class="nodeTag">', nodeName, '</span>' ); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified || // Issue 4432: Firebug Lite: HTML is mixed-up with functions // The problem here is that expando properties added to DOM elements in // IE < 9 will behave like DOM attributes and so they'll show up when // looking at element.attributes list. isIE && (browserVersion-0<9) && typeof attr.nodeValue != "string" || Firebug.ignoreFirebugElements && ignoreHTMLProps.hasOwnProperty(attr.nodeName)) continue; var name = attr.nodeName.toLowerCase(); var value = name == "style" ? formatStyles(node.style.cssText) : attr.nodeValue; html.push('&nbsp;<span class="nodeName">', name, '</span>=&quot;<span class="nodeValue">', escapeHTML(value), '</span>&quot;'); } /* // source code nodes if (nodeName == 'script' || nodeName == 'style') { if(document.all){ var src = node.innerHTML+'\n'; }else { var src = '\n'+node.innerHTML+'\n'; } var match = src.match(/\n/g); var num = match ? match.length : 0; var s = [], sl = 0; for(var c=1; c<num; c++){ s[sl++] = '<div line="'+c+'">' + c + '</div>'; } html.push('&gt;</div><div class="nodeGroup"><div class="nodeChildren"><div class="lineNo">', s.join(''), '</div><pre class="nodeCode">', escapeHTML(src), '</pre>', '</div><div class="objectBox-element">&lt;/<span class="nodeTag">', nodeName, '</span>&gt;</div>', '</div>' ); }/**/ // Just a single text node child if (hasSingleTextChild) { var value = child[0].nodeValue.replace(reTrim, ''); if(value) { html.push( '&gt;<span class="nodeText">', escapeHTML(value), '</span>&lt;/<span class="nodeTag">', nodeName, '</span>&gt;</span></div>' ); } else html.push('/&gt;</span></div>'); // blank text, print as childless node } else if (childLength > 0) { html.push('&gt;</span></div>'); } else html.push('/&gt;</span></div>'); } else if (node.nodeType == 3) { if ( node.parentNode && ( node.parentNode.nodeName.toLowerCase() == "script" || node.parentNode.nodeName.toLowerCase() == "style" ) ) { var value = node.nodeValue.replace(reTrim, ''); if(isIE){ var src = value+'\n'; }else { var src = '\n'+value+'\n'; } var match = src.match(/\n/g); var num = match ? match.length : 0; var s = [], sl = 0; for(var c=1; c<num; c++){ s[sl++] = '<div line="'+c+'">' + c + '</div>'; } html.push('<div class="lineNo">', s.join(''), '</div><pre class="sourceCode">', escapeHTML(src), '</pre>' ); } else { var value = node.nodeValue.replace(reTrim, ''); if (value) html.push('<div class="nodeText">', escapeHTML(value),'</div>'); } } } }, appendTreeChildren: function(treeNode) { var doc = Firebug.chrome.document; var uid = treeNode.id; var parentNode = ElementCache.get(uid); if (parentNode.childNodes.length == 0) return; var treeNext = treeNode.nextSibling; var treeParent = treeNode.parentNode; // FIXME xxxpedro remove this //var isIE = false; var control = isIE ? treeNode.previousSibling : treeNode.firstChild; control.className = 'nodeControl nodeMaximized'; var html = []; var children = doc.createElement("div"); children.className = "nodeChildren"; this.appendTreeNode(parentNode.childNodes, html); children.innerHTML = html.join(""); treeParent.insertBefore(children, treeNext); var closeElement = doc.createElement("div"); closeElement.className = "objectBox-element"; closeElement.innerHTML = '&lt;/<span class="nodeTag">' + parentNode.nodeName.toLowerCase() + '&gt;</span>'; treeParent.insertBefore(closeElement, treeNext); }, removeTreeChildren: function(treeNode) { var children = treeNode.nextSibling; var closeTag = children.nextSibling; // FIXME xxxpedro remove this //var isIE = false; var control = isIE ? treeNode.previousSibling : treeNode.firstChild; control.className = 'nodeControl'; children.parentNode.removeChild(children); closeTag.parentNode.removeChild(closeTag); }, isTreeNodeVisible: function(id) { return $(id); }, select: function(el) { var id = el && ElementCache(el); if (id) this.selectTreeNode(id); }, selectTreeNode: function(id) { id = ""+id; var node, stack = []; while(id && !this.isTreeNodeVisible(id)) { stack.push(id); var node = ElementCache.get(id).parentNode; if (node) id = ElementCache(node); else break; } stack.push(id); while(stack.length > 0) { id = stack.pop(); node = $(id); if (stack.length > 0 && ElementCache.get(id).childNodes.length > 0) this.appendTreeChildren(node); } selectElement(node); // TODO: xxxpedro if (fbPanel1) fbPanel1.scrollTop = Math.round(node.offsetTop - fbPanel1.clientHeight/2); } }); Firebug.registerModule(Firebug.HTML); // ************************************************************************************************ // HTML Panel function HTMLPanel(){}; HTMLPanel.prototype = extend(Firebug.Panel, { name: "HTML", title: "HTML", options: { hasSidePanel: true, //hasToolButtons: true, isPreRendered: !Firebug.flexChromeEnabled /* FIXME xxxpedro chromenew */, innerHTMLSync: true }, create: function(){ Firebug.Panel.create.apply(this, arguments); this.panelNode.style.padding = "4px 3px 1px 15px"; this.panelNode.style.minWidth = "500px"; if (Env.Options.enablePersistent || Firebug.chrome.type != "popup") this.createUI(); if(this.sidePanelBar && !this.sidePanelBar.selectedPanel) { this.sidePanelBar.selectPanel("css"); } }, destroy: function() { selectedElement = null; fbPanel1 = null; selectedSidePanelTS = null; selectedSidePanelTimer = null; Firebug.Panel.destroy.apply(this, arguments); }, createUI: function() { var rootNode = Firebug.browser.document.documentElement; var html = []; Firebug.HTML.appendTreeNode(rootNode, html); this.panelNode.innerHTML = html.join(""); }, initialize: function() { Firebug.Panel.initialize.apply(this, arguments); addEvent(this.panelNode, 'click', Firebug.HTML.onTreeClick); fbPanel1 = $("fbPanel1"); if(!selectedElement) { Firebug.context.persistedState.selectedHTMLElementId = Firebug.context.persistedState.selectedHTMLElementId && ElementCache.get(Firebug.context.persistedState.selectedHTMLElementId) ? Firebug.context.persistedState.selectedHTMLElementId : ElementCache(Firebug.browser.document.body); Firebug.HTML.selectTreeNode(Firebug.context.persistedState.selectedHTMLElementId); } // TODO: xxxpedro addEvent(fbPanel1, 'mousemove', Firebug.HTML.onListMouseMove); addEvent($("fbContent"), 'mouseout', Firebug.HTML.onListMouseMove); addEvent(Firebug.chrome.node, 'mouseout', Firebug.HTML.onListMouseMove); }, shutdown: function() { // TODO: xxxpedro removeEvent(fbPanel1, 'mousemove', Firebug.HTML.onListMouseMove); removeEvent($("fbContent"), 'mouseout', Firebug.HTML.onListMouseMove); removeEvent(Firebug.chrome.node, 'mouseout', Firebug.HTML.onListMouseMove); removeEvent(this.panelNode, 'click', Firebug.HTML.onTreeClick); fbPanel1 = null; Firebug.Panel.shutdown.apply(this, arguments); }, reattach: function() { // TODO: panel reattach if(Firebug.context.persistedState.selectedHTMLElementId) Firebug.HTML.selectTreeNode(Firebug.context.persistedState.selectedHTMLElementId); }, updateSelection: function(object) { var id = ElementCache(object); if (id) { Firebug.HTML.selectTreeNode(id); } } }); Firebug.registerPanel(HTMLPanel); // ************************************************************************************************ var formatStyles = function(styles) { return isIE ? // IE return CSS property names in upper case, so we need to convert them styles.replace(/([^\s]+)\s*:/g, function(m,g){return g.toLowerCase()+":";}) : // other browsers are just fine styles; }; // ************************************************************************************************ var selectedElement = null; var fbPanel1 = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var selectedSidePanelTS, selectedSidePanelTimer; var selectElement= function selectElement(e) { if (e != selectedElement) { if (selectedElement) selectedElement.className = "objectBox-element"; e.className = e.className + " selectedElement"; if (FBL.isFirefox) e.style.MozBorderRadius = "2px"; else if (FBL.isSafari) e.style.WebkitBorderRadius = "2px"; e.style.borderRadius = "2px"; selectedElement = e; Firebug.context.persistedState.selectedHTMLElementId = e.id; var target = ElementCache.get(e.id); var sidePanelBar = Firebug.chrome.getPanel("HTML").sidePanelBar; var selectedSidePanel = sidePanelBar ? sidePanelBar.selectedPanel : null; var stack = FirebugChrome.htmlSelectionStack; stack.unshift(target); if (stack.length > 2) stack.pop(); var lazySelect = function() { selectedSidePanelTS = new Date().getTime(); if (selectedSidePanel) selectedSidePanel.select(target, true); }; if (selectedSidePanelTimer) { clearTimeout(selectedSidePanelTimer); selectedSidePanelTimer = null; } if (new Date().getTime() - selectedSidePanelTS > 100) setTimeout(lazySelect, 0); else selectedSidePanelTimer = setTimeout(lazySelect, 150); } }; // ************************************************************************************************ // *** TODO: REFACTOR ************************************************************************** // ************************************************************************************************ Firebug.HTML.onTreeClick = function (e) { e = e || event; var targ; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; if (targ.className.indexOf('nodeControl') != -1 || targ.className == 'nodeTag') { // FIXME xxxpedro remove this //var isIE = false; if(targ.className == 'nodeTag') { var control = isIE ? (targ.parentNode.previousSibling || targ) : (targ.parentNode.previousSibling || targ); selectElement(targ.parentNode.parentNode); if (control.className.indexOf('nodeControl') == -1) return; } else control = targ; FBL.cancelEvent(e); var treeNode = isIE ? control.nextSibling : control.parentNode; //FBL.Firebug.Console.log(treeNode); if (control.className.indexOf(' nodeMaximized') != -1) { FBL.Firebug.HTML.removeTreeChildren(treeNode); } else { FBL.Firebug.HTML.appendTreeChildren(treeNode); } } else if (targ.className == 'nodeValue' || targ.className == 'nodeName') { /* var input = FBL.Firebug.chrome.document.getElementById('treeInput'); input.style.display = "block"; input.style.left = targ.offsetLeft + 'px'; input.style.top = FBL.topHeight + targ.offsetTop - FBL.fbPanel1.scrollTop + 'px'; input.style.width = targ.offsetWidth + 6 + 'px'; input.value = targ.textContent || targ.innerText; input.focus(); /**/ } }; function onListMouseOut(e) { e = e || event || window; var targ; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; if (hasClass(targ, "fbPanel")) { FBL.Firebug.Inspector.hideBoxModel(); hoverElement = null; } }; var hoverElement = null; var hoverElementTS = 0; Firebug.HTML.onListMouseMove = function onListMouseMove(e) { try { e = e || event || window; var targ; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; var found = false; while (targ && !found) { if (!/\snodeBox\s|\sobjectBox-selector\s/.test(" " + targ.className + " ")) targ = targ.parentNode; else found = true; } if (!targ) { FBL.Firebug.Inspector.hideBoxModel(); hoverElement = null; return; } /* if (typeof targ.attributes[cacheID] == 'undefined') return; var uid = targ.attributes[cacheID]; if (!uid) return; /**/ if (typeof targ.attributes[cacheID] == 'undefined') return; var uid = targ.attributes[cacheID]; if (!uid) return; var el = ElementCache.get(uid.value); var nodeName = el.nodeName.toLowerCase(); if (FBL.isIE && " meta title script link ".indexOf(" "+nodeName+" ") != -1) return; if (!/\snodeBox\s|\sobjectBox-selector\s/.test(" " + targ.className + " ")) return; if (el.id == "FirebugUI" || " html head body br script link iframe ".indexOf(" "+nodeName+" ") != -1) { FBL.Firebug.Inspector.hideBoxModel(); hoverElement = null; return; } if ((new Date().getTime() - hoverElementTS > 40) && hoverElement != el) { hoverElementTS = new Date().getTime(); hoverElement = el; FBL.Firebug.Inspector.drawBoxModel(el); } } catch(E) { } }; // ************************************************************************************************ Firebug.Reps = { appendText: function(object, html) { html.push(escapeHTML(objectToString(object))); }, appendNull: function(object, html) { html.push('<span class="objectBox-null">', escapeHTML(objectToString(object)), '</span>'); }, appendString: function(object, html) { html.push('<span class="objectBox-string">&quot;', escapeHTML(objectToString(object)), '&quot;</span>'); }, appendInteger: function(object, html) { html.push('<span class="objectBox-number">', escapeHTML(objectToString(object)), '</span>'); }, appendFloat: function(object, html) { html.push('<span class="objectBox-number">', escapeHTML(objectToString(object)), '</span>'); }, appendFunction: function(object, html) { var reName = /function ?(.*?)\(/; var m = reName.exec(objectToString(object)); var name = m && m[1] ? m[1] : "function"; html.push('<span class="objectBox-function">', escapeHTML(name), '()</span>'); }, appendObject: function(object, html) { /* var rep = Firebug.getRep(object); var outputs = []; rep.tag.tag.compile(); var str = rep.tag.renderHTML({object: object}, outputs); html.push(str); /**/ try { if (object == undefined) this.appendNull("undefined", html); else if (object == null) this.appendNull("null", html); else if (typeof object == "string") this.appendString(object, html); else if (typeof object == "number") this.appendInteger(object, html); else if (typeof object == "boolean") this.appendInteger(object, html); else if (typeof object == "function") this.appendFunction(object, html); else if (object.nodeType == 1) this.appendSelector(object, html); else if (typeof object == "object") { if (typeof object.length != "undefined") this.appendArray(object, html); else this.appendObjectFormatted(object, html); } else this.appendText(object, html); } catch (exc) { } /**/ }, appendObjectFormatted: function(object, html) { var text = objectToString(object); var reObject = /\[object (.*?)\]/; var m = reObject.exec(text); html.push('<span class="objectBox-object">', m ? m[1] : text, '</span>'); }, appendSelector: function(object, html) { var uid = ElementCache(object); var uidString = uid ? [cacheID, '="', uid, '"'].join("") : ""; html.push('<span class="objectBox-selector"', uidString, '>'); html.push('<span class="selectorTag">', escapeHTML(object.nodeName.toLowerCase()), '</span>'); if (object.id) html.push('<span class="selectorId">#', escapeHTML(object.id), '</span>'); if (object.className) html.push('<span class="selectorClass">.', escapeHTML(object.className), '</span>'); html.push('</span>'); }, appendNode: function(node, html) { if (node.nodeType == 1) { var uid = ElementCache(node); var uidString = uid ? [cacheID, '="', uid, '"'].join("") : ""; html.push( '<div class="objectBox-element"', uidString, '">', '<span ', cacheID, '="', uid, '" class="nodeBox">', '&lt;<span class="nodeTag">', node.nodeName.toLowerCase(), '</span>'); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified || attr.nodeName == cacheID) continue; var name = attr.nodeName.toLowerCase(); var value = name == "style" ? node.style.cssText : attr.nodeValue; html.push('&nbsp;<span class="nodeName">', name, '</span>=&quot;<span class="nodeValue">', escapeHTML(value), '</span>&quot;'); } if (node.firstChild) { html.push('&gt;</div><div class="nodeChildren">'); for (var child = node.firstChild; child; child = child.nextSibling) this.appendNode(child, html); html.push('</div><div class="objectBox-element">&lt;/<span class="nodeTag">', node.nodeName.toLowerCase(), '&gt;</span></span></div>'); } else html.push('/&gt;</span></div>'); } else if (node.nodeType == 3) { var value = trim(node.nodeValue); if (value) html.push('<div class="nodeText">', escapeHTML(value),'</div>'); } }, appendArray: function(object, html) { html.push('<span class="objectBox-array"><b>[</b> '); for (var i = 0, l = object.length, obj; i < l; ++i) { this.appendObject(object[i], html); if (i < l-1) html.push(', '); } html.push(' <b>]</b></span>'); } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ /* Hack: Firebug.chrome.currentPanel = Firebug.chrome.selectedPanel; Firebug.showInfoTips = true; Firebug.InfoTip.initializeBrowser(Firebug.chrome); /**/ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants var maxWidth = 100, maxHeight = 80; var infoTipMargin = 10; var infoTipWindowPadding = 25; // ************************************************************************************************ Firebug.InfoTip = extend(Firebug.Module, { dispatchName: "infoTip", tags: domplate( { infoTipTag: DIV({"class": "infoTip"}), colorTag: DIV({style: "background: $rgbValue; width: 100px; height: 40px"}, "&nbsp;"), imgTag: DIV({"class": "infoTipImageBox infoTipLoading"}, IMG({"class": "infoTipImage", src: "$urlValue", repeat: "$repeat", onload: "$onLoadImage"}), IMG({"class": "infoTipBgImage", collapsed: true, src: "blank.gif"}), DIV({"class": "infoTipCaption"}) ), onLoadImage: function(event) { var img = event.currentTarget || event.srcElement; ///var bgImg = img.nextSibling; ///if (!bgImg) /// return; // Sometimes gets called after element is dead ///var caption = bgImg.nextSibling; var innerBox = img.parentNode; /// TODO: xxxpedro infoTip hack var caption = getElementByClass(innerBox, "infoTipCaption"); var bgImg = getElementByClass(innerBox, "infoTipBgImage"); if (!bgImg) return; // Sometimes gets called after element is dead // TODO: xxxpedro infoTip IE and timing issue // TODO: use offline document to avoid flickering if (isIE) removeClass(innerBox, "infoTipLoading"); var updateInfoTip = function(){ var w = img.naturalWidth || img.width || 10, h = img.naturalHeight || img.height || 10; var repeat = img.getAttribute("repeat"); if (repeat == "repeat-x" || (w == 1 && h > 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat-x"; bgImg.style.width = maxWidth + "px"; if (h > maxHeight) bgImg.style.height = maxHeight + "px"; else bgImg.style.height = h + "px"; } else if (repeat == "repeat-y" || (h == 1 && w > 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat-y"; bgImg.style.height = maxHeight + "px"; if (w > maxWidth) bgImg.style.width = maxWidth + "px"; else bgImg.style.width = w + "px"; } else if (repeat == "repeat" || (w == 1 && h == 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat"; bgImg.style.width = maxWidth + "px"; bgImg.style.height = maxHeight + "px"; } else { if (w > maxWidth || h > maxHeight) { if (w > h) { img.style.width = maxWidth + "px"; img.style.height = Math.round((h / w) * maxWidth) + "px"; } else { img.style.width = Math.round((w / h) * maxHeight) + "px"; img.style.height = maxHeight + "px"; } } } //caption.innerHTML = $STRF("Dimensions", [w, h]); caption.innerHTML = $STRF(w + " x " + h); }; if (isIE) setTimeout(updateInfoTip, 0); else { updateInfoTip(); removeClass(innerBox, "infoTipLoading"); } /// } /* /// onLoadImage original onLoadImage: function(event) { var img = event.currentTarget; var bgImg = img.nextSibling; if (!bgImg) return; // Sometimes gets called after element is dead var caption = bgImg.nextSibling; var innerBox = img.parentNode; var w = img.naturalWidth, h = img.naturalHeight; var repeat = img.getAttribute("repeat"); if (repeat == "repeat-x" || (w == 1 && h > 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat-x"; bgImg.style.width = maxWidth + "px"; if (h > maxHeight) bgImg.style.height = maxHeight + "px"; else bgImg.style.height = h + "px"; } else if (repeat == "repeat-y" || (h == 1 && w > 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat-y"; bgImg.style.height = maxHeight + "px"; if (w > maxWidth) bgImg.style.width = maxWidth + "px"; else bgImg.style.width = w + "px"; } else if (repeat == "repeat" || (w == 1 && h == 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat"; bgImg.style.width = maxWidth + "px"; bgImg.style.height = maxHeight + "px"; } else { if (w > maxWidth || h > maxHeight) { if (w > h) { img.style.width = maxWidth + "px"; img.style.height = Math.round((h / w) * maxWidth) + "px"; } else { img.style.width = Math.round((w / h) * maxHeight) + "px"; img.style.height = maxHeight + "px"; } } } caption.innerHTML = $STRF("Dimensions", [w, h]); removeClass(innerBox, "infoTipLoading"); } /**/ }), initializeBrowser: function(browser) { browser.onInfoTipMouseOut = bind(this.onMouseOut, this, browser); browser.onInfoTipMouseMove = bind(this.onMouseMove, this, browser); ///var doc = browser.contentDocument; var doc = browser.document; if (!doc) return; ///doc.addEventListener("mouseover", browser.onInfoTipMouseMove, true); ///doc.addEventListener("mouseout", browser.onInfoTipMouseOut, true); ///doc.addEventListener("mousemove", browser.onInfoTipMouseMove, true); addEvent(doc, "mouseover", browser.onInfoTipMouseMove); addEvent(doc, "mouseout", browser.onInfoTipMouseOut); addEvent(doc, "mousemove", browser.onInfoTipMouseMove); return browser.infoTip = this.tags.infoTipTag.append({}, getBody(doc)); }, uninitializeBrowser: function(browser) { if (browser.infoTip) { ///var doc = browser.contentDocument; var doc = browser.document; ///doc.removeEventListener("mouseover", browser.onInfoTipMouseMove, true); ///doc.removeEventListener("mouseout", browser.onInfoTipMouseOut, true); ///doc.removeEventListener("mousemove", browser.onInfoTipMouseMove, true); removeEvent(doc, "mouseover", browser.onInfoTipMouseMove); removeEvent(doc, "mouseout", browser.onInfoTipMouseOut); removeEvent(doc, "mousemove", browser.onInfoTipMouseMove); browser.infoTip.parentNode.removeChild(browser.infoTip); delete browser.infoTip; delete browser.onInfoTipMouseMove; } }, showInfoTip: function(infoTip, panel, target, x, y, rangeParent, rangeOffset) { if (!Firebug.showInfoTips) return; var scrollParent = getOverflowParent(target); var scrollX = x + (scrollParent ? scrollParent.scrollLeft : 0); if (panel.showInfoTip(infoTip, target, scrollX, y, rangeParent, rangeOffset)) { var htmlElt = infoTip.ownerDocument.documentElement; var panelWidth = htmlElt.clientWidth; var panelHeight = htmlElt.clientHeight; if (x+infoTip.offsetWidth+infoTipMargin > panelWidth) { infoTip.style.left = Math.max(0, panelWidth-(infoTip.offsetWidth+infoTipMargin)) + "px"; infoTip.style.right = "auto"; } else { infoTip.style.left = (x+infoTipMargin) + "px"; infoTip.style.right = "auto"; } if (y+infoTip.offsetHeight+infoTipMargin > panelHeight) { infoTip.style.top = Math.max(0, panelHeight-(infoTip.offsetHeight+infoTipMargin)) + "px"; infoTip.style.bottom = "auto"; } else { infoTip.style.top = (y+infoTipMargin) + "px"; infoTip.style.bottom = "auto"; } if (FBTrace.DBG_INFOTIP) FBTrace.sysout("infotip.showInfoTip; top: " + infoTip.style.top + ", left: " + infoTip.style.left + ", bottom: " + infoTip.style.bottom + ", right:" + infoTip.style.right + ", offsetHeight: " + infoTip.offsetHeight + ", offsetWidth: " + infoTip.offsetWidth + ", x: " + x + ", panelWidth: " + panelWidth + ", y: " + y + ", panelHeight: " + panelHeight); infoTip.setAttribute("active", "true"); } else this.hideInfoTip(infoTip); }, hideInfoTip: function(infoTip) { if (infoTip) infoTip.removeAttribute("active"); }, onMouseOut: function(event, browser) { if (!event.relatedTarget) this.hideInfoTip(browser.infoTip); }, onMouseMove: function(event, browser) { // Ignore if the mouse is moving over the existing info tip. if (getAncestorByClass(event.target, "infoTip")) return; if (browser.currentPanel) { var x = event.clientX, y = event.clientY, target = event.target || event.srcElement; this.showInfoTip(browser.infoTip, browser.currentPanel, target, x, y, event.rangeParent, event.rangeOffset); } else this.hideInfoTip(browser.infoTip); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * populateColorInfoTip: function(infoTip, color) { this.tags.colorTag.replace({rgbValue: color}, infoTip); return true; }, populateImageInfoTip: function(infoTip, url, repeat) { if (!repeat) repeat = "no-repeat"; this.tags.imgTag.replace({urlValue: url, repeat: repeat}, infoTip); return true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Module disable: function() { // XXXjoe For each browser, call uninitializeBrowser }, showPanel: function(browser, panel) { if (panel) { var infoTip = panel.panelBrowser.infoTip; if (!infoTip) infoTip = this.initializeBrowser(panel.panelBrowser); this.hideInfoTip(infoTip); } }, showSidePanel: function(browser, panel) { this.showPanel(browser, panel); } }); // ************************************************************************************************ Firebug.registerModule(Firebug.InfoTip); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ var CssParser = null; // ************************************************************************************************ // Simple CSS stylesheet parser from: // https://github.com/sergeche/webkit-css /** * Simple CSS stylesheet parser that remembers rule's lines in file * @author Sergey Chikuyonok ([email protected]) * @link http://chikuyonok.ru */ CssParser = (function(){ /** * Returns rule object * @param {Number} start Character index where CSS rule definition starts * @param {Number} body_start Character index where CSS rule's body starts * @param {Number} end Character index where CSS rule definition ends */ function rule(start, body_start, end) { return { start: start || 0, body_start: body_start || 0, end: end || 0, line: -1, selector: null, parent: null, /** @type {rule[]} */ children: [], addChild: function(start, body_start, end) { var r = rule(start, body_start, end); r.parent = this; this.children.push(r); return r; }, /** * Returns last child element * @return {rule} */ lastChild: function() { return this.children[this.children.length - 1]; } }; } /** * Replaces all occurances of substring defined by regexp * @param {String} str * @return {RegExp} re * @return {String} */ function removeAll(str, re) { var m; while (m = str.match(re)) { str = str.substring(m[0].length); } return str; } /** * Trims whitespace from the beginning and the end of string * @param {String} str * @return {String} */ function trim(str) { return str.replace(/^\s+|\s+$/g, ''); } /** * Normalizes CSS rules selector * @param {String} selector */ function normalizeSelector(selector) { // remove newlines selector = selector.replace(/[\n\r]/g, ' '); selector = trim(selector); // remove spaces after commas selector = selector.replace(/\s*,\s*/g, ','); return selector; } /** * Preprocesses parsed rules: adjusts char indexes, skipping whitespace and * newlines, saves rule selector, removes comments, etc. * @param {String} text CSS stylesheet * @param {rule} rule_node CSS rule node * @return {rule[]} */ function preprocessRules(text, rule_node) { for (var i = 0, il = rule_node.children.length; i < il; i++) { var r = rule_node.children[i], rule_start = text.substring(r.start, r.body_start), cur_len = rule_start.length; // remove newlines for better regexp matching rule_start = rule_start.replace(/[\n\r]/g, ' '); // remove @import rules // rule_start = removeAll(rule_start, /^\s*@import\s*url\((['"])?.+?\1?\)\;?/g); // remove comments rule_start = removeAll(rule_start, /^\s*\/\*.*?\*\/[\s\t]*/); // remove whitespace rule_start = rule_start.replace(/^[\s\t]+/, ''); r.start += (cur_len - rule_start.length); r.selector = normalizeSelector(rule_start); } return rule_node; } /** * Saves all lise starting indexes for faster search * @param {String} text CSS stylesheet * @return {Number[]} */ function saveLineIndexes(text) { var result = [0], i = 0, il = text.length, ch, ch2; while (i < il) { ch = text.charAt(i); if (ch == '\n' || ch == '\r') { if (ch == '\r' && i < il - 1 && text.charAt(i + 1) == '\n') { // windows line ending: CRLF. Skip next character i++; } result.push(i + 1); } i++; } return result; } /** * Saves line number for parsed rules * @param {String} text CSS stylesheet * @param {rule} rule_node Rule node * @return {rule[]} */ function saveLineNumbers(text, rule_node, line_indexes, startLine) { preprocessRules(text, rule_node); startLine = startLine || 0; // remember lines start indexes, preserving line ending characters if (!line_indexes) var line_indexes = saveLineIndexes(text); // now find each rule's line for (var i = 0, il = rule_node.children.length; i < il; i++) { var r = rule_node.children[i]; r.line = line_indexes.length + startLine; for (var j = 0, jl = line_indexes.length - 1; j < jl; j++) { var line_ix = line_indexes[j]; if (r.start >= line_indexes[j] && r.start < line_indexes[j + 1]) { r.line = j + 1 + startLine; break; } } saveLineNumbers(text, r, line_indexes); } return rule_node; } return { /** * Parses text as CSS stylesheet, remembring each rule position inside * text * @param {String} text CSS stylesheet to parse */ read: function(text, startLine) { var rule_start = [], rule_body_start = [], rules = [], in_comment = 0, root = rule(), cur_parent = root, last_rule = null, stack = [], ch, ch2; stack.last = function() { return this[this.length - 1]; }; function hasStr(pos, substr) { return text.substr(pos, substr.length) == substr; } for (var i = 0, il = text.length; i < il; i++) { ch = text.charAt(i); ch2 = i < il - 1 ? text.charAt(i + 1) : ''; if (!rule_start.length) rule_start.push(i); switch (ch) { case '@': if (!in_comment) { if (hasStr(i, '@import')) { var m = text.substr(i).match(/^@import\s*url\((['"])?.+?\1?\)\;?/); if (m) { cur_parent.addChild(i, i + 7, i + m[0].length); i += m[0].length; rule_start.pop(); } break; } } case '/': // xxxpedro allowing comment inside comment if (!in_comment && ch2 == '*') { // comment start in_comment++; } break; case '*': if (ch2 == '/') { // comment end in_comment--; } break; case '{': if (!in_comment) { rule_body_start.push(i); cur_parent = cur_parent.addChild(rule_start.pop()); stack.push(cur_parent); } break; case '}': // found the end of the rule if (!in_comment) { /** @type {rule} */ var last_rule = stack.pop(); rule_start.pop(); last_rule.body_start = rule_body_start.pop(); last_rule.end = i; cur_parent = last_rule.parent || root; } break; } } return saveLineNumbers(text, root, null, startLine); }, normalizeSelector: normalizeSelector, /** * Find matched rule by selector. * @param {rule} rule_node Parsed rule node * @param {String} selector CSS selector * @param {String} source CSS stylesheet source code * * @return {rule[]|null} Array of matched rules, sorted by priority (most * recent on top) */ findBySelector: function(rule_node, selector, source) { var selector = normalizeSelector(selector), result = []; if (rule_node) { for (var i = 0, il = rule_node.children.length; i < il; i++) { /** @type {rule} */ var r = rule_node.children[i]; if (r.selector == selector) { result.push(r); } } } if (result.length) { return result; } else { return null; } } }; })(); // ************************************************************************************************ FBL.CssParser = CssParser; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // StyleSheet Parser var CssAnalyzer = {}; // ************************************************************************************************ // Locals var CSSRuleMap = {}; var ElementCSSRulesMap = {}; var internalStyleSheetIndex = -1; var reSelectorTag = /(^|\s)(?:\w+)/g; var reSelectorClass = /\.[\w\d_-]+/g; var reSelectorId = /#[\w\d_-]+/g; var globalCSSRuleIndex; var processAllStyleSheetsTimeout = null; var externalStyleSheetURLs = []; var ElementCache = Firebug.Lite.Cache.Element; var StyleSheetCache = Firebug.Lite.Cache.StyleSheet; //************************************************************************************************ // CSS Analyzer templates CssAnalyzer.externalStyleSheetWarning = domplate(Firebug.Rep, { tag: DIV({"class": "warning focusRow", style: "font-weight:normal;", role: 'listitem'}, SPAN("$object|STR"), A({"href": "$href", target:"_blank"}, "$link|STR") ) }); // ************************************************************************************************ // CSS Analyzer methods CssAnalyzer.processAllStyleSheets = function(doc, styleSheetIterator) { try { processAllStyleSheets(doc, styleSheetIterator); } catch(e) { // TODO: FBTrace condition FBTrace.sysout("CssAnalyzer.processAllStyleSheets fails: ", e); } }; /** * * @param element * @returns {String[]} Array of IDs of CSS Rules */ CssAnalyzer.getElementCSSRules = function(element) { try { return getElementCSSRules(element); } catch(e) { // TODO: FBTrace condition FBTrace.sysout("CssAnalyzer.getElementCSSRules fails: ", e); } }; CssAnalyzer.getRuleData = function(ruleId) { return CSSRuleMap[ruleId]; }; // TODO: do we need this? CssAnalyzer.getRuleLine = function() { }; CssAnalyzer.hasExternalStyleSheet = function() { return externalStyleSheetURLs.length > 0; }; CssAnalyzer.parseStyleSheet = function(href) { var sourceData = extractSourceData(href); var parsedObj = CssParser.read(sourceData.source, sourceData.startLine); var parsedRules = parsedObj.children; // See: Issue 4776: [Firebug lite] CSS Media Types // // Ignore all special selectors like @media and @page for(var i=0; i < parsedRules.length; ) { if (parsedRules[i].selector.indexOf("@") != -1) { parsedRules.splice(i, 1); } else i++; } return parsedRules; }; //************************************************************************************************ // Internals //************************************************************************************************ // ************************************************************************************************ // StyleSheet processing var processAllStyleSheets = function(doc, styleSheetIterator) { styleSheetIterator = styleSheetIterator || processStyleSheet; globalCSSRuleIndex = -1; var styleSheets = doc.styleSheets; var importedStyleSheets = []; if (FBTrace.DBG_CSS) var start = new Date().getTime(); for(var i=0, length=styleSheets.length; i<length; i++) { try { var styleSheet = styleSheets[i]; if ("firebugIgnore" in styleSheet) continue; // we must read the length to make sure we have permission to read // the stylesheet's content. If an error occurs here, we cannot // read the stylesheet due to access restriction policy var rules = isIE ? styleSheet.rules : styleSheet.cssRules; rules.length; } catch(e) { externalStyleSheetURLs.push(styleSheet.href); styleSheet.restricted = true; var ssid = StyleSheetCache(styleSheet); /// TODO: xxxpedro external css //loadExternalStylesheet(doc, styleSheetIterator, styleSheet); } // process internal and external styleSheets styleSheetIterator(doc, styleSheet); var importedStyleSheet, importedRules; // process imported styleSheets in IE if (isIE) { var imports = styleSheet.imports; for(var j=0, importsLength=imports.length; j<importsLength; j++) { try { importedStyleSheet = imports[j]; // we must read the length to make sure we have permission // to read the imported stylesheet's content. importedRules = importedStyleSheet.rules; importedRules.length; } catch(e) { externalStyleSheetURLs.push(styleSheet.href); importedStyleSheet.restricted = true; var ssid = StyleSheetCache(importedStyleSheet); } styleSheetIterator(doc, importedStyleSheet); } } // process imported styleSheets in other browsers else if (rules) { for(var j=0, rulesLength=rules.length; j<rulesLength; j++) { try { var rule = rules[j]; importedStyleSheet = rule.styleSheet; if (importedStyleSheet) { // we must read the length to make sure we have permission // to read the imported stylesheet's content. importedRules = importedStyleSheet.cssRules; importedRules.length; } else break; } catch(e) { externalStyleSheetURLs.push(styleSheet.href); importedStyleSheet.restricted = true; var ssid = StyleSheetCache(importedStyleSheet); } styleSheetIterator(doc, importedStyleSheet); } } }; if (FBTrace.DBG_CSS) { FBTrace.sysout("FBL.processAllStyleSheets", "all stylesheet rules processed in " + (new Date().getTime() - start) + "ms"); } }; // ************************************************************************************************ var processStyleSheet = function(doc, styleSheet) { if (styleSheet.restricted) return; var rules = isIE ? styleSheet.rules : styleSheet.cssRules; var ssid = StyleSheetCache(styleSheet); var href = styleSheet.href; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // CSS Parser var shouldParseCSS = typeof CssParser != "undefined" && !Firebug.disableResourceFetching; if (shouldParseCSS) { try { var parsedRules = CssAnalyzer.parseStyleSheet(href); } catch(e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("processStyleSheet FAILS", e.message || e); shouldParseCSS = false; } finally { var parsedRulesIndex = 0; var dontSupportGroupedRules = isIE && browserVersion < 9; var group = []; var groupItem; } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * for (var i=0, length=rules.length; i<length; i++) { // TODO: xxxpedro is there a better way to cache CSS Rules? The problem is that // we cannot add expando properties in the rule object in IE var rid = ssid + ":" + i; var rule = rules[i]; var selector = rule.selectorText || ""; var lineNo = null; // See: Issue 4776: [Firebug lite] CSS Media Types // // Ignore all special selectors like @media and @page if (!selector || selector.indexOf("@") != -1) continue; if (isIE) selector = selector.replace(reSelectorTag, function(s){return s.toLowerCase();}); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // CSS Parser if (shouldParseCSS) { var parsedRule = parsedRules[parsedRulesIndex]; var parsedSelector = parsedRule.selector; if (dontSupportGroupedRules && parsedSelector.indexOf(",") != -1 && group.length == 0) group = parsedSelector.split(","); if (dontSupportGroupedRules && group.length > 0) { groupItem = group.shift(); if (CssParser.normalizeSelector(selector) == groupItem) lineNo = parsedRule.line; if (group.length == 0) parsedRulesIndex++; } else if (CssParser.normalizeSelector(selector) == parsedRule.selector) { lineNo = parsedRule.line; parsedRulesIndex++; } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * CSSRuleMap[rid] = { styleSheetId: ssid, styleSheetIndex: i, order: ++globalCSSRuleIndex, specificity: // See: Issue 4777: [Firebug lite] Specificity of CSS Rules // // if it is a normal selector then calculate the specificity selector && selector.indexOf(",") == -1 ? getCSSRuleSpecificity(selector) : // See: Issue 3262: [Firebug lite] Specificity of grouped CSS Rules // // if it is a grouped selector, do not calculate the specificity // because the correct value will depend of the matched element. // The proper specificity value for grouped selectors are calculated // via getElementCSSRules(element) 0, rule: rule, lineNo: lineNo, selector: selector, cssText: rule.style ? rule.style.cssText : rule.cssText ? rule.cssText : "" }; // TODO: what happens with elements added after this? Need to create a test case. // Maybe we should place this at getElementCSSRules() but it will make the function // a lot more expensive. // // Maybe add a "refresh" button? var elements = Firebug.Selector(selector, doc); for (var j=0, elementsLength=elements.length; j<elementsLength; j++) { var element = elements[j]; var eid = ElementCache(element); if (!ElementCSSRulesMap[eid]) ElementCSSRulesMap[eid] = []; ElementCSSRulesMap[eid].push(rid); } //console.log(selector, elements); } }; // ************************************************************************************************ // External StyleSheet Loader var loadExternalStylesheet = function(doc, styleSheetIterator, styleSheet) { var url = styleSheet.href; styleSheet.firebugIgnore = true; var source = Firebug.Lite.Proxy.load(url); // TODO: check for null and error responses // remove comments //var reMultiComment = /(\/\*([^\*]|\*(?!\/))*\*\/)/g; //source = source.replace(reMultiComment, ""); // convert relative addresses to absolute ones source = source.replace(/url\(([^\)]+)\)/g, function(a,name){ var hasDomain = /\w+:\/\/./.test(name); if (!hasDomain) { name = name.replace(/^(["'])(.+)\1$/, "$2"); var first = name.charAt(0); // relative path, based on root if (first == "/") { // TODO: xxxpedro move to lib or Firebug.Lite.something // getURLRoot var m = /^([^:]+:\/{1,3}[^\/]+)/.exec(url); return m ? "url(" + m[1] + name + ")" : "url(" + name + ")"; } // relative path, based on current location else { // TODO: xxxpedro move to lib or Firebug.Lite.something // getURLPath var path = url.replace(/[^\/]+\.[\w\d]+(\?.+|#.+)?$/g, ""); path = path + name; var reBack = /[^\/]+\/\.\.\//; while(reBack.test(path)) { path = path.replace(reBack, ""); } //console.log("url(" + path + ")"); return "url(" + path + ")"; } } // if it is an absolute path, there is nothing to do return a; }); var oldStyle = styleSheet.ownerNode; if (!oldStyle) return; if (!oldStyle.parentNode) return; var style = createGlobalElement("style"); style.setAttribute("charset","utf-8"); style.setAttribute("type", "text/css"); style.innerHTML = source; //debugger; oldStyle.parentNode.insertBefore(style, oldStyle.nextSibling); oldStyle.parentNode.removeChild(oldStyle); doc.styleSheets[doc.styleSheets.length-1].externalURL = url; console.log(url, "call " + externalStyleSheetURLs.length, source); externalStyleSheetURLs.pop(); if (processAllStyleSheetsTimeout) { clearTimeout(processAllStyleSheetsTimeout); } processAllStyleSheetsTimeout = setTimeout(function(){ console.log("processing"); FBL.processAllStyleSheets(doc, styleSheetIterator); processAllStyleSheetsTimeout = null; },200); }; //************************************************************************************************ // getElementCSSRules var getElementCSSRules = function(element) { var eid = ElementCache(element); var rules = ElementCSSRulesMap[eid]; if (!rules) return; var arr = [element]; var Selector = Firebug.Selector; var ruleId, rule; // for the case of grouped selectors, we need to calculate the highest // specificity within the selectors of the group that matches the element, // so we can sort the rules properly without over estimating the specificity // of grouped selectors for (var i = 0, length = rules.length; i < length; i++) { ruleId = rules[i]; rule = CSSRuleMap[ruleId]; // check if it is a grouped selector if (rule.selector.indexOf(",") != -1) { var selectors = rule.selector.split(","); var maxSpecificity = -1; var sel, spec, mostSpecificSelector; // loop over all selectors in the group for (var j, len = selectors.length; j < len; j++) { sel = selectors[j]; // find if the selector matches the element if (Selector.matches(sel, arr).length == 1) { spec = getCSSRuleSpecificity(sel); // find the most specific selector that macthes the element if (spec > maxSpecificity) { maxSpecificity = spec; mostSpecificSelector = sel; } } } rule.specificity = maxSpecificity; } } rules.sort(sortElementRules); //rules.sort(solveRulesTied); return rules; }; // ************************************************************************************************ // Rule Specificity var sortElementRules = function(a, b) { var ruleA = CSSRuleMap[a]; var ruleB = CSSRuleMap[b]; var specificityA = ruleA.specificity; var specificityB = ruleB.specificity; if (specificityA > specificityB) return 1; else if (specificityA < specificityB) return -1; else return ruleA.order > ruleB.order ? 1 : -1; }; var solveRulesTied = function(a, b) { var ruleA = CSSRuleMap[a]; var ruleB = CSSRuleMap[b]; if (ruleA.specificity == ruleB.specificity) return ruleA.order > ruleB.order ? 1 : -1; return null; }; var getCSSRuleSpecificity = function(selector) { var match = selector.match(reSelectorTag); var tagCount = match ? match.length : 0; match = selector.match(reSelectorClass); var classCount = match ? match.length : 0; match = selector.match(reSelectorId); var idCount = match ? match.length : 0; return tagCount + 10*classCount + 100*idCount; }; // ************************************************************************************************ // StyleSheet data var extractSourceData = function(href) { var sourceData = { source: null, startLine: 0 }; if (href) { sourceData.source = Firebug.Lite.Proxy.load(href); } else { // TODO: create extractInternalSourceData(index) // TODO: pre process the position of the inline styles so this will happen only once // in case of having multiple inline styles var index = 0; var ssIndex = ++internalStyleSheetIndex; var reStyleTag = /\<\s*style.*\>/gi; var reEndStyleTag = /\<\/\s*style.*\>/gi; var source = Firebug.Lite.Proxy.load(Env.browser.location.href); source = source.replace(/\n\r|\r\n/g, "\n"); // normalize line breaks var startLine = 0; do { var matchStyleTag = source.match(reStyleTag); var i0 = source.indexOf(matchStyleTag[0]) + matchStyleTag[0].length; for (var i=0; i < i0; i++) { if (source.charAt(i) == "\n") startLine++; } source = source.substr(i0); index++; } while (index <= ssIndex); var matchEndStyleTag = source.match(reEndStyleTag); var i1 = source.indexOf(matchEndStyleTag[0]); var extractedSource = source.substr(0, i1); sourceData.source = extractedSource; sourceData.startLine = startLine; } return sourceData; }; // ************************************************************************************************ // Registration FBL.CssAnalyzer = CssAnalyzer; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ // move to FBL (function() { // ************************************************************************************************ // XPath /** * Gets an XPath for an element which describes its hierarchical location. */ this.getElementXPath = function(element) { try { if (element && element.id) return '//*[@id="' + element.id + '"]'; else return this.getElementTreeXPath(element); } catch(E) { // xxxpedro: trying to detect the mysterious error: // Security error" code: "1000 //debugger; } }; this.getElementTreeXPath = function(element) { var paths = []; for (; element && element.nodeType == 1; element = element.parentNode) { var index = 0; var nodeName = element.nodeName; for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) { if (sibling.nodeType != 1) continue; if (sibling.nodeName == nodeName) ++index; } var tagName = element.nodeName.toLowerCase(); var pathIndex = (index ? "[" + (index+1) + "]" : ""); paths.splice(0, 0, tagName + pathIndex); } return paths.length ? "/" + paths.join("/") : null; }; this.getElementsByXPath = function(doc, xpath) { var nodes = []; try { var result = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null); for (var item = result.iterateNext(); item; item = result.iterateNext()) nodes.push(item); } catch (exc) { // Invalid xpath expressions make their way here sometimes. If that happens, // we still want to return an empty set without an exception. } return nodes; }; this.getRuleMatchingElements = function(rule, doc) { var css = rule.selectorText; var xpath = this.cssToXPath(css); return this.getElementsByXPath(doc, xpath); }; }).call(FBL); FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ var toCamelCase = function toCamelCase(s) { return s.replace(reSelectorCase, toCamelCaseReplaceFn); }; var toSelectorCase = function toSelectorCase(s) { return s.replace(reCamelCase, "-$1").toLowerCase(); }; var reCamelCase = /([A-Z])/g; var reSelectorCase = /\-(.)/g; var toCamelCaseReplaceFn = function toCamelCaseReplaceFn(m,g) { return g.toUpperCase(); }; // ************************************************************************************************ var ElementCache = Firebug.Lite.Cache.Element; var StyleSheetCache = Firebug.Lite.Cache.StyleSheet; // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // Constants //const Cc = Components.classes; //const Ci = Components.interfaces; //const nsIDOMCSSStyleRule = Ci.nsIDOMCSSStyleRule; //const nsIInterfaceRequestor = Ci.nsIInterfaceRequestor; //const nsISelectionDisplay = Ci.nsISelectionDisplay; //const nsISelectionController = Ci.nsISelectionController; // See: http://mxr.mozilla.org/mozilla1.9.2/source/content/events/public/nsIEventStateManager.h#153 //const STATE_ACTIVE = 0x01; //const STATE_FOCUS = 0x02; //const STATE_HOVER = 0x04; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Firebug.SourceBoxPanel = Firebug.Panel; var reSelectorTag = /(^|\s)(?:\w+)/g; var domUtils = null; var textContent = isIE ? "innerText" : "textContent"; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var CSSDomplateBase = { isEditable: function(rule) { return !rule.isSystemSheet; }, isSelectorEditable: function(rule) { return rule.isSelectorEditable && this.isEditable(rule); } }; var CSSPropTag = domplate(CSSDomplateBase, { tag: DIV({"class": "cssProp focusRow", $disabledStyle: "$prop.disabled", $editGroup: "$rule|isEditable", $cssOverridden: "$prop.overridden", role : "option"}, A({"class": "cssPropDisable"}, "&nbsp;&nbsp;"), SPAN({"class": "cssPropName", $editable: "$rule|isEditable"}, "$prop.name"), SPAN({"class": "cssColon"}, ":"), SPAN({"class": "cssPropValue", $editable: "$rule|isEditable"}, "$prop.value$prop.important"), SPAN({"class": "cssSemi"}, ";") ) }); var CSSRuleTag = TAG("$rule.tag", {rule: "$rule"}); var CSSImportRuleTag = domplate({ tag: DIV({"class": "cssRule insertInto focusRow importRule", _repObject: "$rule.rule"}, "@import &quot;", A({"class": "objectLink", _repObject: "$rule.rule.styleSheet"}, "$rule.rule.href"), "&quot;;" ) }); var CSSStyleRuleTag = domplate(CSSDomplateBase, { tag: DIV({"class": "cssRule insertInto", $cssEditableRule: "$rule|isEditable", $editGroup: "$rule|isSelectorEditable", _repObject: "$rule.rule", "ruleId": "$rule.id", role : 'presentation'}, DIV({"class": "cssHead focusRow", role : 'listitem'}, SPAN({"class": "cssSelector", $editable: "$rule|isSelectorEditable"}, "$rule.selector"), " {" ), DIV({role : 'group'}, DIV({"class": "cssPropertyListBox", role : 'listbox'}, FOR("prop", "$rule.props", TAG(CSSPropTag.tag, {rule: "$rule", prop: "$prop"}) ) ) ), DIV({"class": "editable insertBefore", role:"presentation"}, "}") ) }); var reSplitCSS = /(url\("?[^"\)]+?"?\))|(rgb\(.*?\))|(#[\dA-Fa-f]+)|(-?\d+(\.\d+)?(%|[a-z]{1,2})?)|([^,\s]+)|"(.*?)"/; var reURL = /url\("?([^"\)]+)?"?\)/; var reRepeat = /no-repeat|repeat-x|repeat-y|repeat/; //const sothinkInstalled = !!$("swfcatcherKey_sidebar"); var sothinkInstalled = false; var styleGroups = { text: [ "font-family", "font-size", "font-weight", "font-style", "color", "text-transform", "text-decoration", "letter-spacing", "word-spacing", "line-height", "text-align", "vertical-align", "direction", "column-count", "column-gap", "column-width" ], background: [ "background-color", "background-image", "background-repeat", "background-position", "background-attachment", "opacity" ], box: [ "width", "height", "top", "right", "bottom", "left", "margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-style", "border-right-style", "border-bottom-style", "border-left-style", "-moz-border-top-radius", "-moz-border-right-radius", "-moz-border-bottom-radius", "-moz-border-left-radius", "outline-top-width", "outline-right-width", "outline-bottom-width", "outline-left-width", "outline-top-color", "outline-right-color", "outline-bottom-color", "outline-left-color", "outline-top-style", "outline-right-style", "outline-bottom-style", "outline-left-style" ], layout: [ "position", "display", "visibility", "z-index", "overflow-x", // http://www.w3.org/TR/2002/WD-css3-box-20021024/#overflow "overflow-y", "overflow-clip", "white-space", "clip", "float", "clear", "-moz-box-sizing" ], other: [ "cursor", "list-style-image", "list-style-position", "list-style-type", "marker-offset", "user-focus", "user-select", "user-modify", "user-input" ] }; var styleGroupTitles = { text: "Text", background: "Background", box: "Box Model", layout: "Layout", other: "Other" }; Firebug.CSSModule = extend(Firebug.Module, { freeEdit: function(styleSheet, value) { if (!styleSheet.editStyleSheet) { var ownerNode = getStyleSheetOwnerNode(styleSheet); styleSheet.disabled = true; var url = CCSV("@mozilla.org/network/standard-url;1", Components.interfaces.nsIURL); url.spec = styleSheet.href; var editStyleSheet = ownerNode.ownerDocument.createElementNS( "http://www.w3.org/1999/xhtml", "style"); unwrapObject(editStyleSheet).firebugIgnore = true; editStyleSheet.setAttribute("type", "text/css"); editStyleSheet.setAttributeNS( "http://www.w3.org/XML/1998/namespace", "base", url.directory); if (ownerNode.hasAttribute("media")) { editStyleSheet.setAttribute("media", ownerNode.getAttribute("media")); } // Insert the edited stylesheet directly after the old one to ensure the styles // cascade properly. ownerNode.parentNode.insertBefore(editStyleSheet, ownerNode.nextSibling); styleSheet.editStyleSheet = editStyleSheet; } styleSheet.editStyleSheet.innerHTML = value; if (FBTrace.DBG_CSS) FBTrace.sysout("css.saveEdit styleSheet.href:"+styleSheet.href+" got innerHTML:"+value+"\n"); dispatch(this.fbListeners, "onCSSFreeEdit", [styleSheet, value]); }, insertRule: function(styleSheet, cssText, ruleIndex) { if (FBTrace.DBG_CSS) FBTrace.sysout("Insert: " + ruleIndex + " " + cssText); var insertIndex = styleSheet.insertRule(cssText, ruleIndex); dispatch(this.fbListeners, "onCSSInsertRule", [styleSheet, cssText, ruleIndex]); return insertIndex; }, deleteRule: function(styleSheet, ruleIndex) { if (FBTrace.DBG_CSS) FBTrace.sysout("deleteRule: " + ruleIndex + " " + styleSheet.cssRules.length, styleSheet.cssRules); dispatch(this.fbListeners, "onCSSDeleteRule", [styleSheet, ruleIndex]); styleSheet.deleteRule(ruleIndex); }, setProperty: function(rule, propName, propValue, propPriority) { var style = rule.style || rule; // Record the original CSS text for the inline case so we can reconstruct at a later // point for diffing purposes var baseText = style.cssText; // good browsers if (style.getPropertyValue) { var prevValue = style.getPropertyValue(propName); var prevPriority = style.getPropertyPriority(propName); // XXXjoe Gecko bug workaround: Just changing priority doesn't have any effect // unless we remove the property first style.removeProperty(propName); style.setProperty(propName, propValue, propPriority); } // sad browsers else { // TODO: xxxpedro parse CSS rule to find property priority in IE? //console.log(propName, propValue); style[toCamelCase(propName)] = propValue; } if (propName) { dispatch(this.fbListeners, "onCSSSetProperty", [style, propName, propValue, propPriority, prevValue, prevPriority, rule, baseText]); } }, removeProperty: function(rule, propName, parent) { var style = rule.style || rule; // Record the original CSS text for the inline case so we can reconstruct at a later // point for diffing purposes var baseText = style.cssText; if (style.getPropertyValue) { var prevValue = style.getPropertyValue(propName); var prevPriority = style.getPropertyPriority(propName); style.removeProperty(propName); } else { style[toCamelCase(propName)] = ""; } if (propName) { dispatch(this.fbListeners, "onCSSRemoveProperty", [style, propName, prevValue, prevPriority, rule, baseText]); } }/*, cleanupSheets: function(doc, context) { // Due to the manner in which the layout engine handles multiple // references to the same sheet we need to kick it a little bit. // The injecting a simple stylesheet then removing it will force // Firefox to regenerate it's CSS hierarchy. // // WARN: This behavior was determined anecdotally. // See http://code.google.com/p/fbug/issues/detail?id=2440 var style = doc.createElementNS("http://www.w3.org/1999/xhtml", "style"); style.setAttribute("charset","utf-8"); unwrapObject(style).firebugIgnore = true; style.setAttribute("type", "text/css"); style.innerHTML = "#fbIgnoreStyleDO_NOT_USE {}"; addStyleSheet(doc, style); style.parentNode.removeChild(style); // https://bugzilla.mozilla.org/show_bug.cgi?id=500365 // This voodoo touches each style sheet to force some Firefox internal change to allow edits. var styleSheets = getAllStyleSheets(context); for(var i = 0; i < styleSheets.length; i++) { try { var rules = styleSheets[i].cssRules; if (rules.length > 0) var touch = rules[0]; if (FBTrace.DBG_CSS && touch) FBTrace.sysout("css.show() touch "+typeof(touch)+" in "+(styleSheets[i].href?styleSheets[i].href:context.getName())); } catch(e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("css.show: sheet.cssRules FAILS for "+(styleSheets[i]?styleSheets[i].href:"null sheet")+e, e); } } }, cleanupSheetHandler: function(event, context) { var target = event.target || event.srcElement, tagName = (target.tagName || "").toLowerCase(); if (tagName == "link") { this.cleanupSheets(target.ownerDocument, context); } }, watchWindow: function(context, win) { var cleanupSheets = bind(this.cleanupSheets, this), cleanupSheetHandler = bind(this.cleanupSheetHandler, this, context), doc = win.document; //doc.addEventListener("DOMAttrModified", cleanupSheetHandler, false); //doc.addEventListener("DOMNodeInserted", cleanupSheetHandler, false); }, loadedContext: function(context) { var self = this; iterateWindows(context.browser.contentWindow, function(subwin) { self.cleanupSheets(subwin.document, context); }); } /**/ }); // ************************************************************************************************ Firebug.CSSStyleSheetPanel = function() {}; Firebug.CSSStyleSheetPanel.prototype = extend(Firebug.SourceBoxPanel, { template: domplate( { tag: DIV({"class": "cssSheet insertInto a11yCSSView"}, FOR("rule", "$rules", CSSRuleTag ), DIV({"class": "cssSheet editable insertBefore"}, "") ) }), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * refresh: function() { if (this.location) this.updateLocation(this.location); else if (this.selection) this.updateSelection(this.selection); }, toggleEditing: function() { if (!this.stylesheetEditor) this.stylesheetEditor = new StyleSheetEditor(this.document); if (this.editing) Firebug.Editor.stopEditing(); else { if (!this.location) return; var styleSheet = this.location.editStyleSheet ? this.location.editStyleSheet.sheet : this.location; var css = getStyleSheetCSS(styleSheet, this.context); //var topmost = getTopmostRuleLine(this.panelNode); this.stylesheetEditor.styleSheet = this.location; Firebug.Editor.startEditing(this.panelNode, css, this.stylesheetEditor); //this.stylesheetEditor.scrollToLine(topmost.line, topmost.offset); } }, getStylesheetURL: function(rule) { if (this.location.href) return this.location.href; else return this.context.window.location.href; }, getRuleByLine: function(styleSheet, line) { if (!domUtils) return null; var cssRules = styleSheet.cssRules; for (var i = 0; i < cssRules.length; ++i) { var rule = cssRules[i]; if (rule instanceof CSSStyleRule) { var ruleLine = domUtils.getRuleLine(rule); if (ruleLine >= line) return rule; } } }, highlightRule: function(rule) { var ruleElement = Firebug.getElementByRepObject(this.panelNode.firstChild, rule); if (ruleElement) { scrollIntoCenterView(ruleElement, this.panelNode); setClassTimed(ruleElement, "jumpHighlight", this.context); } }, getStyleSheetRules: function(context, styleSheet) { var isSystemSheet = isSystemStyleSheet(styleSheet); function appendRules(cssRules) { for (var i = 0; i < cssRules.length; ++i) { var rule = cssRules[i]; // TODO: xxxpedro opera instanceof stylesheet remove the following comments when // the issue with opera and style sheet Classes has been solved. //if (rule instanceof CSSStyleRule) if (instanceOf(rule, "CSSStyleRule")) { var props = this.getRuleProperties(context, rule); //var line = domUtils.getRuleLine(rule); var line = null; var selector = rule.selectorText; if (isIE) { selector = selector.replace(reSelectorTag, function(s){return s.toLowerCase();}); } var ruleId = rule.selectorText+"/"+line; rules.push({tag: CSSStyleRuleTag.tag, rule: rule, id: ruleId, selector: selector, props: props, isSystemSheet: isSystemSheet, isSelectorEditable: true}); } //else if (rule instanceof CSSImportRule) else if (instanceOf(rule, "CSSImportRule")) rules.push({tag: CSSImportRuleTag.tag, rule: rule}); //else if (rule instanceof CSSMediaRule) else if (instanceOf(rule, "CSSMediaRule")) appendRules.apply(this, [rule.cssRules]); else { if (FBTrace.DBG_ERRORS || FBTrace.DBG_CSS) FBTrace.sysout("css getStyleSheetRules failed to classify a rule ", rule); } } } var rules = []; appendRules.apply(this, [styleSheet.cssRules || styleSheet.rules]); return rules; }, parseCSSProps: function(style, inheritMode) { var props = []; if (Firebug.expandShorthandProps) { var count = style.length-1, index = style.length; while (index--) { var propName = style.item(count - index); this.addProperty(propName, style.getPropertyValue(propName), !!style.getPropertyPriority(propName), false, inheritMode, props); } } else { var lines = style.cssText.match(/(?:[^;\(]*(?:\([^\)]*?\))?[^;\(]*)*;?/g); var propRE = /\s*([^:\s]*)\s*:\s*(.*?)\s*(! important)?;?$/; var line,i=0; // TODO: xxxpedro port to firebug: variable leaked into global namespace var m; while(line=lines[i++]){ m = propRE.exec(line); if(!m) continue; //var name = m[1], value = m[2], important = !!m[3]; if (m[2]) this.addProperty(m[1], m[2], !!m[3], false, inheritMode, props); }; } return props; }, getRuleProperties: function(context, rule, inheritMode) { var props = this.parseCSSProps(rule.style, inheritMode); // TODO: xxxpedro port to firebug: variable leaked into global namespace //var line = domUtils.getRuleLine(rule); var line; var ruleId = rule.selectorText+"/"+line; this.addOldProperties(context, ruleId, inheritMode, props); sortProperties(props); return props; }, addOldProperties: function(context, ruleId, inheritMode, props) { if (context.selectorMap && context.selectorMap.hasOwnProperty(ruleId) ) { var moreProps = context.selectorMap[ruleId]; for (var i = 0; i < moreProps.length; ++i) { var prop = moreProps[i]; this.addProperty(prop.name, prop.value, prop.important, true, inheritMode, props); } } }, addProperty: function(name, value, important, disabled, inheritMode, props) { name = name.toLowerCase(); if (inheritMode && !inheritedStyleNames[name]) return; name = this.translateName(name, value); if (name) { value = stripUnits(rgbToHex(value)); important = important ? " !important" : ""; var prop = {name: name, value: value, important: important, disabled: disabled}; props.push(prop); } }, translateName: function(name, value) { // Don't show these proprietary Mozilla properties if ((value == "-moz-initial" && (name == "-moz-background-clip" || name == "-moz-background-origin" || name == "-moz-background-inline-policy")) || (value == "physical" && (name == "margin-left-ltr-source" || name == "margin-left-rtl-source" || name == "margin-right-ltr-source" || name == "margin-right-rtl-source")) || (value == "physical" && (name == "padding-left-ltr-source" || name == "padding-left-rtl-source" || name == "padding-right-ltr-source" || name == "padding-right-rtl-source"))) return null; // Translate these back to the form the user probably expects if (name == "margin-left-value") return "margin-left"; else if (name == "margin-right-value") return "margin-right"; else if (name == "margin-top-value") return "margin-top"; else if (name == "margin-bottom-value") return "margin-bottom"; else if (name == "padding-left-value") return "padding-left"; else if (name == "padding-right-value") return "padding-right"; else if (name == "padding-top-value") return "padding-top"; else if (name == "padding-bottom-value") return "padding-bottom"; // XXXjoe What about border! else return name; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * editElementStyle: function() { ///var rulesBox = this.panelNode.getElementsByClassName("cssElementRuleContainer")[0]; var rulesBox = $$(".cssElementRuleContainer", this.panelNode)[0]; var styleRuleBox = rulesBox && Firebug.getElementByRepObject(rulesBox, this.selection); if (!styleRuleBox) { var rule = {rule: this.selection, inherited: false, selector: "element.style", props: []}; if (!rulesBox) { // The element did not have any displayed styles. We need to create the whole tree and remove // the no styles message styleRuleBox = this.template.cascadedTag.replace({ rules: [rule], inherited: [], inheritLabel: "Inherited from" // $STR("InheritedFrom") }, this.panelNode); ///styleRuleBox = styleRuleBox.getElementsByClassName("cssElementRuleContainer")[0]; styleRuleBox = $$(".cssElementRuleContainer", styleRuleBox)[0]; } else styleRuleBox = this.template.ruleTag.insertBefore({rule: rule}, rulesBox); ///styleRuleBox = styleRuleBox.getElementsByClassName("insertInto")[0]; styleRuleBox = $$(".insertInto", styleRuleBox)[0]; } Firebug.Editor.insertRowForObject(styleRuleBox); }, insertPropertyRow: function(row) { Firebug.Editor.insertRowForObject(row); }, insertRule: function(row) { var location = getAncestorByClass(row, "cssRule"); if (!location) { location = getChildByClass(this.panelNode, "cssSheet"); Firebug.Editor.insertRowForObject(location); } else { Firebug.Editor.insertRow(location, "before"); } }, editPropertyRow: function(row) { var propValueBox = getChildByClass(row, "cssPropValue"); Firebug.Editor.startEditing(propValueBox); }, deletePropertyRow: function(row) { var rule = Firebug.getRepObject(row); var propName = getChildByClass(row, "cssPropName")[textContent]; Firebug.CSSModule.removeProperty(rule, propName); // Remove the property from the selector map, if it was disabled var ruleId = Firebug.getRepNode(row).getAttribute("ruleId"); if ( this.context.selectorMap && this.context.selectorMap.hasOwnProperty(ruleId) ) { var map = this.context.selectorMap[ruleId]; for (var i = 0; i < map.length; ++i) { if (map[i].name == propName) { map.splice(i, 1); break; } } } if (this.name == "stylesheet") dispatch([Firebug.A11yModel], 'onInlineEditorClose', [this, row.firstChild, true]); row.parentNode.removeChild(row); this.markChange(this.name == "stylesheet"); }, disablePropertyRow: function(row) { toggleClass(row, "disabledStyle"); var rule = Firebug.getRepObject(row); var propName = getChildByClass(row, "cssPropName")[textContent]; if (!this.context.selectorMap) this.context.selectorMap = {}; // XXXjoe Generate unique key for elements too var ruleId = Firebug.getRepNode(row).getAttribute("ruleId"); if (!(this.context.selectorMap.hasOwnProperty(ruleId))) this.context.selectorMap[ruleId] = []; var map = this.context.selectorMap[ruleId]; var propValue = getChildByClass(row, "cssPropValue")[textContent]; var parsedValue = parsePriority(propValue); if (hasClass(row, "disabledStyle")) { Firebug.CSSModule.removeProperty(rule, propName); map.push({"name": propName, "value": parsedValue.value, "important": parsedValue.priority}); } else { Firebug.CSSModule.setProperty(rule, propName, parsedValue.value, parsedValue.priority); var index = findPropByName(map, propName); map.splice(index, 1); } this.markChange(this.name == "stylesheet"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onMouseDown: function(event) { //console.log("onMouseDown", event.target || event.srcElement, event); // xxxpedro adjusting coordinates because the panel isn't a window yet var offset = event.clientX - this.panelNode.parentNode.offsetLeft; // XXjoe Hack to only allow clicking on the checkbox if (!isLeftClick(event) || offset > 20) return; var target = event.target || event.srcElement; if (hasClass(target, "textEditor")) return; var row = getAncestorByClass(target, "cssProp"); if (row && hasClass(row, "editGroup")) { this.disablePropertyRow(row); cancelEvent(event); } }, onDoubleClick: function(event) { //console.log("onDoubleClick", event.target || event.srcElement, event); // xxxpedro adjusting coordinates because the panel isn't a window yet var offset = event.clientX - this.panelNode.parentNode.offsetLeft; if (!isLeftClick(event) || offset <= 20) return; var target = event.target || event.srcElement; //console.log("ok", target, hasClass(target, "textEditorInner"), !isLeftClick(event), offset <= 20); // if the inline editor was clicked, don't insert a new rule if (hasClass(target, "textEditorInner")) return; var row = getAncestorByClass(target, "cssRule"); if (row && !getAncestorByClass(target, "cssPropName") && !getAncestorByClass(target, "cssPropValue")) { this.insertPropertyRow(row); cancelEvent(event); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "stylesheet", title: "CSS", parentPanel: null, searchable: true, dependents: ["css", "stylesheet", "dom", "domSide", "layout"], options: { hasToolButtons: true }, create: function() { Firebug.Panel.create.apply(this, arguments); this.onMouseDown = bind(this.onMouseDown, this); this.onDoubleClick = bind(this.onDoubleClick, this); if (this.name == "stylesheet") { this.onChangeSelect = bind(this.onChangeSelect, this); var doc = Firebug.browser.document; var selectNode = this.selectNode = createElement("select"); CssAnalyzer.processAllStyleSheets(doc, function(doc, styleSheet) { var key = StyleSheetCache.key(styleSheet); var fileName = getFileName(styleSheet.href) || getFileName(doc.location.href); var option = createElement("option", {value: key}); option.appendChild(Firebug.chrome.document.createTextNode(fileName)); selectNode.appendChild(option); }); this.toolButtonsNode.appendChild(selectNode); } /**/ }, onChangeSelect: function(event) { event = event || window.event; var target = event.srcElement || event.currentTarget; var key = target.value; var styleSheet = StyleSheetCache.get(key); this.updateLocation(styleSheet); }, initialize: function() { Firebug.Panel.initialize.apply(this, arguments); //if (!domUtils) //{ // try { // domUtils = CCSV("@mozilla.org/inspector/dom-utils;1", "inIDOMUtils"); // } catch (exc) { // if (FBTrace.DBG_ERRORS) // FBTrace.sysout("@mozilla.org/inspector/dom-utils;1 FAILED to load: "+exc, exc); // } //} //TODO: xxxpedro this.context = Firebug.chrome; // TODO: xxxpedro css2 this.document = Firebug.chrome.document; // TODO: xxxpedro css2 this.initializeNode(); if (this.name == "stylesheet") { var styleSheets = Firebug.browser.document.styleSheets; if (styleSheets.length > 0) { addEvent(this.selectNode, "change", this.onChangeSelect); this.updateLocation(styleSheets[0]); } } //Firebug.SourceBoxPanel.initialize.apply(this, arguments); }, shutdown: function() { // must destroy the editor when we leave the panel to avoid problems (Issue 2981) Firebug.Editor.stopEditing(); if (this.name == "stylesheet") { removeEvent(this.selectNode, "change", this.onChangeSelect); } this.destroyNode(); Firebug.Panel.shutdown.apply(this, arguments); }, destroy: function(state) { //state.scrollTop = this.panelNode.scrollTop ? this.panelNode.scrollTop : this.lastScrollTop; //persistObjects(this, state); // xxxpedro we are stopping the editor in the shutdown method already //Firebug.Editor.stopEditing(); Firebug.Panel.destroy.apply(this, arguments); }, initializeNode: function(oldPanelNode) { addEvent(this.panelNode, "mousedown", this.onMouseDown); addEvent(this.panelNode, "dblclick", this.onDoubleClick); //Firebug.SourceBoxPanel.initializeNode.apply(this, arguments); //dispatch([Firebug.A11yModel], 'onInitializeNode', [this, 'css']); }, destroyNode: function() { removeEvent(this.panelNode, "mousedown", this.onMouseDown); removeEvent(this.panelNode, "dblclick", this.onDoubleClick); //Firebug.SourceBoxPanel.destroyNode.apply(this, arguments); //dispatch([Firebug.A11yModel], 'onDestroyNode', [this, 'css']); }, ishow: function(state) { Firebug.Inspector.stopInspecting(true); this.showToolbarButtons("fbCSSButtons", true); if (this.context.loaded && !this.location) // wait for loadedContext to restore the panel { restoreObjects(this, state); if (!this.location) this.location = this.getDefaultLocation(); if (state && state.scrollTop) this.panelNode.scrollTop = state.scrollTop; } }, ihide: function() { this.showToolbarButtons("fbCSSButtons", false); this.lastScrollTop = this.panelNode.scrollTop; }, supportsObject: function(object) { if (object instanceof CSSStyleSheet) return 1; else if (object instanceof CSSStyleRule) return 2; else if (object instanceof CSSStyleDeclaration) return 2; else if (object instanceof SourceLink && object.type == "css" && reCSS.test(object.href)) return 2; else return 0; }, updateLocation: function(styleSheet) { if (!styleSheet) return; if (styleSheet.editStyleSheet) styleSheet = styleSheet.editStyleSheet.sheet; // if it is a restricted stylesheet, show the warning message and abort the update process if (styleSheet.restricted) { FirebugReps.Warning.tag.replace({object: "AccessRestricted"}, this.panelNode); // TODO: xxxpedro remove when there the external resource problem is fixed CssAnalyzer.externalStyleSheetWarning.tag.append({ object: "The stylesheet could not be loaded due to access restrictions. ", link: "more...", href: "http://getfirebug.com/wiki/index.php/Firebug_Lite_FAQ#I_keep_seeing_.22Access_to_restricted_URI_denied.22" }, this.panelNode); return; } var rules = this.getStyleSheetRules(this.context, styleSheet); var result; if (rules.length) // FIXME xxxpedro chromenew this is making iPad's Safari to crash result = this.template.tag.replace({rules: rules}, this.panelNode); else result = FirebugReps.Warning.tag.replace({object: "EmptyStyleSheet"}, this.panelNode); // TODO: xxxpedro need to fix showToolbarButtons function //this.showToolbarButtons("fbCSSButtons", !isSystemStyleSheet(this.location)); //dispatch([Firebug.A11yModel], 'onCSSRulesAdded', [this, this.panelNode]); }, updateSelection: function(object) { this.selection = null; if (object instanceof CSSStyleDeclaration) { object = object.parentRule; } if (object instanceof CSSStyleRule) { this.navigate(object.parentStyleSheet); this.highlightRule(object); } else if (object instanceof CSSStyleSheet) { this.navigate(object); } else if (object instanceof SourceLink) { try { var sourceLink = object; var sourceFile = getSourceFileByHref(sourceLink.href, this.context); if (sourceFile) { clearNode(this.panelNode); // replace rendered stylesheets this.showSourceFile(sourceFile); var lineNo = object.line; if (lineNo) this.scrollToLine(lineNo, this.jumpHighlightFactory(lineNo, this.context)); } else // XXXjjb we should not be taking this path { var stylesheet = getStyleSheetByHref(sourceLink.href, this.context); if (stylesheet) this.navigate(stylesheet); else { if (FBTrace.DBG_CSS) FBTrace.sysout("css.updateSelection no sourceFile for "+sourceLink.href, sourceLink); } } } catch(exc) { if (FBTrace.DBG_CSS) FBTrace.sysout("css.upDateSelection FAILS "+exc, exc); } } }, updateOption: function(name, value) { if (name == "expandShorthandProps") this.refresh(); }, getLocationList: function() { var styleSheets = getAllStyleSheets(this.context); return styleSheets; }, getOptionsMenuItems: function() { return [ {label: "Expand Shorthand Properties", type: "checkbox", checked: Firebug.expandShorthandProps, command: bindFixed(Firebug.togglePref, Firebug, "expandShorthandProps") }, "-", {label: "Refresh", command: bind(this.refresh, this) } ]; }, getContextMenuItems: function(style, target) { var items = []; if (this.infoTipType == "color") { items.push( {label: "CopyColor", command: bindFixed(copyToClipboard, FBL, this.infoTipObject) } ); } else if (this.infoTipType == "image") { items.push( {label: "CopyImageLocation", command: bindFixed(copyToClipboard, FBL, this.infoTipObject) }, {label: "OpenImageInNewTab", command: bindFixed(openNewTab, FBL, this.infoTipObject) } ); } ///if (this.selection instanceof Element) if (isElement(this.selection)) { items.push( //"-", {label: "EditStyle", command: bindFixed(this.editElementStyle, this) } ); } else if (!isSystemStyleSheet(this.selection)) { items.push( //"-", {label: "NewRule", command: bindFixed(this.insertRule, this, target) } ); } var cssRule = getAncestorByClass(target, "cssRule"); if (cssRule && hasClass(cssRule, "cssEditableRule")) { items.push( "-", {label: "NewProp", command: bindFixed(this.insertPropertyRow, this, target) } ); var propRow = getAncestorByClass(target, "cssProp"); if (propRow) { var propName = getChildByClass(propRow, "cssPropName")[textContent]; var isDisabled = hasClass(propRow, "disabledStyle"); items.push( {label: $STRF("EditProp", [propName]), nol10n: true, command: bindFixed(this.editPropertyRow, this, propRow) }, {label: $STRF("DeleteProp", [propName]), nol10n: true, command: bindFixed(this.deletePropertyRow, this, propRow) }, {label: $STRF("DisableProp", [propName]), nol10n: true, type: "checkbox", checked: isDisabled, command: bindFixed(this.disablePropertyRow, this, propRow) } ); } } items.push( "-", {label: "Refresh", command: bind(this.refresh, this) } ); return items; }, browseObject: function(object) { if (this.infoTipType == "image") { openNewTab(this.infoTipObject); return true; } }, showInfoTip: function(infoTip, target, x, y) { var propValue = getAncestorByClass(target, "cssPropValue"); if (propValue) { var offset = getClientOffset(propValue); var offsetX = x-offset.x; var text = propValue[textContent]; var charWidth = propValue.offsetWidth/text.length; var charOffset = Math.floor(offsetX/charWidth); var cssValue = parseCSSValue(text, charOffset); if (cssValue) { if (cssValue.value == this.infoTipValue) return true; this.infoTipValue = cssValue.value; if (cssValue.type == "rgb" || (!cssValue.type && isColorKeyword(cssValue.value))) { this.infoTipType = "color"; this.infoTipObject = cssValue.value; return Firebug.InfoTip.populateColorInfoTip(infoTip, cssValue.value); } else if (cssValue.type == "url") { ///var propNameNode = target.parentNode.getElementsByClassName("cssPropName").item(0); var propNameNode = getElementByClass(target.parentNode, "cssPropName"); if (propNameNode && isImageRule(propNameNode[textContent])) { var rule = Firebug.getRepObject(target); var baseURL = this.getStylesheetURL(rule); var relURL = parseURLValue(cssValue.value); var absURL = isDataURL(relURL) ? relURL:absoluteURL(relURL, baseURL); var repeat = parseRepeatValue(text); this.infoTipType = "image"; this.infoTipObject = absURL; return Firebug.InfoTip.populateImageInfoTip(infoTip, absURL, repeat); } } } } delete this.infoTipType; delete this.infoTipValue; delete this.infoTipObject; }, getEditor: function(target, value) { if (target == this.panelNode || hasClass(target, "cssSelector") || hasClass(target, "cssRule") || hasClass(target, "cssSheet")) { if (!this.ruleEditor) this.ruleEditor = new CSSRuleEditor(this.document); return this.ruleEditor; } else { if (!this.editor) this.editor = new CSSEditor(this.document); return this.editor; } }, getDefaultLocation: function() { try { var styleSheets = this.context.window.document.styleSheets; if (styleSheets.length) { var sheet = styleSheets[0]; return (Firebug.filterSystemURLs && isSystemURL(getURLForStyleSheet(sheet))) ? null : sheet; } } catch (exc) { if (FBTrace.DBG_LOCATIONS) FBTrace.sysout("css.getDefaultLocation FAILS "+exc, exc); } }, getObjectDescription: function(styleSheet) { var url = getURLForStyleSheet(styleSheet); var instance = getInstanceForStyleSheet(styleSheet); var baseDescription = splitURLBase(url); if (instance) { baseDescription.name = baseDescription.name + " #" + (instance + 1); } return baseDescription; }, search: function(text, reverse) { var curDoc = this.searchCurrentDoc(!Firebug.searchGlobal, text, reverse); if (!curDoc && Firebug.searchGlobal) { return this.searchOtherDocs(text, reverse); } return curDoc; }, searchOtherDocs: function(text, reverse) { var scanRE = Firebug.Search.getTestingRegex(text); function scanDoc(styleSheet) { // we don't care about reverse here as we are just looking for existence, // if we do have a result we will handle the reverse logic on display for (var i = 0; i < styleSheet.cssRules.length; i++) { if (scanRE.test(styleSheet.cssRules[i].cssText)) { return true; } } } if (this.navigateToNextDocument(scanDoc, reverse)) { return this.searchCurrentDoc(true, text, reverse); } }, searchCurrentDoc: function(wrapSearch, text, reverse) { if (!text) { delete this.currentSearch; return false; } var row; if (this.currentSearch && text == this.currentSearch.text) { row = this.currentSearch.findNext(wrapSearch, false, reverse, Firebug.Search.isCaseSensitive(text)); } else { if (this.editing) { this.currentSearch = new TextSearch(this.stylesheetEditor.box); row = this.currentSearch.find(text, reverse, Firebug.Search.isCaseSensitive(text)); if (row) { var sel = this.document.defaultView.getSelection(); sel.removeAllRanges(); sel.addRange(this.currentSearch.range); scrollSelectionIntoView(this); return true; } else return false; } else { function findRow(node) { return node.nodeType == 1 ? node : node.parentNode; } this.currentSearch = new TextSearch(this.panelNode, findRow); row = this.currentSearch.find(text, reverse, Firebug.Search.isCaseSensitive(text)); } } if (row) { this.document.defaultView.getSelection().selectAllChildren(row); scrollIntoCenterView(row, this.panelNode); dispatch([Firebug.A11yModel], 'onCSSSearchMatchFound', [this, text, row]); return true; } else { dispatch([Firebug.A11yModel], 'onCSSSearchMatchFound', [this, text, null]); return false; } }, getSearchOptionsMenuItems: function() { return [ Firebug.Search.searchOptionMenu("search.Case_Sensitive", "searchCaseSensitive"), Firebug.Search.searchOptionMenu("search.Multiple_Files", "searchGlobal") ]; } }); /**/ // ************************************************************************************************ function CSSElementPanel() {} CSSElementPanel.prototype = extend(Firebug.CSSStyleSheetPanel.prototype, { template: domplate( { cascadedTag: DIV({"class": "a11yCSSView", role : 'presentation'}, DIV({role : 'list', 'aria-label' : $STR('aria.labels.style rules') }, FOR("rule", "$rules", TAG("$ruleTag", {rule: "$rule"}) ) ), DIV({role : "list", 'aria-label' :$STR('aria.labels.inherited style rules')}, FOR("section", "$inherited", H1({"class": "cssInheritHeader groupHeader focusRow", role : 'listitem' }, SPAN({"class": "cssInheritLabel"}, "$inheritLabel"), TAG(FirebugReps.Element.shortTag, {object: "$section.element"}) ), DIV({role : 'group'}, FOR("rule", "$section.rules", TAG("$ruleTag", {rule: "$rule"}) ) ) ) ) ), ruleTag: isIE ? // IE needs the sourceLink first, otherwise it will be rendered outside the panel DIV({"class": "cssElementRuleContainer"}, TAG(FirebugReps.SourceLink.tag, {object: "$rule.sourceLink"}), TAG(CSSStyleRuleTag.tag, {rule: "$rule"}) ) : // other browsers need the sourceLink last, otherwise it will cause an extra space // before the rule representation DIV({"class": "cssElementRuleContainer"}, TAG(CSSStyleRuleTag.tag, {rule: "$rule"}), TAG(FirebugReps.SourceLink.tag, {object: "$rule.sourceLink"}) ) }), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * updateCascadeView: function(element) { //dispatch([Firebug.A11yModel], 'onBeforeCSSRulesAdded', [this]); var rules = [], sections = [], usedProps = {}; this.getInheritedRules(element, sections, usedProps); this.getElementRules(element, rules, usedProps); if (rules.length || sections.length) { var inheritLabel = "Inherited from"; // $STR("InheritedFrom"); var result = this.template.cascadedTag.replace({rules: rules, inherited: sections, inheritLabel: inheritLabel}, this.panelNode); //dispatch([Firebug.A11yModel], 'onCSSRulesAdded', [this, result]); } else { var result = FirebugReps.Warning.tag.replace({object: "EmptyElementCSS"}, this.panelNode); //dispatch([Firebug.A11yModel], 'onCSSRulesAdded', [this, result]); } // TODO: xxxpedro remove when there the external resource problem is fixed if (CssAnalyzer.hasExternalStyleSheet()) CssAnalyzer.externalStyleSheetWarning.tag.append({ object: "The results here may be inaccurate because some " + "stylesheets could not be loaded due to access restrictions. ", link: "more...", href: "http://getfirebug.com/wiki/index.php/Firebug_Lite_FAQ#I_keep_seeing_.22This_element_has_no_style_rules.22" }, this.panelNode); }, getStylesheetURL: function(rule) { // if the parentStyleSheet.href is null, CSS std says its inline style. // TODO: xxxpedro IE doesn't have rule.parentStyleSheet so we must fall back to the doc.location if (rule && rule.parentStyleSheet && rule.parentStyleSheet.href) return rule.parentStyleSheet.href; else return this.selection.ownerDocument.location.href; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getInheritedRules: function(element, sections, usedProps) { var parent = element.parentNode; if (parent && parent.nodeType == 1) { this.getInheritedRules(parent, sections, usedProps); var rules = []; this.getElementRules(parent, rules, usedProps, true); if (rules.length) sections.splice(0, 0, {element: parent, rules: rules}); } }, getElementRules: function(element, rules, usedProps, inheritMode) { var inspectedRules, displayedRules = {}; inspectedRules = CssAnalyzer.getElementCSSRules(element); if (inspectedRules) { for (var i = 0, length=inspectedRules.length; i < length; ++i) { var ruleId = inspectedRules[i]; var ruleData = CssAnalyzer.getRuleData(ruleId); var rule = ruleData.rule; var ssid = ruleData.styleSheetId; var parentStyleSheet = StyleSheetCache.get(ssid); var href = parentStyleSheet.externalURL ? parentStyleSheet.externalURL : parentStyleSheet.href; // Null means inline var instance = null; //var instance = getInstanceForStyleSheet(rule.parentStyleSheet, element.ownerDocument); var isSystemSheet = false; //var isSystemSheet = isSystemStyleSheet(rule.parentStyleSheet); if (!Firebug.showUserAgentCSS && isSystemSheet) // This removes user agent rules continue; if (!href) href = element.ownerDocument.location.href; // http://code.google.com/p/fbug/issues/detail?id=452 var props = this.getRuleProperties(this.context, rule, inheritMode); if (inheritMode && !props.length) continue; // //var line = domUtils.getRuleLine(rule); // TODO: xxxpedro CSS line number var line = ruleData.lineNo; var ruleId = rule.selectorText+"/"+line; var sourceLink = new SourceLink(href, line, "css", rule, instance); this.markOverridenProps(props, usedProps, inheritMode); rules.splice(0, 0, {rule: rule, id: ruleId, selector: ruleData.selector, sourceLink: sourceLink, props: props, inherited: inheritMode, isSystemSheet: isSystemSheet}); } } if (element.style) this.getStyleProperties(element, rules, usedProps, inheritMode); if (FBTrace.DBG_CSS) FBTrace.sysout("getElementRules "+rules.length+" rules for "+getElementXPath(element), rules); }, /* getElementRules: function(element, rules, usedProps, inheritMode) { var inspectedRules, displayedRules = {}; try { inspectedRules = domUtils ? domUtils.getCSSStyleRules(element) : null; } catch (exc) {} if (inspectedRules) { for (var i = 0; i < inspectedRules.Count(); ++i) { var rule = QI(inspectedRules.GetElementAt(i), nsIDOMCSSStyleRule); var href = rule.parentStyleSheet.href; // Null means inline var instance = getInstanceForStyleSheet(rule.parentStyleSheet, element.ownerDocument); var isSystemSheet = isSystemStyleSheet(rule.parentStyleSheet); if (!Firebug.showUserAgentCSS && isSystemSheet) // This removes user agent rules continue; if (!href) href = element.ownerDocument.location.href; // http://code.google.com/p/fbug/issues/detail?id=452 var props = this.getRuleProperties(this.context, rule, inheritMode); if (inheritMode && !props.length) continue; var line = domUtils.getRuleLine(rule); var ruleId = rule.selectorText+"/"+line; var sourceLink = new SourceLink(href, line, "css", rule, instance); this.markOverridenProps(props, usedProps, inheritMode); rules.splice(0, 0, {rule: rule, id: ruleId, selector: rule.selectorText, sourceLink: sourceLink, props: props, inherited: inheritMode, isSystemSheet: isSystemSheet}); } } if (element.style) this.getStyleProperties(element, rules, usedProps, inheritMode); if (FBTrace.DBG_CSS) FBTrace.sysout("getElementRules "+rules.length+" rules for "+getElementXPath(element), rules); }, /**/ markOverridenProps: function(props, usedProps, inheritMode) { for (var i = 0; i < props.length; ++i) { var prop = props[i]; if ( usedProps.hasOwnProperty(prop.name) ) { var deadProps = usedProps[prop.name]; // all previous occurrences of this property for (var j = 0; j < deadProps.length; ++j) { var deadProp = deadProps[j]; if (!deadProp.disabled && !deadProp.wasInherited && deadProp.important && !prop.important) prop.overridden = true; // new occurrence overridden else if (!prop.disabled) deadProp.overridden = true; // previous occurrences overridden } } else usedProps[prop.name] = []; prop.wasInherited = inheritMode ? true : false; usedProps[prop.name].push(prop); // all occurrences of a property seen so far, by name } }, getStyleProperties: function(element, rules, usedProps, inheritMode) { var props = this.parseCSSProps(element.style, inheritMode); this.addOldProperties(this.context, getElementXPath(element), inheritMode, props); sortProperties(props); this.markOverridenProps(props, usedProps, inheritMode); if (props.length) rules.splice(0, 0, {rule: element, id: getElementXPath(element), selector: "element.style", props: props, inherited: inheritMode}); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "css", title: "Style", parentPanel: "HTML", order: 0, initialize: function() { this.context = Firebug.chrome; // TODO: xxxpedro css2 this.document = Firebug.chrome.document; // TODO: xxxpedro css2 Firebug.CSSStyleSheetPanel.prototype.initialize.apply(this, arguments); // TODO: xxxpedro css2 var selection = ElementCache.get(Firebug.context.persistedState.selectedHTMLElementId); if (selection) this.select(selection, true); //this.updateCascadeView(document.getElementsByTagName("h1")[0]); //this.updateCascadeView(document.getElementById("build")); /* this.onStateChange = bindFixed(this.contentStateCheck, this); this.onHoverChange = bindFixed(this.contentStateCheck, this, STATE_HOVER); this.onActiveChange = bindFixed(this.contentStateCheck, this, STATE_ACTIVE); /**/ }, ishow: function(state) { }, watchWindow: function(win) { if (domUtils) { // Normally these would not be required, but in order to update after the state is set // using the options menu we need to monitor these global events as well var doc = win.document; ///addEvent(doc, "mouseover", this.onHoverChange); ///addEvent(doc, "mousedown", this.onActiveChange); } }, unwatchWindow: function(win) { var doc = win.document; ///removeEvent(doc, "mouseover", this.onHoverChange); ///removeEvent(doc, "mousedown", this.onActiveChange); if (isAncestor(this.stateChangeEl, doc)) { this.removeStateChangeHandlers(); } }, supportsObject: function(object) { return object instanceof Element ? 1 : 0; }, updateView: function(element) { this.updateCascadeView(element); if (domUtils) { this.contentState = safeGetContentState(element); this.addStateChangeHandlers(element); } }, updateSelection: function(element) { if ( !instanceOf(element , "Element") ) // html supports SourceLink return; if (sothinkInstalled) { FirebugReps.Warning.tag.replace({object: "SothinkWarning"}, this.panelNode); return; } /* if (!domUtils) { FirebugReps.Warning.tag.replace({object: "DOMInspectorWarning"}, this.panelNode); return; } /**/ if (!element) return; this.updateView(element); }, updateOption: function(name, value) { if (name == "showUserAgentCSS" || name == "expandShorthandProps") this.refresh(); }, getOptionsMenuItems: function() { var ret = [ {label: "Show User Agent CSS", type: "checkbox", checked: Firebug.showUserAgentCSS, command: bindFixed(Firebug.togglePref, Firebug, "showUserAgentCSS") }, {label: "Expand Shorthand Properties", type: "checkbox", checked: Firebug.expandShorthandProps, command: bindFixed(Firebug.togglePref, Firebug, "expandShorthandProps") } ]; if (domUtils && this.selection) { var state = safeGetContentState(this.selection); ret.push("-"); ret.push({label: ":active", type: "checkbox", checked: state & STATE_ACTIVE, command: bindFixed(this.updateContentState, this, STATE_ACTIVE, state & STATE_ACTIVE)}); ret.push({label: ":hover", type: "checkbox", checked: state & STATE_HOVER, command: bindFixed(this.updateContentState, this, STATE_HOVER, state & STATE_HOVER)}); } return ret; }, updateContentState: function(state, remove) { domUtils.setContentState(remove ? this.selection.ownerDocument.documentElement : this.selection, state); this.refresh(); }, addStateChangeHandlers: function(el) { this.removeStateChangeHandlers(); /* addEvent(el, "focus", this.onStateChange); addEvent(el, "blur", this.onStateChange); addEvent(el, "mouseup", this.onStateChange); addEvent(el, "mousedown", this.onStateChange); addEvent(el, "mouseover", this.onStateChange); addEvent(el, "mouseout", this.onStateChange); /**/ this.stateChangeEl = el; }, removeStateChangeHandlers: function() { var sel = this.stateChangeEl; if (sel) { /* removeEvent(sel, "focus", this.onStateChange); removeEvent(sel, "blur", this.onStateChange); removeEvent(sel, "mouseup", this.onStateChange); removeEvent(sel, "mousedown", this.onStateChange); removeEvent(sel, "mouseover", this.onStateChange); removeEvent(sel, "mouseout", this.onStateChange); /**/ } }, contentStateCheck: function(state) { if (!state || this.contentState & state) { var timeoutRunner = bindFixed(function() { var newState = safeGetContentState(this.selection); if (newState != this.contentState) { this.context.invalidatePanels(this.name); } }, this); // Delay exec until after the event has processed and the state has been updated setTimeout(timeoutRunner, 0); } } }); function safeGetContentState(selection) { try { return domUtils.getContentState(selection); } catch (e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("css.safeGetContentState; EXCEPTION", e); } } // ************************************************************************************************ function CSSComputedElementPanel() {} CSSComputedElementPanel.prototype = extend(CSSElementPanel.prototype, { template: domplate( { computedTag: DIV({"class": "a11yCSSView", role : "list", "aria-label" : $STR('aria.labels.computed styles')}, FOR("group", "$groups", H1({"class": "cssInheritHeader groupHeader focusRow", role : "listitem"}, SPAN({"class": "cssInheritLabel"}, "$group.title") ), TABLE({width: "100%", role : 'group'}, TBODY({role : 'presentation'}, FOR("prop", "$group.props", TR({"class": 'focusRow computedStyleRow', role : 'listitem'}, TD({"class": "stylePropName", role : 'presentation'}, "$prop.name"), TD({"class": "stylePropValue", role : 'presentation'}, "$prop.value") ) ) ) ) ) ) }), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * updateComputedView: function(element) { var win = isIE ? element.ownerDocument.parentWindow : element.ownerDocument.defaultView; var style = isIE ? element.currentStyle : win.getComputedStyle(element, ""); var groups = []; for (var groupName in styleGroups) { // TODO: xxxpedro i18n $STR //var title = $STR("StyleGroup-" + groupName); var title = styleGroupTitles[groupName]; var group = {title: title, props: []}; groups.push(group); var props = styleGroups[groupName]; for (var i = 0; i < props.length; ++i) { var propName = props[i]; var propValue = style.getPropertyValue ? style.getPropertyValue(propName) : ""+style[toCamelCase(propName)]; if (propValue === undefined || propValue === null) continue; propValue = stripUnits(rgbToHex(propValue)); if (propValue) group.props.push({name: propName, value: propValue}); } } var result = this.template.computedTag.replace({groups: groups}, this.panelNode); //dispatch([Firebug.A11yModel], 'onCSSRulesAdded', [this, result]); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "computed", title: "Computed", parentPanel: "HTML", order: 1, updateView: function(element) { this.updateComputedView(element); }, getOptionsMenuItems: function() { return [ {label: "Refresh", command: bind(this.refresh, this) } ]; } }); // ************************************************************************************************ // CSSEditor function CSSEditor(doc) { this.initializeInline(doc); } CSSEditor.prototype = domplate(Firebug.InlineEditor.prototype, { insertNewRow: function(target, insertWhere) { var rule = Firebug.getRepObject(target); var emptyProp = { // TODO: xxxpedro - uses charCode(255) to force the element being rendered, // allowing webkit to get the correct position of the property name "span", // when inserting a new CSS rule? name: "", value: "", important: "" }; if (insertWhere == "before") return CSSPropTag.tag.insertBefore({prop: emptyProp, rule: rule}, target); else return CSSPropTag.tag.insertAfter({prop: emptyProp, rule: rule}, target); }, saveEdit: function(target, value, previousValue) { // We need to check the value first in order to avoid a problem in IE8 // See Issue 3038: Empty (null) styles when adding CSS styles in Firebug Lite if (!value) return; target.innerHTML = escapeForCss(value); var row = getAncestorByClass(target, "cssProp"); if (hasClass(row, "disabledStyle")) toggleClass(row, "disabledStyle"); var rule = Firebug.getRepObject(target); if (hasClass(target, "cssPropName")) { if (value && previousValue != value) // name of property has changed. { var propValue = getChildByClass(row, "cssPropValue")[textContent]; var parsedValue = parsePriority(propValue); if (propValue && propValue != "undefined") { if (FBTrace.DBG_CSS) FBTrace.sysout("CSSEditor.saveEdit : "+previousValue+"->"+value+" = "+propValue+"\n"); if (previousValue) Firebug.CSSModule.removeProperty(rule, previousValue); Firebug.CSSModule.setProperty(rule, value, parsedValue.value, parsedValue.priority); } } else if (!value) // name of the property has been deleted, so remove the property. Firebug.CSSModule.removeProperty(rule, previousValue); } else if (getAncestorByClass(target, "cssPropValue")) { var propName = getChildByClass(row, "cssPropName")[textContent]; var propValue = getChildByClass(row, "cssPropValue")[textContent]; if (FBTrace.DBG_CSS) { FBTrace.sysout("CSSEditor.saveEdit propName=propValue: "+propName +" = "+propValue+"\n"); // FBTrace.sysout("CSSEditor.saveEdit BEFORE style:",style); } if (value && value != "null") { var parsedValue = parsePriority(value); Firebug.CSSModule.setProperty(rule, propName, parsedValue.value, parsedValue.priority); } else if (previousValue && previousValue != "null") Firebug.CSSModule.removeProperty(rule, propName); } this.panel.markChange(this.panel.name == "stylesheet"); }, advanceToNext: function(target, charCode) { if (charCode == 58 /*":"*/ && hasClass(target, "cssPropName")) return true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getAutoCompleteRange: function(value, offset) { if (hasClass(this.target, "cssPropName")) return {start: 0, end: value.length-1}; else return parseCSSValue(value, offset); }, getAutoCompleteList: function(preExpr, expr, postExpr) { if (hasClass(this.target, "cssPropName")) { return getCSSPropertyNames(); } else { var row = getAncestorByClass(this.target, "cssProp"); var propName = getChildByClass(row, "cssPropName")[textContent]; return getCSSKeywordsByProperty(propName); } } }); //************************************************************************************************ //CSSRuleEditor function CSSRuleEditor(doc) { this.initializeInline(doc); this.completeAsYouType = false; } CSSRuleEditor.uniquifier = 0; CSSRuleEditor.prototype = domplate(Firebug.InlineEditor.prototype, { insertNewRow: function(target, insertWhere) { var emptyRule = { selector: "", id: "", props: [], isSelectorEditable: true }; if (insertWhere == "before") return CSSStyleRuleTag.tag.insertBefore({rule: emptyRule}, target); else return CSSStyleRuleTag.tag.insertAfter({rule: emptyRule}, target); }, saveEdit: function(target, value, previousValue) { if (FBTrace.DBG_CSS) FBTrace.sysout("CSSRuleEditor.saveEdit: '" + value + "' '" + previousValue + "'", target); target.innerHTML = escapeForCss(value); if (value === previousValue) return; var row = getAncestorByClass(target, "cssRule"); var styleSheet = this.panel.location; styleSheet = styleSheet.editStyleSheet ? styleSheet.editStyleSheet.sheet : styleSheet; var cssRules = styleSheet.cssRules; var rule = Firebug.getRepObject(target), oldRule = rule; var ruleIndex = cssRules.length; if (rule || Firebug.getRepObject(row.nextSibling)) { var searchRule = rule || Firebug.getRepObject(row.nextSibling); for (ruleIndex=0; ruleIndex<cssRules.length && searchRule!=cssRules[ruleIndex]; ruleIndex++) {} } // Delete in all cases except for new add // We want to do this before the insert to ease change tracking if (oldRule) { Firebug.CSSModule.deleteRule(styleSheet, ruleIndex); } // Firefox does not follow the spec for the update selector text case. // When attempting to update the value, firefox will silently fail. // See https://bugzilla.mozilla.org/show_bug.cgi?id=37468 for the quite // old discussion of this bug. // As a result we need to recreate the style every time the selector // changes. if (value) { var cssText = [ value, "{" ]; var props = row.getElementsByClassName("cssProp"); for (var i = 0; i < props.length; i++) { var propEl = props[i]; if (!hasClass(propEl, "disabledStyle")) { cssText.push(getChildByClass(propEl, "cssPropName")[textContent]); cssText.push(":"); cssText.push(getChildByClass(propEl, "cssPropValue")[textContent]); cssText.push(";"); } } cssText.push("}"); cssText = cssText.join(""); try { var insertLoc = Firebug.CSSModule.insertRule(styleSheet, cssText, ruleIndex); rule = cssRules[insertLoc]; ruleIndex++; } catch (err) { if (FBTrace.DBG_CSS || FBTrace.DBG_ERRORS) FBTrace.sysout("CSS Insert Error: "+err, err); target.innerHTML = escapeForCss(previousValue); row.repObject = undefined; return; } } else { rule = undefined; } // Update the rep object row.repObject = rule; if (!oldRule) { // Who knows what the domutils will return for rule line // for a recently created rule. To be safe we just generate // a unique value as this is only used as an internal key. var ruleId = "new/"+value+"/"+(++CSSRuleEditor.uniquifier); row.setAttribute("ruleId", ruleId); } this.panel.markChange(this.panel.name == "stylesheet"); } }); // ************************************************************************************************ // StyleSheetEditor function StyleSheetEditor(doc) { this.box = this.tag.replace({}, doc, this); this.input = this.box.firstChild; } StyleSheetEditor.prototype = domplate(Firebug.BaseEditor, { multiLine: true, tag: DIV( TEXTAREA({"class": "styleSheetEditor fullPanelEditor", oninput: "$onInput"}) ), getValue: function() { return this.input.value; }, setValue: function(value) { return this.input.value = value; }, show: function(target, panel, value, textSize, targetSize) { this.target = target; this.panel = panel; this.panel.panelNode.appendChild(this.box); this.input.value = value; this.input.focus(); var command = Firebug.chrome.$("cmd_toggleCSSEditing"); command.setAttribute("checked", true); }, hide: function() { var command = Firebug.chrome.$("cmd_toggleCSSEditing"); command.setAttribute("checked", false); if (this.box.parentNode == this.panel.panelNode) this.panel.panelNode.removeChild(this.box); delete this.target; delete this.panel; delete this.styleSheet; }, saveEdit: function(target, value, previousValue) { Firebug.CSSModule.freeEdit(this.styleSheet, value); }, endEditing: function() { this.panel.refresh(); return true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onInput: function() { Firebug.Editor.update(); }, scrollToLine: function(line, offset) { this.startMeasuring(this.input); var lineHeight = this.measureText().height; this.stopMeasuring(); this.input.scrollTop = (line * lineHeight) + offset; } }); // ************************************************************************************************ // Local Helpers var rgbToHex = function rgbToHex(value) { return value.replace(/\brgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/gi, rgbToHexReplacer); }; var rgbToHexReplacer = function(_, r, g, b) { return '#' + ((1 << 24) + (r << 16) + (g << 8) + (b << 0)).toString(16).substr(-6).toUpperCase(); }; var stripUnits = function stripUnits(value) { // remove units from '0px', '0em' etc. leave non-zero units in-tact. return value.replace(/(url\(.*?\)|[^0]\S*\s*)|0(%|em|ex|px|in|cm|mm|pt|pc)(\s|$)/gi, stripUnitsReplacer); }; var stripUnitsReplacer = function(_, skip, remove, whitespace) { return skip || ('0' + whitespace); }; function parsePriority(value) { var rePriority = /(.*?)\s*(!important)?$/; var m = rePriority.exec(value); var propValue = m ? m[1] : ""; var priority = m && m[2] ? "important" : ""; return {value: propValue, priority: priority}; } function parseURLValue(value) { var m = reURL.exec(value); return m ? m[1] : ""; } function parseRepeatValue(value) { var m = reRepeat.exec(value); return m ? m[0] : ""; } function parseCSSValue(value, offset) { var start = 0; var m; while (1) { m = reSplitCSS.exec(value); if (m && m.index+m[0].length < offset) { value = value.substr(m.index+m[0].length); start += m.index+m[0].length; offset -= m.index+m[0].length; } else break; } if (m) { var type; if (m[1]) type = "url"; else if (m[2] || m[3]) type = "rgb"; else if (m[4]) type = "int"; return {value: m[0], start: start+m.index, end: start+m.index+(m[0].length-1), type: type}; } } function findPropByName(props, name) { for (var i = 0; i < props.length; ++i) { if (props[i].name == name) return i; } } function sortProperties(props) { props.sort(function(a, b) { return a.name > b.name ? 1 : -1; }); } function getTopmostRuleLine(panelNode) { for (var child = panelNode.firstChild; child; child = child.nextSibling) { if (child.offsetTop+child.offsetHeight > panelNode.scrollTop) { var rule = child.repObject; if (rule) return { line: domUtils.getRuleLine(rule), offset: panelNode.scrollTop-child.offsetTop }; } } return 0; } function getStyleSheetCSS(sheet, context) { if (sheet.ownerNode instanceof HTMLStyleElement) return sheet.ownerNode.innerHTML; else return context.sourceCache.load(sheet.href).join(""); } function getStyleSheetOwnerNode(sheet) { for (; sheet && !sheet.ownerNode; sheet = sheet.parentStyleSheet); return sheet.ownerNode; } function scrollSelectionIntoView(panel) { var selCon = getSelectionController(panel); selCon.scrollSelectionIntoView( nsISelectionController.SELECTION_NORMAL, nsISelectionController.SELECTION_FOCUS_REGION, true); } function getSelectionController(panel) { var browser = Firebug.chrome.getPanelBrowser(panel); return browser.docShell.QueryInterface(nsIInterfaceRequestor) .getInterface(nsISelectionDisplay) .QueryInterface(nsISelectionController); } // ************************************************************************************************ Firebug.registerModule(Firebug.CSSModule); Firebug.registerPanel(Firebug.CSSStyleSheetPanel); Firebug.registerPanel(CSSElementPanel); Firebug.registerPanel(CSSComputedElementPanel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Script Module Firebug.Script = extend(Firebug.Module, { getPanel: function() { return Firebug.chrome ? Firebug.chrome.getPanel("Script") : null; }, selectSourceCode: function(index) { this.getPanel().selectSourceCode(index); } }); Firebug.registerModule(Firebug.Script); // ************************************************************************************************ // Script Panel function ScriptPanel(){}; ScriptPanel.prototype = extend(Firebug.Panel, { name: "Script", title: "Script", selectIndex: 0, // index of the current selectNode's option sourceIndex: -1, // index of the script node, based in doc.getElementsByTagName("script") options: { hasToolButtons: true }, create: function() { Firebug.Panel.create.apply(this, arguments); this.onChangeSelect = bind(this.onChangeSelect, this); var doc = Firebug.browser.document; var scripts = doc.getElementsByTagName("script"); var selectNode = this.selectNode = createElement("select"); for(var i=0, script; script=scripts[i]; i++) { // Don't show Firebug Lite source code in the list of options if (Firebug.ignoreFirebugElements && script.getAttribute("firebugIgnore")) continue; var fileName = getFileName(script.src) || getFileName(doc.location.href); var option = createElement("option", {value:i}); option.appendChild(Firebug.chrome.document.createTextNode(fileName)); selectNode.appendChild(option); }; this.toolButtonsNode.appendChild(selectNode); }, initialize: function() { // we must render the code first, so the persistent state can be restore this.selectSourceCode(this.selectIndex); Firebug.Panel.initialize.apply(this, arguments); addEvent(this.selectNode, "change", this.onChangeSelect); }, shutdown: function() { removeEvent(this.selectNode, "change", this.onChangeSelect); Firebug.Panel.shutdown.apply(this, arguments); }, detach: function(oldChrome, newChrome) { Firebug.Panel.detach.apply(this, arguments); var oldPanel = oldChrome.getPanel("Script"); var index = oldPanel.selectIndex; this.selectNode.selectedIndex = index; this.selectIndex = index; this.sourceIndex = -1; }, onChangeSelect: function(event) { var select = this.selectNode; this.selectIndex = select.selectedIndex; var option = select.options[select.selectedIndex]; if (!option) return; var selectedSourceIndex = parseInt(option.value); this.renderSourceCode(selectedSourceIndex); }, selectSourceCode: function(index) { var select = this.selectNode; select.selectedIndex = index; var option = select.options[index]; if (!option) return; var selectedSourceIndex = parseInt(option.value); this.renderSourceCode(selectedSourceIndex); }, renderSourceCode: function(index) { if (this.sourceIndex != index) { var renderProcess = function renderProcess(src) { var html = [], hl = 0; src = isIE && !isExternal ? src+'\n' : // IE put an extra line when reading source of local resources '\n'+src; // find the number of lines of code src = src.replace(/\n\r|\r\n/g, "\n"); var match = src.match(/[\n]/g); var lines=match ? match.length : 0; // render the full source code + line numbers html html[hl++] = '<div><div class="sourceBox" style="left:'; html[hl++] = 35 + 7*(lines+'').length; html[hl++] = 'px;"><pre class="sourceCode">'; html[hl++] = escapeHTML(src); html[hl++] = '</pre></div><div class="lineNo">'; // render the line number divs for(var l=1, lines; l<=lines; l++) { html[hl++] = '<div line="'; html[hl++] = l; html[hl++] = '">'; html[hl++] = l; html[hl++] = '</div>'; } html[hl++] = '</div></div>'; updatePanel(html); }; var updatePanel = function(html) { self.panelNode.innerHTML = html.join(""); // IE needs this timeout, otherwise the panel won't scroll setTimeout(function(){ self.synchronizeUI(); },0); }; var onFailure = function() { FirebugReps.Warning.tag.replace({object: "AccessRestricted"}, self.panelNode); }; var self = this; var doc = Firebug.browser.document; var script = doc.getElementsByTagName("script")[index]; var url = getScriptURL(script); var isExternal = url && url != doc.location.href; try { if (Firebug.disableResourceFetching) { renderProcess(Firebug.Lite.Proxy.fetchResourceDisabledMessage); } else if (isExternal) { Ajax.request({url: url, onSuccess: renderProcess, onFailure: onFailure}); } else { var src = script.innerHTML; renderProcess(src); } } catch(e) { onFailure(); } this.sourceIndex = index; } } }); Firebug.registerPanel(ScriptPanel); // ************************************************************************************************ var getScriptURL = function getScriptURL(script) { var reFile = /([^\/\?#]+)(#.+)?$/; var rePath = /^(.*\/)/; var reProtocol = /^\w+:\/\//; var path = null; var doc = Firebug.browser.document; var file = reFile.exec(script.src); if (file) { var fileName = file[1]; var fileOptions = file[2]; // absolute path if (reProtocol.test(script.src)) { path = rePath.exec(script.src)[1]; } // relative path else { var r = rePath.exec(script.src); var src = r ? r[1] : script.src; var backDir = /^((?:\.\.\/)+)(.*)/.exec(src); var reLastDir = /^(.*\/)[^\/]+\/$/; path = rePath.exec(doc.location.href)[1]; // "../some/path" if (backDir) { var j = backDir[1].length/3; var p; while (j-- > 0) path = reLastDir.exec(path)[1]; path += backDir[2]; } else if(src.indexOf("/") != -1) { // "./some/path" if(/^\.\/./.test(src)) { path += src.substring(2); } // "/some/path" else if(/^\/./.test(src)) { var domain = /^(\w+:\/\/[^\/]+)/.exec(path); path = domain[1] + src; } // "some/path" else { path += src; } } } } var m = path && path.match(/([^\/]+)\/$/) || null; if (path && m) { return path + fileName; } }; var getFileName = function getFileName(path) { if (!path) return ""; var match = path && path.match(/[^\/]+(\?.*)?(#.*)?$/); return match && match[0] || path; }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var ElementCache = Firebug.Lite.Cache.Element; var insertSliceSize = 18; var insertInterval = 40; var ignoreVars = { "__firebug__": 1, "eval": 1, // We are forced to ignore Java-related variables, because // trying to access them causes browser freeze "java": 1, "sun": 1, "Packages": 1, "JavaArray": 1, "JavaMember": 1, "JavaObject": 1, "JavaClass": 1, "JavaPackage": 1, "_firebug": 1, "_FirebugConsole": 1, "_FirebugCommandLine": 1 }; if (Firebug.ignoreFirebugElements) ignoreVars[Firebug.Lite.Cache.ID] = 1; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var memberPanelRep = isIE6 ? {"class": "memberLabel $member.type\\Label", href: "javacript:void(0)"} : {"class": "memberLabel $member.type\\Label"}; var RowTag = TR({"class": "memberRow $member.open $member.type\\Row", $hasChildren: "$member.hasChildren", role : 'presentation', level: "$member.level"}, TD({"class": "memberLabelCell", style: "padding-left: $member.indent\\px", role : 'presentation'}, A(memberPanelRep, SPAN({}, "$member.name") ) ), TD({"class": "memberValueCell", role : 'presentation'}, TAG("$member.tag", {object: "$member.value"}) ) ); var WatchRowTag = TR({"class": "watchNewRow", level: 0}, TD({"class": "watchEditCell", colspan: 2}, DIV({"class": "watchEditBox a11yFocusNoTab", role: "button", 'tabindex' : '0', 'aria-label' : $STR('press enter to add new watch expression')}, $STR("NewWatch") ) ) ); var SizerRow = TR({role : 'presentation'}, TD({width: "30%"}), TD({width: "70%"}) ); var domTableClass = isIElt8 ? "domTable domTableIE" : "domTable"; var DirTablePlate = domplate(Firebug.Rep, { tag: TABLE({"class": domTableClass, cellpadding: 0, cellspacing: 0, onclick: "$onClick", role :"tree"}, TBODY({role: 'presentation'}, SizerRow, FOR("member", "$object|memberIterator", RowTag) ) ), watchTag: TABLE({"class": domTableClass, cellpadding: 0, cellspacing: 0, _toggles: "$toggles", _domPanel: "$domPanel", onclick: "$onClick", role : 'tree'}, TBODY({role : 'presentation'}, SizerRow, WatchRowTag ) ), tableTag: TABLE({"class": domTableClass, cellpadding: 0, cellspacing: 0, _toggles: "$toggles", _domPanel: "$domPanel", onclick: "$onClick", role : 'tree'}, TBODY({role : 'presentation'}, SizerRow ) ), rowTag: FOR("member", "$members", RowTag), memberIterator: function(object, level) { return getMembers(object, level); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onClick: function(event) { if (!isLeftClick(event)) return; var target = event.target || event.srcElement; var row = getAncestorByClass(target, "memberRow"); var label = getAncestorByClass(target, "memberLabel"); if (label && hasClass(row, "hasChildren")) { var row = label.parentNode.parentNode; this.toggleRow(row); } else { var object = Firebug.getRepObject(target); if (typeof(object) == "function") { Firebug.chrome.select(object, "script"); cancelEvent(event); } else if (event.detail == 2 && !object) { var panel = row.parentNode.parentNode.domPanel; if (panel) { var rowValue = panel.getRowPropertyValue(row); if (typeof(rowValue) == "boolean") panel.setPropertyValue(row, !rowValue); else panel.editProperty(row); cancelEvent(event); } } } return false; }, toggleRow: function(row) { var level = parseInt(row.getAttribute("level")); var toggles = row.parentNode.parentNode.toggles; if (hasClass(row, "opened")) { removeClass(row, "opened"); if (toggles) { var path = getPath(row); // Remove the path from the toggle tree for (var i = 0; i < path.length; ++i) { if (i == path.length-1) delete toggles[path[i]]; else toggles = toggles[path[i]]; } } var rowTag = this.rowTag; var tbody = row.parentNode; setTimeout(function() { for (var firstRow = row.nextSibling; firstRow; firstRow = row.nextSibling) { if (parseInt(firstRow.getAttribute("level")) <= level) break; tbody.removeChild(firstRow); } }, row.insertTimeout ? row.insertTimeout : 0); } else { setClass(row, "opened"); if (toggles) { var path = getPath(row); // Mark the path in the toggle tree for (var i = 0; i < path.length; ++i) { var name = path[i]; if (toggles.hasOwnProperty(name)) toggles = toggles[name]; else toggles = toggles[name] = {}; } } var value = row.lastChild.firstChild.repObject; var members = getMembers(value, level+1); var rowTag = this.rowTag; var lastRow = row; var delay = 0; //var setSize = members.length; //var rowCount = 1; while (members.length) { with({slice: members.splice(0, insertSliceSize), isLast: !members.length}) { setTimeout(function() { if (lastRow.parentNode) { var result = rowTag.insertRows({members: slice}, lastRow); lastRow = result[1]; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [null, result, rowCount, setSize]); //rowCount += insertSliceSize; } if (isLast) row.removeAttribute("insertTimeout"); }, delay); } delay += insertInterval; } row.insertTimeout = delay; } } }); // ************************************************************************************************ Firebug.DOMBasePanel = function() {}; Firebug.DOMBasePanel.prototype = extend(Firebug.Panel, { tag: DirTablePlate.tableTag, getRealObject: function(object) { // TODO: Move this to some global location // TODO: Unwrapping should be centralized rather than sprinkling it around ad hoc. // TODO: We might be able to make this check more authoritative with QueryInterface. if (!object) return object; if (object.wrappedJSObject) return object.wrappedJSObject; return object; }, rebuild: function(update, scrollTop) { //dispatch([Firebug.A11yModel], 'onBeforeDomUpdateSelection', [this]); var members = getMembers(this.selection); expandMembers(members, this.toggles, 0, 0); this.showMembers(members, update, scrollTop); //TODO: xxxpedro statusbar if (!this.parentPanel) updateStatusBar(this); }, showMembers: function(members, update, scrollTop) { // If we are still in the midst of inserting rows, cancel all pending // insertions here - this is a big speedup when stepping in the debugger if (this.timeouts) { for (var i = 0; i < this.timeouts.length; ++i) this.context.clearTimeout(this.timeouts[i]); delete this.timeouts; } if (!members.length) return this.showEmptyMembers(); var panelNode = this.panelNode; var priorScrollTop = scrollTop == undefined ? panelNode.scrollTop : scrollTop; // If we are asked to "update" the current view, then build the new table // offscreen and swap it in when it's done var offscreen = update && panelNode.firstChild; var dest = offscreen ? panelNode.ownerDocument : panelNode; var table = this.tag.replace({domPanel: this, toggles: this.toggles}, dest); var tbody = table.lastChild; var rowTag = DirTablePlate.rowTag; // Insert the first slice immediately //var slice = members.splice(0, insertSliceSize); //var result = rowTag.insertRows({members: slice}, tbody.lastChild); //var setSize = members.length; //var rowCount = 1; var panel = this; var result; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [panel, result, rowCount, setSize]); var timeouts = []; var delay = 0; // enable to measure rendering performance var renderStart = new Date().getTime(); while (members.length) { with({slice: members.splice(0, insertSliceSize), isLast: !members.length}) { timeouts.push(this.context.setTimeout(function() { // TODO: xxxpedro can this be a timing error related to the // "iteration number" approach insted of "duration time"? // avoid error in IE8 if (!tbody.lastChild) return; result = rowTag.insertRows({members: slice}, tbody.lastChild); //rowCount += insertSliceSize; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [panel, result, rowCount, setSize]); if ((panelNode.scrollHeight+panelNode.offsetHeight) >= priorScrollTop) panelNode.scrollTop = priorScrollTop; // enable to measure rendering performance //if (isLast) alert(new Date().getTime() - renderStart + "ms"); }, delay)); delay += insertInterval; } } if (offscreen) { timeouts.push(this.context.setTimeout(function() { if (panelNode.firstChild) panelNode.replaceChild(table, panelNode.firstChild); else panelNode.appendChild(table); // Scroll back to where we were before panelNode.scrollTop = priorScrollTop; }, delay)); } else { timeouts.push(this.context.setTimeout(function() { panelNode.scrollTop = scrollTop == undefined ? 0 : scrollTop; }, delay)); } this.timeouts = timeouts; }, /* // new showMembers: function(members, update, scrollTop) { // If we are still in the midst of inserting rows, cancel all pending // insertions here - this is a big speedup when stepping in the debugger if (this.timeouts) { for (var i = 0; i < this.timeouts.length; ++i) this.context.clearTimeout(this.timeouts[i]); delete this.timeouts; } if (!members.length) return this.showEmptyMembers(); var panelNode = this.panelNode; var priorScrollTop = scrollTop == undefined ? panelNode.scrollTop : scrollTop; // If we are asked to "update" the current view, then build the new table // offscreen and swap it in when it's done var offscreen = update && panelNode.firstChild; var dest = offscreen ? panelNode.ownerDocument : panelNode; var table = this.tag.replace({domPanel: this, toggles: this.toggles}, dest); var tbody = table.lastChild; var rowTag = DirTablePlate.rowTag; // Insert the first slice immediately //var slice = members.splice(0, insertSliceSize); //var result = rowTag.insertRows({members: slice}, tbody.lastChild); //var setSize = members.length; //var rowCount = 1; var panel = this; var result; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [panel, result, rowCount, setSize]); var timeouts = []; var delay = 0; var _insertSliceSize = insertSliceSize; var _insertInterval = insertInterval; // enable to measure rendering performance var renderStart = new Date().getTime(); var lastSkip = renderStart, now; while (members.length) { with({slice: members.splice(0, _insertSliceSize), isLast: !members.length}) { var _tbody = tbody; var _rowTag = rowTag; var _panelNode = panelNode; var _priorScrollTop = priorScrollTop; timeouts.push(this.context.setTimeout(function() { // TODO: xxxpedro can this be a timing error related to the // "iteration number" approach insted of "duration time"? // avoid error in IE8 if (!_tbody.lastChild) return; result = _rowTag.insertRows({members: slice}, _tbody.lastChild); //rowCount += _insertSliceSize; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [panel, result, rowCount, setSize]); if ((_panelNode.scrollHeight + _panelNode.offsetHeight) >= _priorScrollTop) _panelNode.scrollTop = _priorScrollTop; // enable to measure rendering performance //alert("gap: " + (new Date().getTime() - lastSkip)); //lastSkip = new Date().getTime(); //if (isLast) alert("new: " + (new Date().getTime() - renderStart) + "ms"); }, delay)); delay += _insertInterval; } } if (offscreen) { timeouts.push(this.context.setTimeout(function() { if (panelNode.firstChild) panelNode.replaceChild(table, panelNode.firstChild); else panelNode.appendChild(table); // Scroll back to where we were before panelNode.scrollTop = priorScrollTop; }, delay)); } else { timeouts.push(this.context.setTimeout(function() { panelNode.scrollTop = scrollTop == undefined ? 0 : scrollTop; }, delay)); } this.timeouts = timeouts; }, /**/ showEmptyMembers: function() { FirebugReps.Warning.tag.replace({object: "NoMembersWarning"}, this.panelNode); }, findPathObject: function(object) { var pathIndex = -1; for (var i = 0; i < this.objectPath.length; ++i) { // IE needs === instead of == or otherwise some objects will // be considered equal to different objects, returning the // wrong index of the objectPath array if (this.getPathObject(i) === object) return i; } return -1; }, getPathObject: function(index) { var object = this.objectPath[index]; if (object instanceof Property) return object.getObject(); else return object; }, getRowObject: function(row) { var object = getRowOwnerObject(row); return object ? object : this.selection; }, getRowPropertyValue: function(row) { var object = this.getRowObject(row); object = this.getRealObject(object); if (object) { var propName = getRowName(row); if (object instanceof jsdIStackFrame) return Firebug.Debugger.evaluate(propName, this.context); else return object[propName]; } }, /* copyProperty: function(row) { var value = this.getRowPropertyValue(row); copyToClipboard(value); }, editProperty: function(row, editValue) { if (hasClass(row, "watchNewRow")) { if (this.context.stopped) Firebug.Editor.startEditing(row, ""); else if (Firebug.Console.isAlwaysEnabled()) // not stopped in debugger, need command line { if (Firebug.CommandLine.onCommandLineFocus()) Firebug.Editor.startEditing(row, ""); else row.innerHTML = $STR("warning.Command line blocked?"); } else row.innerHTML = $STR("warning.Console must be enabled"); } else if (hasClass(row, "watchRow")) Firebug.Editor.startEditing(row, getRowName(row)); else { var object = this.getRowObject(row); this.context.thisValue = object; if (!editValue) { var propValue = this.getRowPropertyValue(row); var type = typeof(propValue); if (type == "undefined" || type == "number" || type == "boolean") editValue = propValue; else if (type == "string") editValue = "\"" + escapeJS(propValue) + "\""; else if (propValue == null) editValue = "null"; else if (object instanceof Window || object instanceof jsdIStackFrame) editValue = getRowName(row); else editValue = "this." + getRowName(row); } Firebug.Editor.startEditing(row, editValue); } }, deleteProperty: function(row) { if (hasClass(row, "watchRow")) this.deleteWatch(row); else { var object = getRowOwnerObject(row); if (!object) object = this.selection; object = this.getRealObject(object); if (object) { var name = getRowName(row); try { delete object[name]; } catch (exc) { return; } this.rebuild(true); this.markChange(); } } }, setPropertyValue: function(row, value) // value must be string { if(FBTrace.DBG_DOM) { FBTrace.sysout("row: "+row); FBTrace.sysout("value: "+value+" type "+typeof(value), value); } var name = getRowName(row); if (name == "this") return; var object = this.getRowObject(row); object = this.getRealObject(object); if (object && !(object instanceof jsdIStackFrame)) { // unwrappedJSObject.property = unwrappedJSObject Firebug.CommandLine.evaluate(value, this.context, object, this.context.getGlobalScope(), function success(result, context) { if (FBTrace.DBG_DOM) FBTrace.sysout("setPropertyValue evaluate success object["+name+"]="+result+" type "+typeof(result), result); object[name] = result; }, function failed(exc, context) { try { if (FBTrace.DBG_DOM) FBTrace.sysout("setPropertyValue evaluate failed with exc:"+exc+" object["+name+"]="+value+" type "+typeof(value), exc); // If the value doesn't parse, then just store it as a string. Some users will // not realize they're supposed to enter a JavaScript expression and just type // literal text object[name] = String(value); // unwrappedJSobject.property = string } catch (exc) { return; } } ); } else if (this.context.stopped) { try { Firebug.CommandLine.evaluate(name+"="+value, this.context); } catch (exc) { try { // See catch block above... object[name] = String(value); // unwrappedJSobject.property = string } catch (exc) { return; } } } this.rebuild(true); this.markChange(); }, highlightRow: function(row) { if (this.highlightedRow) cancelClassTimed(this.highlightedRow, "jumpHighlight", this.context); this.highlightedRow = row; if (row) setClassTimed(row, "jumpHighlight", this.context); },/**/ onMouseMove: function(event) { var target = event.srcElement || event.target; var object = getAncestorByClass(target, "objectLink-element"); object = object ? object.repObject : null; if(object && instanceOf(object, "Element") && object.nodeType == 1) { if(object != lastHighlightedObject) { Firebug.Inspector.drawBoxModel(object); object = lastHighlightedObject; } } else Firebug.Inspector.hideBoxModel(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel create: function() { // TODO: xxxpedro this.context = Firebug.browser; this.objectPath = []; this.propertyPath = []; this.viewPath = []; this.pathIndex = -1; this.toggles = {}; Firebug.Panel.create.apply(this, arguments); this.panelNode.style.padding = "0 1px"; }, initialize: function(){ Firebug.Panel.initialize.apply(this, arguments); addEvent(this.panelNode, "mousemove", this.onMouseMove); }, shutdown: function() { removeEvent(this.panelNode, "mousemove", this.onMouseMove); Firebug.Panel.shutdown.apply(this, arguments); }, /* destroy: function(state) { var view = this.viewPath[this.pathIndex]; if (view && this.panelNode.scrollTop) view.scrollTop = this.panelNode.scrollTop; if (this.pathIndex) state.pathIndex = this.pathIndex; if (this.viewPath) state.viewPath = this.viewPath; if (this.propertyPath) state.propertyPath = this.propertyPath; if (this.propertyPath.length > 0 && !this.propertyPath[1]) state.firstSelection = persistObject(this.getPathObject(1), this.context); Firebug.Panel.destroy.apply(this, arguments); }, /**/ ishow: function(state) { if (this.context.loaded && !this.selection) { if (!state) { this.select(null); return; } if (state.viewPath) this.viewPath = state.viewPath; if (state.propertyPath) this.propertyPath = state.propertyPath; var defaultObject = this.getDefaultSelection(this.context); var selectObject = defaultObject; if (state.firstSelection) { var restored = state.firstSelection(this.context); if (restored) { selectObject = restored; this.objectPath = [defaultObject, restored]; } else this.objectPath = [defaultObject]; } else this.objectPath = [defaultObject]; if (this.propertyPath.length > 1) { for (var i = 1; i < this.propertyPath.length; ++i) { var name = this.propertyPath[i]; if (!name) continue; var object = selectObject; try { selectObject = object[name]; } catch (exc) { selectObject = null; } if (selectObject) { this.objectPath.push(new Property(object, name)); } else { // If we can't access a property, just stop this.viewPath.splice(i); this.propertyPath.splice(i); this.objectPath.splice(i); selectObject = this.getPathObject(this.objectPath.length-1); break; } } } var selection = state.pathIndex <= this.objectPath.length-1 ? this.getPathObject(state.pathIndex) : this.getPathObject(this.objectPath.length-1); this.select(selection); } }, /* hide: function() { var view = this.viewPath[this.pathIndex]; if (view && this.panelNode.scrollTop) view.scrollTop = this.panelNode.scrollTop; }, /**/ supportsObject: function(object) { if (object == null) return 1000; if (typeof(object) == "undefined") return 1000; else if (object instanceof SourceLink) return 0; else return 1; // just agree to support everything but not agressively. }, refresh: function() { this.rebuild(true); }, updateSelection: function(object) { var previousIndex = this.pathIndex; var previousView = previousIndex == -1 ? null : this.viewPath[previousIndex]; var newPath = this.pathToAppend; delete this.pathToAppend; var pathIndex = this.findPathObject(object); if (newPath || pathIndex == -1) { this.toggles = {}; if (newPath) { // Remove everything after the point where we are inserting, so we // essentially replace it with the new path if (previousView) { if (this.panelNode.scrollTop) previousView.scrollTop = this.panelNode.scrollTop; var start = previousIndex + 1, // Opera needs the length argument in splice(), otherwise // it will consider that only one element should be removed length = this.objectPath.length - start; this.objectPath.splice(start, length); this.propertyPath.splice(start, length); this.viewPath.splice(start, length); } var value = this.getPathObject(previousIndex); if (!value) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("dom.updateSelection no pathObject for "+previousIndex+"\n"); return; } for (var i = 0, length = newPath.length; i < length; ++i) { var name = newPath[i]; var object = value; try { value = value[name]; } catch(exc) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("dom.updateSelection FAILS at path_i="+i+" for name:"+name+"\n"); return; } ++this.pathIndex; this.objectPath.push(new Property(object, name)); this.propertyPath.push(name); this.viewPath.push({toggles: this.toggles, scrollTop: 0}); } } else { this.toggles = {}; var win = Firebug.browser.window; //var win = this.context.getGlobalScope(); if (object === win) { this.pathIndex = 0; this.objectPath = [win]; this.propertyPath = [null]; this.viewPath = [{toggles: this.toggles, scrollTop: 0}]; } else { this.pathIndex = 1; this.objectPath = [win, object]; this.propertyPath = [null, null]; this.viewPath = [ {toggles: {}, scrollTop: 0}, {toggles: this.toggles, scrollTop: 0} ]; } } this.panelNode.scrollTop = 0; this.rebuild(); } else { this.pathIndex = pathIndex; var view = this.viewPath[pathIndex]; this.toggles = view.toggles; // Persist the current scroll location if (previousView && this.panelNode.scrollTop) previousView.scrollTop = this.panelNode.scrollTop; this.rebuild(false, view.scrollTop); } }, getObjectPath: function(object) { return this.objectPath; }, getDefaultSelection: function() { return Firebug.browser.window; //return this.context.getGlobalScope(); }/*, updateOption: function(name, value) { const optionMap = {showUserProps: 1, showUserFuncs: 1, showDOMProps: 1, showDOMFuncs: 1, showDOMConstants: 1}; if ( optionMap.hasOwnProperty(name) ) this.rebuild(true); }, getOptionsMenuItems: function() { return [ optionMenu("ShowUserProps", "showUserProps"), optionMenu("ShowUserFuncs", "showUserFuncs"), optionMenu("ShowDOMProps", "showDOMProps"), optionMenu("ShowDOMFuncs", "showDOMFuncs"), optionMenu("ShowDOMConstants", "showDOMConstants"), "-", {label: "Refresh", command: bindFixed(this.rebuild, this, true) } ]; }, getContextMenuItems: function(object, target) { var row = getAncestorByClass(target, "memberRow"); var items = []; if (row) { var rowName = getRowName(row); var rowObject = this.getRowObject(row); var rowValue = this.getRowPropertyValue(row); var isWatch = hasClass(row, "watchRow"); var isStackFrame = rowObject instanceof jsdIStackFrame; if (typeof(rowValue) == "string" || typeof(rowValue) == "number") { // Functions already have a copy item in their context menu items.push( "-", {label: "CopyValue", command: bindFixed(this.copyProperty, this, row) } ); } items.push( "-", {label: isWatch ? "EditWatch" : (isStackFrame ? "EditVariable" : "EditProperty"), command: bindFixed(this.editProperty, this, row) } ); if (isWatch || (!isStackFrame && !isDOMMember(rowObject, rowName))) { items.push( {label: isWatch ? "DeleteWatch" : "DeleteProperty", command: bindFixed(this.deleteProperty, this, row) } ); } } items.push( "-", {label: "Refresh", command: bindFixed(this.rebuild, this, true) } ); return items; }, getEditor: function(target, value) { if (!this.editor) this.editor = new DOMEditor(this.document); return this.editor; }/**/ }); // ************************************************************************************************ // TODO: xxxpedro statusbar var updateStatusBar = function(panel) { var path = panel.propertyPath; var index = panel.pathIndex; var r = []; for (var i=0, l=path.length; i<l; i++) { r.push(i==index ? '<a class="fbHover fbButton fbBtnSelected" ' : '<a class="fbHover fbButton" '); r.push('pathIndex='); r.push(i); if(isIE6) r.push(' href="javascript:void(0)"'); r.push('>'); r.push(i==0 ? "window" : path[i] || "Object"); r.push('</a>'); if(i < l-1) r.push('<span class="fbStatusSeparator">&gt;</span>'); } panel.statusBarNode.innerHTML = r.join(""); }; var DOMMainPanel = Firebug.DOMPanel = function () {}; Firebug.DOMPanel.DirTable = DirTablePlate; DOMMainPanel.prototype = extend(Firebug.DOMBasePanel.prototype, { onClickStatusBar: function(event) { var target = event.srcElement || event.target; var element = getAncestorByClass(target, "fbHover"); if(element) { var pathIndex = element.getAttribute("pathIndex"); if(pathIndex) { this.select(this.getPathObject(pathIndex)); } } }, selectRow: function(row, target) { if (!target) target = row.lastChild.firstChild; if (!target || !target.repObject) return; this.pathToAppend = getPath(row); // If the object is inside an array, look up its index var valueBox = row.lastChild.firstChild; if (hasClass(valueBox, "objectBox-array")) { var arrayIndex = FirebugReps.Arr.getItemIndex(target); this.pathToAppend.push(arrayIndex); } // Make sure we get a fresh status path for the object, since otherwise // it might find the object in the existing path and not refresh it //Firebug.chrome.clearStatusPath(); this.select(target.repObject, true); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onClick: function(event) { var target = event.srcElement || event.target; var repNode = Firebug.getRepNode(target); if (repNode) { var row = getAncestorByClass(target, "memberRow"); if (row) { this.selectRow(row, repNode); cancelEvent(event); } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "DOM", title: "DOM", searchable: true, statusSeparator: ">", options: { hasToolButtons: true, hasStatusBar: true }, create: function() { Firebug.DOMBasePanel.prototype.create.apply(this, arguments); this.onClick = bind(this.onClick, this); //TODO: xxxpedro this.onClickStatusBar = bind(this.onClickStatusBar, this); this.panelNode.style.padding = "0 1px"; }, initialize: function(oldPanelNode) { //this.panelNode.addEventListener("click", this.onClick, false); //dispatch([Firebug.A11yModel], 'onInitializeNode', [this, 'console']); Firebug.DOMBasePanel.prototype.initialize.apply(this, arguments); addEvent(this.panelNode, "click", this.onClick); // TODO: xxxpedro dom this.ishow(); //TODO: xxxpedro addEvent(this.statusBarNode, "click", this.onClickStatusBar); }, shutdown: function() { //this.panelNode.removeEventListener("click", this.onClick, false); //dispatch([Firebug.A11yModel], 'onDestroyNode', [this, 'console']); removeEvent(this.panelNode, "click", this.onClick); Firebug.DOMBasePanel.prototype.shutdown.apply(this, arguments); }/*, search: function(text, reverse) { if (!text) { delete this.currentSearch; this.highlightRow(null); return false; } var row; if (this.currentSearch && text == this.currentSearch.text) row = this.currentSearch.findNext(true, undefined, reverse, Firebug.searchCaseSensitive); else { function findRow(node) { return getAncestorByClass(node, "memberRow"); } this.currentSearch = new TextSearch(this.panelNode, findRow); row = this.currentSearch.find(text, reverse, Firebug.searchCaseSensitive); } if (row) { var sel = this.document.defaultView.getSelection(); sel.removeAllRanges(); sel.addRange(this.currentSearch.range); scrollIntoCenterView(row, this.panelNode); this.highlightRow(row); dispatch([Firebug.A11yModel], 'onDomSearchMatchFound', [this, text, row]); return true; } else { dispatch([Firebug.A11yModel], 'onDomSearchMatchFound', [this, text, null]); return false; } }/**/ }); Firebug.registerPanel(DOMMainPanel); // ************************************************************************************************ // ************************************************************************************************ // Local Helpers var getMembers = function getMembers(object, level) // we expect object to be user-level object wrapped in security blanket { if (!level) level = 0; var ordinals = [], userProps = [], userClasses = [], userFuncs = [], domProps = [], domFuncs = [], domConstants = []; try { var domMembers = getDOMMembers(object); //var domMembers = {}; // TODO: xxxpedro //var domConstantMap = {}; // TODO: xxxpedro if (object.wrappedJSObject) var insecureObject = object.wrappedJSObject; else var insecureObject = object; // IE function prototype is not listed in (for..in) if (isIE && isFunction(object)) addMember("user", userProps, "prototype", object.prototype, level); for (var name in insecureObject) // enumeration is safe { if (ignoreVars[name] == 1) // javascript.options.strict says ignoreVars is undefined. continue; var val; try { val = insecureObject[name]; // getter is safe } catch (exc) { // Sometimes we get exceptions trying to access certain members if (FBTrace.DBG_ERRORS && FBTrace.DBG_DOM) FBTrace.sysout("dom.getMembers cannot access "+name, exc); } var ordinal = parseInt(name); if (ordinal || ordinal == 0) { addMember("ordinal", ordinals, name, val, level); } else if (isFunction(val)) { if (isClassFunction(val) && !(name in domMembers)) addMember("userClass", userClasses, name, val, level); else if (name in domMembers) addMember("domFunction", domFuncs, name, val, level, domMembers[name]); else addMember("userFunction", userFuncs, name, val, level); } else { //TODO: xxxpedro /* var getterFunction = insecureObject.__lookupGetter__(name), setterFunction = insecureObject.__lookupSetter__(name), prefix = ""; if(getterFunction && !setterFunction) prefix = "get "; /**/ var prefix = ""; if (name in domMembers && !(name in domConstantMap)) addMember("dom", domProps, (prefix+name), val, level, domMembers[name]); else if (name in domConstantMap) addMember("dom", domConstants, (prefix+name), val, level); else addMember("user", userProps, (prefix+name), val, level); } } } catch (exc) { // Sometimes we get exceptions just from trying to iterate the members // of certain objects, like StorageList, but don't let that gum up the works throw exc; if (FBTrace.DBG_ERRORS && FBTrace.DBG_DOM) FBTrace.sysout("dom.getMembers FAILS: ", exc); //throw exc; } function sortName(a, b) { return a.name > b.name ? 1 : -1; } function sortOrder(a, b) { return a.order > b.order ? 1 : -1; } var members = []; members.push.apply(members, ordinals); Firebug.showUserProps = true; // TODO: xxxpedro Firebug.showUserFuncs = true; // TODO: xxxpedro Firebug.showDOMProps = true; Firebug.showDOMFuncs = true; Firebug.showDOMConstants = true; if (Firebug.showUserProps) { userProps.sort(sortName); members.push.apply(members, userProps); } if (Firebug.showUserFuncs) { userClasses.sort(sortName); members.push.apply(members, userClasses); userFuncs.sort(sortName); members.push.apply(members, userFuncs); } if (Firebug.showDOMProps) { domProps.sort(sortName); members.push.apply(members, domProps); } if (Firebug.showDOMFuncs) { domFuncs.sort(sortName); members.push.apply(members, domFuncs); } if (Firebug.showDOMConstants) members.push.apply(members, domConstants); return members; }; function expandMembers(members, toggles, offset, level) // recursion starts with offset=0, level=0 { var expanded = 0; for (var i = offset; i < members.length; ++i) { var member = members[i]; if (member.level > level) break; if ( toggles.hasOwnProperty(member.name) ) { member.open = "opened"; // member.level <= level && member.name in toggles. var newMembers = getMembers(member.value, level+1); // sets newMembers.level to level+1 var args = [i+1, 0]; args.push.apply(args, newMembers); members.splice.apply(members, args); /* if (FBTrace.DBG_DOM) { FBTrace.sysout("expandMembers member.name", member.name); FBTrace.sysout("expandMembers toggles", toggles); FBTrace.sysout("expandMembers toggles[member.name]", toggles[member.name]); FBTrace.sysout("dom.expandedMembers level: "+level+" member", member); } /**/ expanded += newMembers.length; i += newMembers.length + expandMembers(members, toggles[member.name], i+1, level+1); } } return expanded; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * function isClassFunction(fn) { try { for (var name in fn.prototype) return true; } catch (exc) {} return false; } // FIXME: xxxpedro This function is already defined in Lib. If we keep this definition here, it // will crash IE9 when not running the IE Developer Tool with JavaScript Debugging enabled!!! // Check if this function is in fact defined in Firebug for Firefox. If so, we should remove // this from here. The only difference of this function is the IE hack to show up the prototype // of functions, but Firebug no longer shows the prototype for simple functions. //var hasProperties = function hasProperties(ob) //{ // try // { // for (var name in ob) // return true; // } catch (exc) {} // // // IE function prototype is not listed in (for..in) // if (isFunction(ob)) return true; // // return false; //}; FBL.ErrorCopy = function(message) { this.message = message; }; var addMember = function addMember(type, props, name, value, level, order) { var rep = Firebug.getRep(value); // do this first in case a call to instanceof reveals contents var tag = rep.shortTag ? rep.shortTag : rep.tag; var ErrorCopy = function(){}; //TODO: xxxpedro var valueType = typeof(value); var hasChildren = hasProperties(value) && !(value instanceof ErrorCopy) && (isFunction(value) || (valueType == "object" && value != null) || (valueType == "string" && value.length > Firebug.stringCropLength)); props.push({ name: name, value: value, type: type, rowClass: "memberRow-"+type, open: "", order: order, level: level, indent: level*16, hasChildren: hasChildren, tag: tag }); }; var getWatchRowIndex = function getWatchRowIndex(row) { var index = -1; for (; row && hasClass(row, "watchRow"); row = row.previousSibling) ++index; return index; }; var getRowName = function getRowName(row) { var node = row.firstChild; return node.textContent ? node.textContent : node.innerText; }; var getRowValue = function getRowValue(row) { return row.lastChild.firstChild.repObject; }; var getRowOwnerObject = function getRowOwnerObject(row) { var parentRow = getParentRow(row); if (parentRow) return getRowValue(parentRow); }; var getParentRow = function getParentRow(row) { var level = parseInt(row.getAttribute("level"))-1; for (row = row.previousSibling; row; row = row.previousSibling) { if (parseInt(row.getAttribute("level")) == level) return row; } }; var getPath = function getPath(row) { var name = getRowName(row); var path = [name]; var level = parseInt(row.getAttribute("level"))-1; for (row = row.previousSibling; row; row = row.previousSibling) { if (parseInt(row.getAttribute("level")) == level) { var name = getRowName(row); path.splice(0, 0, name); --level; } } return path; }; // ************************************************************************************************ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ************************************************************************************************ // DOM Module Firebug.DOM = extend(Firebug.Module, { getPanel: function() { return Firebug.chrome ? Firebug.chrome.getPanel("DOM") : null; } }); Firebug.registerModule(Firebug.DOM); // ************************************************************************************************ // DOM Panel var lastHighlightedObject; function DOMSidePanel(){}; DOMSidePanel.prototype = extend(Firebug.DOMBasePanel.prototype, { selectRow: function(row, target) { if (!target) target = row.lastChild.firstChild; if (!target || !target.repObject) return; this.pathToAppend = getPath(row); // If the object is inside an array, look up its index var valueBox = row.lastChild.firstChild; if (hasClass(valueBox, "objectBox-array")) { var arrayIndex = FirebugReps.Arr.getItemIndex(target); this.pathToAppend.push(arrayIndex); } // Make sure we get a fresh status path for the object, since otherwise // it might find the object in the existing path and not refresh it //Firebug.chrome.clearStatusPath(); var object = target.repObject; if (instanceOf(object, "Element")) { Firebug.HTML.selectTreeNode(ElementCache(object)); } else { Firebug.chrome.selectPanel("DOM"); Firebug.chrome.getPanel("DOM").select(object, true); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onClick: function(event) { /* var target = event.srcElement || event.target; var object = getAncestorByClass(target, "objectLink"); object = object ? object.repObject : null; if(!object) return; if (instanceOf(object, "Element")) { Firebug.HTML.selectTreeNode(ElementCache(object)); } else { Firebug.chrome.selectPanel("DOM"); Firebug.chrome.getPanel("DOM").select(object, true); } /**/ var target = event.srcElement || event.target; var repNode = Firebug.getRepNode(target); if (repNode) { var row = getAncestorByClass(target, "memberRow"); if (row) { this.selectRow(row, repNode); cancelEvent(event); } } /**/ }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "DOMSidePanel", parentPanel: "HTML", title: "DOM", options: { hasToolButtons: true }, isInitialized: false, create: function() { Firebug.DOMBasePanel.prototype.create.apply(this, arguments); this.onClick = bind(this.onClick, this); }, initialize: function(){ Firebug.DOMBasePanel.prototype.initialize.apply(this, arguments); addEvent(this.panelNode, "click", this.onClick); // TODO: xxxpedro css2 var selection = ElementCache.get(Firebug.context.persistedState.selectedHTMLElementId); if (selection) this.select(selection, true); }, shutdown: function() { removeEvent(this.panelNode, "click", this.onClick); Firebug.DOMBasePanel.prototype.shutdown.apply(this, arguments); }, reattach: function(oldChrome) { //this.isInitialized = oldChrome.getPanel("DOM").isInitialized; this.toggles = oldChrome.getPanel("DOMSidePanel").toggles; } }); Firebug.registerPanel(DOMSidePanel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.FBTrace = {}; (function() { // ************************************************************************************************ var traceOptions = { DBG_TIMESTAMP: 1, DBG_INITIALIZE: 1, DBG_CHROME: 1, DBG_ERRORS: 1, DBG_DISPATCH: 1, DBG_CSS: 1 }; this.module = null; this.initialize = function() { if (!this.messageQueue) this.messageQueue = []; for (var name in traceOptions) this[name] = traceOptions[name]; }; // ************************************************************************************************ // FBTrace API this.sysout = function() { return this.logFormatted(arguments, ""); }; this.dumpProperties = function(title, object) { return this.logFormatted("dumpProperties() not supported.", "warning"); }; this.dumpStack = function() { return this.logFormatted("dumpStack() not supported.", "warning"); }; this.flush = function(module) { this.module = module; var queue = this.messageQueue; this.messageQueue = []; for (var i = 0; i < queue.length; ++i) this.writeMessage(queue[i][0], queue[i][1], queue[i][2]); }; this.getPanel = function() { return this.module ? this.module.getPanel() : null; }; //************************************************************************************************* this.logFormatted = function(objects, className) { var html = this.DBG_TIMESTAMP ? [getTimestamp(), " | "] : []; var length = objects.length; for (var i = 0; i < length; ++i) { appendText(" ", html); var object = objects[i]; if (i == 0) { html.push("<b>"); appendText(object, html); html.push("</b>"); } else appendText(object, html); } return this.logRow(html, className); }; this.logRow = function(message, className) { var panel = this.getPanel(); if (panel && panel.panelNode) this.writeMessage(message, className); else { this.messageQueue.push([message, className]); } return this.LOG_COMMAND; }; this.writeMessage = function(message, className) { var container = this.getPanel().containerNode; var isScrolledToBottom = container.scrollTop + container.offsetHeight >= container.scrollHeight; this.writeRow.call(this, message, className); if (isScrolledToBottom) container.scrollTop = container.scrollHeight - container.offsetHeight; }; this.appendRow = function(row) { var container = this.getPanel().panelNode; container.appendChild(row); }; this.writeRow = function(message, className) { var row = this.getPanel().panelNode.ownerDocument.createElement("div"); row.className = "logRow" + (className ? " logRow-"+className : ""); row.innerHTML = message.join(""); this.appendRow(row); }; //************************************************************************************************* function appendText(object, html) { html.push(escapeHTML(objectToString(object))); }; function getTimestamp() { var now = new Date(); var ms = "" + (now.getMilliseconds() / 1000).toFixed(3); ms = ms.substr(2); return now.toLocaleTimeString() + "." + ms; }; //************************************************************************************************* var HTMLtoEntity = { "<": "&lt;", ">": "&gt;", "&": "&amp;", "'": "&#39;", '"': "&quot;" }; function replaceChars(ch) { return HTMLtoEntity[ch]; }; function escapeHTML(value) { return (value+"").replace(/[<>&"']/g, replaceChars); }; //************************************************************************************************* function objectToString(object) { try { return object+""; } catch (exc) { return null; } }; // ************************************************************************************************ }).apply(FBL.FBTrace); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // If application isn't in trace mode, the FBTrace panel won't be loaded if (!Env.Options.enableTrace) return; // ************************************************************************************************ // FBTrace Module Firebug.Trace = extend(Firebug.Module, { getPanel: function() { return Firebug.chrome ? Firebug.chrome.getPanel("Trace") : null; }, clear: function() { this.getPanel().panelNode.innerHTML = ""; } }); Firebug.registerModule(Firebug.Trace); // ************************************************************************************************ // FBTrace Panel function TracePanel(){}; TracePanel.prototype = extend(Firebug.Panel, { name: "Trace", title: "Trace", options: { hasToolButtons: true, innerHTMLSync: true }, create: function(){ Firebug.Panel.create.apply(this, arguments); this.clearButton = new Button({ caption: "Clear", title: "Clear FBTrace logs", owner: Firebug.Trace, onClick: Firebug.Trace.clear }); }, initialize: function(){ Firebug.Panel.initialize.apply(this, arguments); this.clearButton.initialize(); }, shutdown: function() { this.clearButton.shutdown(); Firebug.Panel.shutdown.apply(this, arguments); } }); Firebug.registerPanel(TracePanel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals var modules = []; var panelTypes = []; var panelTypeMap = {}; var parentPanelMap = {}; var registerModule = Firebug.registerModule; var registerPanel = Firebug.registerPanel; // ************************************************************************************************ append(Firebug, { extend: function(fn) { if (Firebug.chrome && Firebug.chrome.addPanel) { var namespace = ns(fn); fn.call(namespace, FBL); } else { setTimeout(function(){Firebug.extend(fn);},100); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Registration registerModule: function() { registerModule.apply(Firebug, arguments); modules.push.apply(modules, arguments); dispatch(modules, "initialize", []); if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.registerModule"); }, registerPanel: function() { registerPanel.apply(Firebug, arguments); panelTypes.push.apply(panelTypes, arguments); for (var i = 0, panelType; panelType = arguments[i]; ++i) { // TODO: xxxpedro investigate why Dev Panel throws an error if (panelType.prototype.name == "Dev") continue; panelTypeMap[panelType.prototype.name] = arguments[i]; var parentPanelName = panelType.prototype.parentPanel; if (parentPanelName) { parentPanelMap[parentPanelName] = 1; } else { var panelName = panelType.prototype.name; var chrome = Firebug.chrome; chrome.addPanel(panelName); // tab click handler var onTabClick = function onTabClick() { chrome.selectPanel(panelName); return false; }; chrome.addController([chrome.panelMap[panelName].tabNode, "mousedown", onTabClick]); } } if (FBTrace.DBG_INITIALIZE) for (var i = 0; i < arguments.length; ++i) FBTrace.sysout("Firebug.registerPanel", arguments[i].prototype.name); } }); // ************************************************************************************************ }}); FBL.ns(function() { with (FBL) { // ************************************************************************************************ FirebugChrome.Skin = { CSS: '.obscured{left:-999999px !important;}.collapsed{display:none;}[collapsed="true"]{display:none;}#fbCSS{padding:0 !important;}.cssPropDisable{float:left;display:block;width:2em;cursor:default;}.infoTip{z-index:2147483647;position:fixed;padding:2px 3px;border:1px solid #CBE087;background:LightYellow;font-family:Monaco,monospace;color:#000000;display:none;white-space:nowrap;pointer-events:none;}.infoTip[active="true"]{display:block;}.infoTipLoading{width:16px;height:16px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/loading_16.gif) no-repeat;}.infoTipImageBox{font-size:11px;min-width:100px;text-align:center;}.infoTipCaption{font-size:11px;font:Monaco,monospace;}.infoTipLoading > .infoTipImage,.infoTipLoading > .infoTipCaption{display:none;}h1.groupHeader{padding:2px 4px;margin:0 0 4px 0;border-top:1px solid #CCCCCC;border-bottom:1px solid #CCCCCC;background:#eee url(https://getfirebug.com/releases/lite/latest/skin/xp/group.gif) repeat-x;font-size:11px;font-weight:bold;_position:relative;}.inlineEditor,.fixedWidthEditor{z-index:2147483647;position:absolute;display:none;}.inlineEditor{margin-left:-6px;margin-top:-3px;}.textEditorInner,.fixedWidthEditor{margin:0 0 0 0 !important;padding:0;border:none !important;font:inherit;text-decoration:inherit;background-color:#FFFFFF;}.fixedWidthEditor{border-top:1px solid #888888 !important;border-bottom:1px solid #888888 !important;}.textEditorInner{position:relative;top:-7px;left:-5px;outline:none;resize:none;}.textEditorInner1{padding-left:11px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorBorders.png) repeat-y;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorBorders.gif) repeat-y;_overflow:hidden;}.textEditorInner2{position:relative;padding-right:2px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorBorders.png) repeat-y 100% 0;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorBorders.gif) repeat-y 100% 0;_position:fixed;}.textEditorTop1{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.png) no-repeat 100% 0;margin-left:11px;height:10px;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.gif) no-repeat 100% 0;_overflow:hidden;}.textEditorTop2{position:relative;left:-11px;width:11px;height:10px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.png) no-repeat;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.gif) no-repeat;}.textEditorBottom1{position:relative;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.png) no-repeat 100% 100%;margin-left:11px;height:12px;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.gif) no-repeat 100% 100%;}.textEditorBottom2{position:relative;left:-11px;width:11px;height:12px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.png) no-repeat 0 100%;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.gif) no-repeat 0 100%;}.panelNode-css{overflow-x:hidden;}.cssSheet > .insertBefore{height:1.5em;}.cssRule{position:relative;margin:0;padding:1em 0 0 6px;font-family:Monaco,monospace;color:#000000;}.cssRule:first-child{padding-top:6px;}.cssElementRuleContainer{position:relative;}.cssHead{padding-right:150px;}.cssProp{}.cssPropName{color:DarkGreen;}.cssPropValue{margin-left:8px;color:DarkBlue;}.cssOverridden span{text-decoration:line-through;}.cssInheritedRule{}.cssInheritLabel{margin-right:0.5em;font-weight:bold;}.cssRule .objectLink-sourceLink{top:0;}.cssProp.editGroup:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/disable.png) no-repeat 2px 1px;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/disable.gif) no-repeat 2px 1px;}.cssProp.editGroup.editing{background:none;}.cssProp.disabledStyle{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/disableHover.png) no-repeat 2px 1px;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/disableHover.gif) no-repeat 2px 1px;opacity:1;color:#CCCCCC;}.disabledStyle .cssPropName,.disabledStyle .cssPropValue{color:#CCCCCC;}.cssPropValue.editing + .cssSemi,.inlineExpander + .cssSemi{display:none;}.cssPropValue.editing{white-space:nowrap;}.stylePropName{font-weight:bold;padding:0 4px 4px 4px;width:50%;}.stylePropValue{width:50%;}.panelNode-net{overflow-x:hidden;}.netTable{width:100%;}.hideCategory-undefined .category-undefined,.hideCategory-html .category-html,.hideCategory-css .category-css,.hideCategory-js .category-js,.hideCategory-image .category-image,.hideCategory-xhr .category-xhr,.hideCategory-flash .category-flash,.hideCategory-txt .category-txt,.hideCategory-bin .category-bin{display:none;}.netHeadRow{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/group.gif) repeat-x #FFFFFF;}.netHeadCol{border-bottom:1px solid #CCCCCC;padding:2px 4px 2px 18px;font-weight:bold;}.netHeadLabel{white-space:nowrap;overflow:hidden;}.netHeaderRow{height:16px;}.netHeaderCell{cursor:pointer;-moz-user-select:none;border-bottom:1px solid #9C9C9C;padding:0 !important;font-weight:bold;background:#BBBBBB url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/tableHeader.gif) repeat-x;white-space:nowrap;}.netHeaderRow > .netHeaderCell:first-child > .netHeaderCellBox{padding:2px 14px 2px 18px;}.netHeaderCellBox{padding:2px 14px 2px 10px;border-left:1px solid #D9D9D9;border-right:1px solid #9C9C9C;}.netHeaderCell:hover:active{background:#959595 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/tableHeaderActive.gif) repeat-x;}.netHeaderSorted{background:#7D93B2 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/tableHeaderSorted.gif) repeat-x;}.netHeaderSorted > .netHeaderCellBox{border-right-color:#6B7C93;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/arrowDown.png) no-repeat right;}.netHeaderSorted.sortedAscending > .netHeaderCellBox{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/arrowUp.png);}.netHeaderSorted:hover:active{background:#536B90 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/tableHeaderSortedActive.gif) repeat-x;}.panelNode-net .netRowHeader{display:block;}.netRowHeader{cursor:pointer;display:none;height:15px;margin-right:0 !important;}.netRow .netRowHeader{background-position:5px 1px;}.netRow[breakpoint="true"] .netRowHeader{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/breakpoint.png);}.netRow[breakpoint="true"][disabledBreakpoint="true"] .netRowHeader{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/breakpointDisabled.png);}.netRow.category-xhr:hover .netRowHeader{background-color:#F6F6F6;}#netBreakpointBar{max-width:38px;}#netHrefCol > .netHeaderCellBox{border-left:0px;}.netRow .netRowHeader{width:3px;}.netInfoRow .netRowHeader{display:table-cell;}.netTable[hiddenCols~=netHrefCol] TD[id="netHrefCol"],.netTable[hiddenCols~=netHrefCol] TD.netHrefCol,.netTable[hiddenCols~=netStatusCol] TD[id="netStatusCol"],.netTable[hiddenCols~=netStatusCol] TD.netStatusCol,.netTable[hiddenCols~=netDomainCol] TD[id="netDomainCol"],.netTable[hiddenCols~=netDomainCol] TD.netDomainCol,.netTable[hiddenCols~=netSizeCol] TD[id="netSizeCol"],.netTable[hiddenCols~=netSizeCol] TD.netSizeCol,.netTable[hiddenCols~=netTimeCol] TD[id="netTimeCol"],.netTable[hiddenCols~=netTimeCol] TD.netTimeCol{display:none;}.netRow{background:LightYellow;}.netRow.loaded{background:#FFFFFF;}.netRow.loaded:hover{background:#EFEFEF;}.netCol{padding:0;vertical-align:top;border-bottom:1px solid #EFEFEF;white-space:nowrap;height:17px;}.netLabel{width:100%;}.netStatusCol{padding-left:10px;color:rgb(128,128,128);}.responseError > .netStatusCol{color:red;}.netDomainCol{padding-left:5px;}.netSizeCol{text-align:right;padding-right:10px;}.netHrefLabel{-moz-box-sizing:padding-box;overflow:hidden;z-index:10;position:absolute;padding-left:18px;padding-top:1px;max-width:15%;font-weight:bold;}.netFullHrefLabel{display:none;-moz-user-select:none;padding-right:10px;padding-bottom:3px;max-width:100%;background:#FFFFFF;z-index:200;}.netHrefCol:hover > .netFullHrefLabel{display:block;}.netRow.loaded:hover .netCol > .netFullHrefLabel{background-color:#EFEFEF;}.useA11y .a11yShowFullLabel{display:block;background-image:none !important;border:1px solid #CBE087;background-color:LightYellow;font-family:Monaco,monospace;color:#000000;font-size:10px;z-index:2147483647;}.netSizeLabel{padding-left:6px;}.netStatusLabel,.netDomainLabel,.netSizeLabel,.netBar{padding:1px 0 2px 0 !important;}.responseError{color:red;}.hasHeaders .netHrefLabel:hover{cursor:pointer;color:blue;text-decoration:underline;}.netLoadingIcon{position:absolute;border:0;margin-left:14px;width:16px;height:16px;background:transparent no-repeat 0 0;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/loading_16.gif);display:inline-block;}.loaded .netLoadingIcon{display:none;}.netBar,.netSummaryBar{position:relative;border-right:50px solid transparent;}.netResolvingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarResolving.gif) repeat-x;z-index:60;}.netConnectingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarConnecting.gif) repeat-x;z-index:50;}.netBlockingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarWaiting.gif) repeat-x;z-index:40;}.netSendingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarSending.gif) repeat-x;z-index:30;}.netWaitingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarResponded.gif) repeat-x;z-index:20;min-width:1px;}.netReceivingBar{position:absolute;left:0;top:0;bottom:0;background:#38D63B url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarLoading.gif) repeat-x;z-index:10;}.netWindowLoadBar,.netContentLoadBar{position:absolute;left:0;top:0;bottom:0;width:1px;background-color:red;z-index:70;opacity:0.5;display:none;margin-bottom:-1px;}.netContentLoadBar{background-color:Blue;}.netTimeLabel{-moz-box-sizing:padding-box;position:absolute;top:1px;left:100%;padding-left:6px;color:#444444;min-width:16px;}.loaded .netReceivingBar,.loaded.netReceivingBar{background:#B6B6B6 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarLoaded.gif) repeat-x;border-color:#B6B6B6;}.fromCache .netReceivingBar,.fromCache.netReceivingBar{background:#D6D6D6 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarCached.gif) repeat-x;border-color:#D6D6D6;}.netSummaryRow .netTimeLabel,.loaded .netTimeLabel{background:transparent;}.timeInfoTip{width:150px; height:40px}.timeInfoTipBar,.timeInfoTipEventBar{position:relative;display:block;margin:0;opacity:1;height:15px;width:4px;}.timeInfoTipEventBar{width:1px !important;}.timeInfoTipCell.startTime{padding-right:8px;}.timeInfoTipCell.elapsedTime{text-align:right;padding-right:8px;}.sizeInfoLabelCol{font-weight:bold;padding-right:10px;font-family:Lucida Grande,Tahoma,sans-serif;font-size:11px;}.sizeInfoSizeCol{font-weight:bold;}.sizeInfoDetailCol{color:gray;text-align:right;}.sizeInfoDescCol{font-style:italic;}.netSummaryRow .netReceivingBar{background:#BBBBBB;border:none;}.netSummaryLabel{color:#222222;}.netSummaryRow{background:#BBBBBB !important;font-weight:bold;}.netSummaryRow .netBar{border-right-color:#BBBBBB;}.netSummaryRow > .netCol{border-top:1px solid #999999;border-bottom:2px solid;-moz-border-bottom-colors:#EFEFEF #999999;padding-top:1px;padding-bottom:2px;}.netSummaryRow > .netHrefCol:hover{background:transparent !important;}.netCountLabel{padding-left:18px;}.netTotalSizeCol{text-align:right;padding-right:10px;}.netTotalTimeCol{text-align:right;}.netCacheSizeLabel{position:absolute;z-index:1000;left:0;top:0;}.netLimitRow{background:rgb(255,255,225) !important;font-weight:normal;color:black;font-weight:normal;}.netLimitLabel{padding-left:18px;}.netLimitRow > .netCol{border-bottom:2px solid;-moz-border-bottom-colors:#EFEFEF #999999;vertical-align:middle !important;padding-top:2px;padding-bottom:2px;}.netLimitButton{font-size:11px;padding-top:1px;padding-bottom:1px;}.netInfoCol{border-top:1px solid #EEEEEE;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/group.gif) repeat-x #FFFFFF;}.netInfoBody{margin:10px 0 4px 10px;}.netInfoTabs{position:relative;padding-left:17px;}.netInfoTab{position:relative;top:-3px;margin-top:10px;padding:4px 6px;border:1px solid transparent;border-bottom:none;_border:none;font-weight:bold;color:#565656;cursor:pointer;}.netInfoTabSelected{cursor:default !important;border:1px solid #D7D7D7 !important;border-bottom:none !important;-moz-border-radius:4px 4px 0 0;-webkit-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;background-color:#FFFFFF;}.logRow-netInfo.error .netInfoTitle{color:red;}.logRow-netInfo.loading .netInfoResponseText{font-style:italic;color:#888888;}.loading .netInfoResponseHeadersTitle{display:none;}.netInfoResponseSizeLimit{font-family:Lucida Grande,Tahoma,sans-serif;padding-top:10px;font-size:11px;}.netInfoText{display:none;margin:0;border:1px solid #D7D7D7;border-right:none;padding:8px;background-color:#FFFFFF;font-family:Monaco,monospace;white-space:pre-wrap;}.netInfoTextSelected{display:block;}.netInfoParamName{padding-right:10px;font-family:Lucida Grande,Tahoma,sans-serif;font-weight:bold;vertical-align:top;text-align:right;white-space:nowrap;}.netInfoPostText .netInfoParamName{width:1px;}.netInfoParamValue{width:100%;}.netInfoHeadersText,.netInfoPostText,.netInfoPutText{padding-top:0;}.netInfoHeadersGroup,.netInfoPostParams,.netInfoPostSource{margin-bottom:4px;border-bottom:1px solid #D7D7D7;padding-top:8px;padding-bottom:2px;font-family:Lucida Grande,Tahoma,sans-serif;font-weight:bold;color:#565656;}.netInfoPostParamsTable,.netInfoPostPartsTable,.netInfoPostJSONTable,.netInfoPostXMLTable,.netInfoPostSourceTable{margin-bottom:10px;width:100%;}.netInfoPostContentType{color:#bdbdbd;padding-left:50px;font-weight:normal;}.netInfoHtmlPreview{border:0;width:100%;height:100%;}.netHeadersViewSource{color:#bdbdbd;margin-left:200px;font-weight:normal;}.netHeadersViewSource:hover{color:blue;cursor:pointer;}.netActivationRow,.netPageSeparatorRow{background:rgb(229,229,229) !important;font-weight:normal;color:black;}.netActivationLabel{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/infoIcon.png) no-repeat 3px 2px;padding-left:22px;}.netPageSeparatorRow{height:5px !important;}.netPageSeparatorLabel{padding-left:22px;height:5px !important;}.netPageRow{background-color:rgb(255,255,255);}.netPageRow:hover{background:#EFEFEF;}.netPageLabel{padding:1px 0 2px 18px !important;font-weight:bold;}.netActivationRow > .netCol{border-bottom:2px solid;-moz-border-bottom-colors:#EFEFEF #999999;padding-top:2px;padding-bottom:3px;}.twisty,.logRow-errorMessage > .hasTwisty > .errorTitle,.logRow-log > .objectBox-array.hasTwisty,.logRow-spy .spyHead .spyTitle,.logGroup > .logRow,.memberRow.hasChildren > .memberLabelCell > .memberLabel,.hasHeaders .netHrefLabel,.netPageRow > .netCol > .netPageTitle{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_open.gif);background-repeat:no-repeat;background-position:2px 2px;min-height:12px;}.logRow-errorMessage > .hasTwisty.opened > .errorTitle,.logRow-log > .objectBox-array.hasTwisty.opened,.logRow-spy.opened .spyHead .spyTitle,.logGroup.opened > .logRow,.memberRow.hasChildren.opened > .memberLabelCell > .memberLabel,.nodeBox.highlightOpen > .nodeLabel > .twisty,.nodeBox.open > .nodeLabel > .twisty,.netRow.opened > .netCol > .netHrefLabel,.netPageRow.opened > .netCol > .netPageTitle{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_close.gif);}.twisty{background-position:4px 4px;}* html .logRow-spy .spyHead .spyTitle,* html .logGroup .logGroupLabel,* html .hasChildren .memberLabelCell .memberLabel,* html .hasHeaders .netHrefLabel{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_open.gif);background-repeat:no-repeat;background-position:2px 2px;}* html .opened .spyHead .spyTitle,* html .opened .logGroupLabel,* html .opened .memberLabelCell .memberLabel{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_close.gif);background-repeat:no-repeat;background-position:2px 2px;}.panelNode-console{overflow-x:hidden;}.objectLink{text-decoration:none;}.objectLink:hover{cursor:pointer;text-decoration:underline;}.logRow{position:relative;margin:0;border-bottom:1px solid #D7D7D7;padding:2px 4px 1px 6px;background-color:#FFFFFF;overflow:hidden !important;}.useA11y .logRow:focus{border-bottom:1px solid #000000 !important;outline:none !important;background-color:#FFFFAD !important;}.useA11y .logRow:focus a.objectLink-sourceLink{background-color:#FFFFAD;}.useA11y .a11yFocus:focus,.useA11y .objectBox:focus{outline:2px solid #FF9933;background-color:#FFFFAD;}.useA11y .objectBox-null:focus,.useA11y .objectBox-undefined:focus{background-color:#888888 !important;}.useA11y .logGroup.opened > .logRow{border-bottom:1px solid #ffffff;}.logGroup{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/group.gif) repeat-x #FFFFFF;padding:0 !important;border:none !important;}.logGroupBody{display:none;margin-left:16px;border-left:1px solid #D7D7D7;border-top:1px solid #D7D7D7;background:#FFFFFF;}.logGroup > .logRow{background-color:transparent !important;font-weight:bold;}.logGroup.opened > .logRow{border-bottom:none;}.logGroup.opened > .logGroupBody{display:block;}.logRow-command > .objectBox-text{font-family:Monaco,monospace;color:#0000FF;white-space:pre-wrap;}.logRow-info,.logRow-warn,.logRow-error,.logRow-assert,.logRow-warningMessage,.logRow-errorMessage{padding-left:22px;background-repeat:no-repeat;background-position:4px 2px;}.logRow-assert,.logRow-warningMessage,.logRow-errorMessage{padding-top:0;padding-bottom:0;}.logRow-info,.logRow-info .objectLink-sourceLink{background-color:#FFFFFF;}.logRow-warn,.logRow-warningMessage,.logRow-warn .objectLink-sourceLink,.logRow-warningMessage .objectLink-sourceLink{background-color:cyan;}.logRow-error,.logRow-assert,.logRow-errorMessage,.logRow-error .objectLink-sourceLink,.logRow-errorMessage .objectLink-sourceLink{background-color:LightYellow;}.logRow-error,.logRow-assert,.logRow-errorMessage{color:#FF0000;}.logRow-info{}.logRow-warn,.logRow-warningMessage{}.logRow-error,.logRow-assert,.logRow-errorMessage{}.objectBox-string,.objectBox-text,.objectBox-number,.objectLink-element,.objectLink-textNode,.objectLink-function,.objectBox-stackTrace,.objectLink-profile{font-family:Monaco,monospace;}.objectBox-string,.objectBox-text,.objectLink-textNode{white-space:pre-wrap;}.objectBox-number,.objectLink-styleRule,.objectLink-element,.objectLink-textNode{color:#000088;}.objectBox-string{color:#FF0000;}.objectLink-function,.objectBox-stackTrace,.objectLink-profile{color:DarkGreen;}.objectBox-null,.objectBox-undefined{padding:0 2px;border:1px solid #666666;background-color:#888888;color:#FFFFFF;}.objectBox-exception{padding:0 2px 0 18px;color:red;}.objectLink-sourceLink{position:absolute;right:4px;top:2px;padding-left:8px;font-family:Lucida Grande,sans-serif;font-weight:bold;color:#0000FF;}.errorTitle{margin-top:0px;margin-bottom:1px;padding-top:2px;padding-bottom:2px;}.errorTrace{margin-left:17px;}.errorSourceBox{margin:2px 0;}.errorSource-none{display:none;}.errorSource-syntax > .errorBreak{visibility:hidden;}.errorSource{cursor:pointer;font-family:Monaco,monospace;color:DarkGreen;}.errorSource:hover{text-decoration:underline;}.errorBreak{cursor:pointer;display:none;margin:0 6px 0 0;width:13px;height:14px;vertical-align:bottom;opacity:0.1;}.hasBreakSwitch .errorBreak{display:inline;}.breakForError .errorBreak{opacity:1;}.assertDescription{margin:0;}.logRow-profile > .logRow > .objectBox-text{font-family:Lucida Grande,Tahoma,sans-serif;color:#000000;}.logRow-profile > .logRow > .objectBox-text:last-child{color:#555555;font-style:italic;}.logRow-profile.opened > .logRow{padding-bottom:4px;}.profilerRunning > .logRow{padding-left:22px !important;}.profileSizer{width:100%;overflow-x:auto;overflow-y:scroll;}.profileTable{border-bottom:1px solid #D7D7D7;padding:0 0 4px 0;}.profileTable tr[odd="1"]{background-color:#F5F5F5;vertical-align:middle;}.profileTable a{vertical-align:middle;}.profileTable td{padding:1px 4px 0 4px;}.headerCell{cursor:pointer;-moz-user-select:none;border-bottom:1px solid #9C9C9C;padding:0 !important;font-weight:bold;}.headerCellBox{padding:2px 4px;border-left:1px solid #D9D9D9;border-right:1px solid #9C9C9C;}.headerCell:hover:active{}.headerSorted{}.headerSorted > .headerCellBox{border-right-color:#6B7C93;}.headerSorted.sortedAscending > .headerCellBox{}.headerSorted:hover:active{}.linkCell{text-align:right;}.linkCell > .objectLink-sourceLink{position:static;}.logRow-stackTrace{padding-top:0;background:#f8f8f8;}.logRow-stackTrace > .objectBox-stackFrame{position:relative;padding-top:2px;}.objectLink-object{font-family:Lucida Grande,sans-serif;font-weight:bold;color:DarkGreen;white-space:pre-wrap;}.objectProp-object{color:DarkGreen;}.objectProps{color:#000;font-weight:normal;}.objectPropName{color:#777;}.objectProps .objectProp-string{color:#f55;}.objectProps .objectProp-number{color:#55a;}.objectProps .objectProp-object{color:#585;}.selectorTag,.selectorId,.selectorClass{font-family:Monaco,monospace;font-weight:normal;}.selectorTag{color:#0000FF;}.selectorId{color:DarkBlue;}.selectorClass{color:red;}.selectorHidden > .selectorTag{color:#5F82D9;}.selectorHidden > .selectorId{color:#888888;}.selectorHidden > .selectorClass{color:#D86060;}.selectorValue{font-family:Lucida Grande,sans-serif;font-style:italic;color:#555555;}.panelNode.searching .logRow{display:none;}.logRow.matched{display:block !important;}.logRow.matching{position:absolute;left:-1000px;top:-1000px;max-width:0;max-height:0;overflow:hidden;}.objectLeftBrace,.objectRightBrace,.objectEqual,.objectComma,.arrayLeftBracket,.arrayRightBracket,.arrayComma{font-family:Monaco,monospace;}.objectLeftBrace,.objectRightBrace,.arrayLeftBracket,.arrayRightBracket{font-weight:bold;}.objectLeftBrace,.arrayLeftBracket{margin-right:4px;}.objectRightBrace,.arrayRightBracket{margin-left:4px;}.logRow-dir{padding:0;}.logRow-errorMessage .hasTwisty .errorTitle,.logRow-spy .spyHead .spyTitle,.logGroup .logRow{cursor:pointer;padding-left:18px;background-repeat:no-repeat;background-position:3px 3px;}.logRow-errorMessage > .hasTwisty > .errorTitle{background-position:2px 3px;}.logRow-errorMessage > .hasTwisty > .errorTitle:hover,.logRow-spy .spyHead .spyTitle:hover,.logGroup > .logRow:hover{text-decoration:underline;}.logRow-spy{padding:0 !important;}.logRow-spy,.logRow-spy .objectLink-sourceLink{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/group.gif) repeat-x #FFFFFF;padding-right:4px;right:0;}.logRow-spy.opened{padding-bottom:4px;border-bottom:none;}.spyTitle{color:#000000;font-weight:bold;-moz-box-sizing:padding-box;overflow:hidden;z-index:100;padding-left:18px;}.spyCol{padding:0;white-space:nowrap;height:16px;}.spyTitleCol:hover > .objectLink-sourceLink,.spyTitleCol:hover > .spyTime,.spyTitleCol:hover > .spyStatus,.spyTitleCol:hover > .spyTitle{display:none;}.spyFullTitle{display:none;-moz-user-select:none;max-width:100%;background-color:Transparent;}.spyTitleCol:hover > .spyFullTitle{display:block;}.spyStatus{padding-left:10px;color:rgb(128,128,128);}.spyTime{margin-left:4px;margin-right:4px;color:rgb(128,128,128);}.spyIcon{margin-right:4px;margin-left:4px;width:16px;height:16px;vertical-align:middle;background:transparent no-repeat 0 0;display:none;}.loading .spyHead .spyRow .spyIcon{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/loading_16.gif);display:block;}.logRow-spy.loaded:not(.error) .spyHead .spyRow .spyIcon{width:0;margin:0;}.logRow-spy.error .spyHead .spyRow .spyIcon{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon-sm.png);display:block;background-position:2px 2px;}.logRow-spy .spyHead .netInfoBody{display:none;}.logRow-spy.opened .spyHead .netInfoBody{margin-top:10px;display:block;}.logRow-spy.error .spyTitle,.logRow-spy.error .spyStatus,.logRow-spy.error .spyTime{color:red;}.logRow-spy.loading .spyResponseText{font-style:italic;color:#888888;}.caption{font-family:Lucida Grande,Tahoma,sans-serif;font-weight:bold;color:#444444;}.warning{padding:10px;font-family:Lucida Grande,Tahoma,sans-serif;font-weight:bold;color:#888888;}.panelNode-dom{overflow-x:hidden !important;}.domTable{font-size:1em;width:100%;table-layout:fixed;background:#fff;}.domTableIE{width:auto;}.memberLabelCell{padding:2px 0 2px 0;vertical-align:top;}.memberValueCell{padding:1px 0 1px 5px;display:block;overflow:hidden;}.memberLabel{display:block;cursor:default;-moz-user-select:none;overflow:hidden;padding-left:18px;background-color:#FFFFFF;text-decoration:none;}.memberRow.hasChildren .memberLabelCell .memberLabel:hover{cursor:pointer;color:blue;text-decoration:underline;}.userLabel{color:#000000;font-weight:bold;}.userClassLabel{color:#E90000;font-weight:bold;}.userFunctionLabel{color:#025E2A;font-weight:bold;}.domLabel{color:#000000;}.domFunctionLabel{color:#025E2A;}.ordinalLabel{color:SlateBlue;font-weight:bold;}.scopesRow{padding:2px 18px;background-color:LightYellow;border-bottom:5px solid #BEBEBE;color:#666666;}.scopesLabel{background-color:LightYellow;}.watchEditCell{padding:2px 18px;background-color:LightYellow;border-bottom:1px solid #BEBEBE;color:#666666;}.editor-watchNewRow,.editor-memberRow{font-family:Monaco,monospace !important;}.editor-memberRow{padding:1px 0 !important;}.editor-watchRow{padding-bottom:0 !important;}.watchRow > .memberLabelCell{font-family:Monaco,monospace;padding-top:1px;padding-bottom:1px;}.watchRow > .memberLabelCell > .memberLabel{background-color:transparent;}.watchRow > .memberValueCell{padding-top:2px;padding-bottom:2px;}.watchRow > .memberLabelCell,.watchRow > .memberValueCell{background-color:#F5F5F5;border-bottom:1px solid #BEBEBE;}.watchToolbox{z-index:2147483647;position:absolute;right:0;padding:1px 2px;}#fbConsole{overflow-x:hidden !important;}#fbCSS{font:1em Monaco,monospace;padding:0 7px;}#fbstylesheetButtons select,#fbScriptButtons select{font:11px Lucida Grande,Tahoma,sans-serif;margin-top:1px;padding-left:3px;background:#fafafa;border:1px inset #fff;width:220px;outline:none;}.Selector{margin-top:10px}.CSSItem{margin-left:4%}.CSSText{padding-left:20px;}.CSSProperty{color:#005500;}.CSSValue{padding-left:5px; color:#000088;}#fbHTMLStatusBar{display:inline;}.fbToolbarButtons{display:none;}.fbStatusSeparator{display:block;float:left;padding-top:4px;}#fbStatusBarBox{display:none;}#fbToolbarContent{display:block;position:absolute;_position:absolute;top:0;padding-top:4px;height:23px;clip:rect(0,2048px,27px,0);}.fbTabMenuTarget{display:none !important;float:left;width:10px;height:10px;margin-top:6px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuTarget.png);}.fbTabMenuTarget:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuTargetHover.png);}.fbShadow{float:left;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/shadowAlpha.png) no-repeat bottom right !important;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/shadow2.gif) no-repeat bottom right;margin:10px 0 0 10px !important;margin:10px 0 0 5px;}.fbShadowContent{display:block;position:relative;background-color:#fff;border:1px solid #a9a9a9;top:-6px;left:-6px;}.fbMenu{display:none;position:absolute;font-size:11px;line-height:13px;z-index:2147483647;}.fbMenuContent{padding:2px;}.fbMenuSeparator{display:block;position:relative;padding:1px 18px 0;text-decoration:none;color:#000;cursor:default;background:#ACA899;margin:4px 0;}.fbMenuOption{display:block;position:relative;padding:2px 18px;text-decoration:none;color:#000;cursor:default;}.fbMenuOption:hover{color:#fff;background:#316AC5;}.fbMenuGroup{background:transparent url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuPin.png) no-repeat right 0;}.fbMenuGroup:hover{background:#316AC5 url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuPin.png) no-repeat right -17px;}.fbMenuGroupSelected{color:#fff;background:#316AC5 url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuPin.png) no-repeat right -17px;}.fbMenuChecked{background:transparent url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuCheckbox.png) no-repeat 4px 0;}.fbMenuChecked:hover{background:#316AC5 url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuCheckbox.png) no-repeat 4px -17px;}.fbMenuRadioSelected{background:transparent url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuRadio.png) no-repeat 4px 0;}.fbMenuRadioSelected:hover{background:#316AC5 url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuRadio.png) no-repeat 4px -17px;}.fbMenuShortcut{padding-right:85px;}.fbMenuShortcutKey{position:absolute;right:0;top:2px;width:77px;}#fbFirebugMenu{top:22px;left:0;}.fbMenuDisabled{color:#ACA899 !important;}#fbFirebugSettingsMenu{left:245px;top:99px;}#fbConsoleMenu{top:42px;left:48px;}.fbIconButton{display:block;}.fbIconButton{display:block;}.fbIconButton{display:block;float:left;height:20px;width:20px;color:#000;margin-right:2px;text-decoration:none;cursor:default;}.fbIconButton:hover{position:relative;top:-1px;left:-1px;margin-right:0;_margin-right:1px;color:#333;border:1px solid #fff;border-bottom:1px solid #bbb;border-right:1px solid #bbb;}.fbIconPressed{position:relative;margin-right:0;_margin-right:1px;top:0 !important;left:0 !important;height:19px;color:#333 !important;border:1px solid #bbb !important;border-bottom:1px solid #cfcfcf !important;border-right:1px solid #ddd !important;}#fbErrorPopup{position:absolute;right:0;bottom:0;height:19px;width:75px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 0;z-index:999;}#fbErrorPopupContent{position:absolute;right:0;top:1px;height:18px;width:75px;_width:74px;border-left:1px solid #aca899;}#fbErrorIndicator{position:absolute;top:2px;right:5px;}.fbBtnInspectActive{background:#aaa;color:#fff !important;}.fbBody{margin:0;padding:0;overflow:hidden;font-family:Lucida Grande,Tahoma,sans-serif;font-size:11px;background:#fff;}.clear{clear:both;}#fbMiniChrome{display:none;right:0;height:27px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 0;margin-left:1px;}#fbMiniContent{display:block;position:relative;left:-1px;right:0;top:1px;height:25px;border-left:1px solid #aca899;}#fbToolbarSearch{float:right;border:1px solid #ccc;margin:0 5px 0 0;background:#fff url(https://getfirebug.com/releases/lite/latest/skin/xp/search.png) no-repeat 4px 2px !important;background:#fff url(https://getfirebug.com/releases/lite/latest/skin/xp/search.gif) no-repeat 4px 2px;padding-left:20px;font-size:11px;}#fbToolbarErrors{float:right;margin:1px 4px 0 0;font-size:11px;}#fbLeftToolbarErrors{float:left;margin:7px 0px 0 5px;font-size:11px;}.fbErrors{padding-left:20px;height:14px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon.png) no-repeat !important;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon.gif) no-repeat;color:#f00;font-weight:bold;}#fbMiniErrors{display:inline;display:none;float:right;margin:5px 2px 0 5px;}#fbMiniIcon{float:right;margin:3px 4px 0;height:20px;width:20px;float:right;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) 0 -135px;cursor:pointer;}#fbChrome{font-family:Lucida Grande,Tahoma,sans-serif;font-size:11px;position:absolute;_position:static;top:0;left:0;height:100%;width:100%;border-collapse:collapse;border-spacing:0;background:#fff;overflow:hidden;}#fbChrome > tbody > tr > td{padding:0;}#fbTop{height:49px;}#fbToolbar{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 0;height:27px;font-size:11px;line-height:13px;}#fbPanelBarBox{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #dbd9c9 0 -27px;height:22px;}#fbContent{height:100%;vertical-align:top;}#fbBottom{height:18px;background:#fff;}#fbToolbarIcon{float:left;padding:0 5px 0;}#fbToolbarIcon a{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) 0 -135px;}#fbToolbarButtons{padding:0 2px 0 5px;}#fbToolbarButtons{padding:0 2px 0 5px;}.fbButton{text-decoration:none;display:block;float:left;color:#000;padding:4px 6px 4px 7px;cursor:default;}.fbButton:hover{color:#333;background:#f5f5ef url(https://getfirebug.com/releases/lite/latest/skin/xp/buttonBg.png);padding:3px 5px 3px 6px;border:1px solid #fff;border-bottom:1px solid #bbb;border-right:1px solid #bbb;}.fbBtnPressed{background:#e3e3db url(https://getfirebug.com/releases/lite/latest/skin/xp/buttonBgHover.png) !important;padding:3px 4px 2px 6px !important;margin:1px 0 0 1px !important;border:1px solid #ACA899 !important;border-color:#ACA899 #ECEBE3 #ECEBE3 #ACA899 !important;}#fbStatusBarBox{top:4px;cursor:default;}.fbToolbarSeparator{overflow:hidden;border:1px solid;border-color:transparent #fff transparent #777;_border-color:#eee #fff #eee #777;height:7px;margin:6px 3px;float:left;}.fbBtnSelected{font-weight:bold;}.fbStatusBar{color:#aca899;}.fbStatusBar a{text-decoration:none;color:black;}.fbStatusBar a:hover{color:blue;cursor:pointer;}#fbWindowButtons{position:absolute;white-space:nowrap;right:0;top:0;height:17px;width:48px;padding:5px;z-index:6;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 0;}#fbPanelBar1{width:1024px; z-index:8;left:0;white-space:nowrap;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #dbd9c9 0 -27px;position:absolute;left:4px;}#fbPanelBar2Box{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #dbd9c9 0 -27px;position:absolute;height:22px;width:300px; z-index:9;right:0;}#fbPanelBar2{position:absolute;width:290px; height:22px;padding-left:4px;}.fbPanel{display:none;}#fbPanelBox1,#fbPanelBox2{max-height:inherit;height:100%;font-size:1em;}#fbPanelBox2{background:#fff;}#fbPanelBox2{width:300px;background:#fff;}#fbPanel2{margin-left:6px;background:#fff;}#fbLargeCommandLine{display:none;position:absolute;z-index:9;top:27px;right:0;width:294px;height:201px;border-width:0;margin:0;padding:2px 0 0 2px;resize:none;outline:none;font-size:11px;overflow:auto;border-top:1px solid #B9B7AF;_right:-1px;_border-left:1px solid #fff;}#fbLargeCommandButtons{display:none;background:#ECE9D8;bottom:0;right:0;width:294px;height:21px;padding-top:1px;position:fixed;border-top:1px solid #ACA899;z-index:9;}#fbSmallCommandLineIcon{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/down.png) no-repeat;position:absolute;right:2px;bottom:3px;z-index:99;}#fbSmallCommandLineIcon:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/downHover.png) no-repeat;}.hide{overflow:hidden !important;position:fixed !important;display:none !important;visibility:hidden !important;}#fbCommand{height:18px;}#fbCommandBox{position:fixed;_position:absolute;width:100%;height:18px;bottom:0;overflow:hidden;z-index:9;background:#fff;border:0;border-top:1px solid #ccc;}#fbCommandIcon{position:absolute;color:#00f;top:2px;left:6px;display:inline;font:11px Monaco,monospace;z-index:10;}#fbCommandLine{position:absolute;width:100%;top:0;left:0;border:0;margin:0;padding:2px 0 2px 32px;font:11px Monaco,monospace;z-index:9;outline:none;}#fbLargeCommandLineIcon{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/up.png) no-repeat;position:absolute;right:1px;bottom:1px;z-index:10;}#fbLargeCommandLineIcon:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/upHover.png) no-repeat;}div.fbFitHeight{overflow:auto;position:relative;}.fbSmallButton{overflow:hidden;width:16px;height:16px;display:block;text-decoration:none;cursor:default;}#fbWindowButtons .fbSmallButton{float:right;}#fbWindow_btClose{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/min.png);}#fbWindow_btClose:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/minHover.png);}#fbWindow_btDetach{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/detach.png);}#fbWindow_btDetach:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/detachHover.png);}#fbWindow_btDeactivate{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/off.png);}#fbWindow_btDeactivate:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/offHover.png);}.fbTab{text-decoration:none;display:none;float:left;width:auto;float:left;cursor:default;font-family:Lucida Grande,Tahoma,sans-serif;font-size:11px;line-height:13px;font-weight:bold;height:22px;color:#565656;}.fbPanelBar span{float:left;}.fbPanelBar .fbTabL,.fbPanelBar .fbTabR{height:22px;width:8px;}.fbPanelBar .fbTabText{padding:4px 1px 0;}a.fbTab:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) 0 -73px;}a.fbTab:hover .fbTabL{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) -16px -96px;}a.fbTab:hover .fbTabR{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) -24px -96px;}.fbSelectedTab{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 -50px !important;color:#000;}.fbSelectedTab .fbTabL{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) 0 -96px !important;}.fbSelectedTab .fbTabR{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) -8px -96px !important;}#fbHSplitter{position:fixed;_position:absolute;left:0;top:0;width:100%;height:5px;overflow:hidden;cursor:n-resize !important;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/pixel_transparent.gif);z-index:9;}#fbHSplitter.fbOnMovingHSplitter{height:100%;z-index:100;}.fbVSplitter{background:#ece9d8;color:#000;border:1px solid #716f64;border-width:0 1px;border-left-color:#aca899;width:4px;cursor:e-resize;overflow:hidden;right:294px;text-decoration:none;z-index:10;position:absolute;height:100%;top:27px;}div.lineNo{font:1em/1.4545em Monaco,monospace;position:relative;float:left;top:0;left:0;margin:0 5px 0 0;padding:0 5px 0 10px;background:#eee;color:#888;border-right:1px solid #ccc;text-align:right;}.sourceBox{position:absolute;}.sourceCode{font:1em Monaco,monospace;overflow:hidden;white-space:pre;display:inline;}.nodeControl{margin-top:3px;margin-left:-14px;float:left;width:9px;height:9px;overflow:hidden;cursor:default;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_open.gif);_float:none;_display:inline;_position:absolute;}div.nodeMaximized{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_close.gif);}div.objectBox-element{padding:1px 3px;}.objectBox-selector{cursor:default;}.selectedElement{background:highlight;color:#fff !important;}.selectedElement span{color:#fff !important;}* html .selectedElement{position:relative;}@media screen and (-webkit-min-device-pixel-ratio:0){.selectedElement{background:#316AC5;color:#fff !important;}}.logRow *{font-size:1em;}.logRow{position:relative;border-bottom:1px solid #D7D7D7;padding:2px 4px 1px 6px;zbackground-color:#FFFFFF;}.logRow-command{font-family:Monaco,monospace;color:blue;}.objectBox-string,.objectBox-text,.objectBox-number,.objectBox-function,.objectLink-element,.objectLink-textNode,.objectLink-function,.objectBox-stackTrace,.objectLink-profile{font-family:Monaco,monospace;}.objectBox-null{padding:0 2px;border:1px solid #666666;background-color:#888888;color:#FFFFFF;}.objectBox-string{color:red;}.objectBox-number{color:#000088;}.objectBox-function{color:DarkGreen;}.objectBox-object{color:DarkGreen;font-weight:bold;font-family:Lucida Grande,sans-serif;}.objectBox-array{color:#000;}.logRow-info,.logRow-error,.logRow-warn{background:#fff no-repeat 2px 2px;padding-left:20px;padding-bottom:3px;}.logRow-info{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/infoIcon.png) !important;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/infoIcon.gif);}.logRow-warn{background-color:cyan;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/warningIcon.png) !important;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/warningIcon.gif);}.logRow-error{background-color:LightYellow;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon.png) !important;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon.gif);color:#f00;}.errorMessage{vertical-align:top;color:#f00;}.objectBox-sourceLink{position:absolute;right:4px;top:2px;padding-left:8px;font-family:Lucida Grande,sans-serif;font-weight:bold;color:#0000FF;}.selectorTag,.selectorId,.selectorClass{font-family:Monaco,monospace;font-weight:normal;}.selectorTag{color:#0000FF;}.selectorId{color:DarkBlue;}.selectorClass{color:red;}.objectBox-element{font-family:Monaco,monospace;color:#000088;}.nodeChildren{padding-left:26px;}.nodeTag{color:blue;cursor:pointer;}.nodeValue{color:#FF0000;font-weight:normal;}.nodeText,.nodeComment{margin:0 2px;vertical-align:top;}.nodeText{color:#333333;font-family:Monaco,monospace;}.nodeComment{color:DarkGreen;}.nodeHidden,.nodeHidden *{color:#888888;}.nodeHidden .nodeTag{color:#5F82D9;}.nodeHidden .nodeValue{color:#D86060;}.selectedElement .nodeHidden,.selectedElement .nodeHidden *{color:SkyBlue !important;}.log-object{}.property{position:relative;clear:both;height:15px;}.propertyNameCell{vertical-align:top;float:left;width:28%;position:absolute;left:0;z-index:0;}.propertyValueCell{float:right;width:68%;background:#fff;position:absolute;padding-left:5px;display:table-cell;right:0;z-index:1;}.propertyName{font-weight:bold;}.FirebugPopup{height:100% !important;}.FirebugPopup #fbWindowButtons{display:none !important;}.FirebugPopup #fbHSplitter{display:none !important;}', HTML: '<table id="fbChrome" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td id="fbTop" colspan="2"><div id="fbWindowButtons"><a id="fbWindow_btDeactivate" class="fbSmallButton fbHover" title="Deactivate Firebug for this web page">&nbsp;</a><a id="fbWindow_btDetach" class="fbSmallButton fbHover" title="Open Firebug in popup window">&nbsp;</a><a id="fbWindow_btClose" class="fbSmallButton fbHover" title="Minimize Firebug">&nbsp;</a></div><div id="fbToolbar"><div id="fbToolbarContent"><span id="fbToolbarIcon"><a id="fbFirebugButton" class="fbIconButton" class="fbHover" target="_blank">&nbsp;</a></span><span id="fbToolbarButtons"><span id="fbFixedButtons"><a id="fbChrome_btInspect" class="fbButton fbHover" title="Click an element in the page to inspect">Inspect</a></span><span id="fbConsoleButtons" class="fbToolbarButtons"><a id="fbConsole_btClear" class="fbButton fbHover" title="Clear the console">Clear</a></span></span><span id="fbStatusBarBox"><span class="fbToolbarSeparator"></span></span></div></div><div id="fbPanelBarBox"><div id="fbPanelBar1" class="fbPanelBar"><a id="fbConsoleTab" class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">Console</span><span class="fbTabMenuTarget"></span><span class="fbTabR"></span></a><a id="fbHTMLTab" class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">HTML</span><span class="fbTabR"></span></a><a class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">CSS</span><span class="fbTabR"></span></a><a class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">Script</span><span class="fbTabR"></span></a><a class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">DOM</span><span class="fbTabR"></span></a></div><div id="fbPanelBar2Box" class="hide"><div id="fbPanelBar2" class="fbPanelBar"></div></div></div><div id="fbHSplitter">&nbsp;</div></td></tr><tr id="fbContent"><td id="fbPanelBox1"><div id="fbPanel1" class="fbFitHeight"><div id="fbConsole" class="fbPanel"></div><div id="fbHTML" class="fbPanel"></div></div></td><td id="fbPanelBox2" class="hide"><div id="fbVSplitter" class="fbVSplitter">&nbsp;</div><div id="fbPanel2" class="fbFitHeight"><div id="fbHTML_Style" class="fbPanel"></div><div id="fbHTML_Layout" class="fbPanel"></div><div id="fbHTML_DOM" class="fbPanel"></div></div><textarea id="fbLargeCommandLine" class="fbFitHeight"></textarea><div id="fbLargeCommandButtons"><a id="fbCommand_btRun" class="fbButton fbHover">Run</a><a id="fbCommand_btClear" class="fbButton fbHover">Clear</a><a id="fbSmallCommandLineIcon" class="fbSmallButton fbHover"></a></div></td></tr><tr id="fbBottom" class="hide"><td id="fbCommand" colspan="2"><div id="fbCommandBox"><div id="fbCommandIcon">&gt;&gt;&gt;</div><input id="fbCommandLine" name="fbCommandLine" type="text"/><a id="fbLargeCommandLineIcon" class="fbSmallButton fbHover"></a></div></td></tr></tbody></table><span id="fbMiniChrome"><span id="fbMiniContent"><span id="fbMiniIcon" title="Open Firebug Lite"></span><span id="fbMiniErrors" class="fbErrors"></span></span></span>' }; // ************************************************************************************************ }}); // ************************************************************************************************ FBL.initialize(); // ************************************************************************************************ })();
packages/docs/components/Examples/undo/gettingStarted.js
draft-js-plugins/draft-js-plugins
// It is important to import the Editor which accepts plugins. import Editor from '@draft-js-plugins/editor'; import createUndoPlugin from '@draft-js-plugins/undo'; import React from 'react'; // Creates an Instance. At this step, a configuration object can be passed in // as an argument. const undoPlugin = createUndoPlugin(); const { UndoButton, RedoButton } = undoPlugin; // The Editor accepts an array of plugins. In this case, only the undoPlugin // is passed in, although it is possible to pass in multiple plugins. const MyEditor = ({ editorState, onChange }) => ( <div> <Editor editorState={editorState} onChange={onChange} plugins={[undoPlugin]} /> <UndoButton /> <RedoButton /> </div> ); export default MyEditor;
client/containers/services.js
ckiss/vidi-dashboard
'use strict' import React from 'react' import {connect} from 'react-redux' import Panel from '../components/panel' export const Services = React.createClass({ render () { return ( <div className="page container-fluid"> <div className="row middle-xs"> <h2 className="col-xs-12 col-sm-6">Services</h2> <div className="col-xs-12 col-sm-6 txt-right"> <select> <option>120 seconds</option> <option>5 minutes</option> <option>30 minutes</option> <option>1 hour</option> </select> </div> </div> <Panel title={'info'} /> </div> ) } }) export default connect((state) => { return { } })(Services)
ajax/libs/angular.js/0.9.1/angular-scenario.min.js
alucard001/cdnjs
/*! * jQuery JavaScript Library v1.4.2 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Sat Feb 13 22:33:48 2010 -0500 */ (function(aM,C){var a=function(aY,aZ){return new a.fn.init(aY,aZ)},n=aM.jQuery,R=aM.$,ab=aM.document,X,P=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,aW=/^.[^:#\[\.,]*$/,ax=/\S/,M=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,e=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,b=navigator.userAgent,u,K=false,ad=[],aG,at=Object.prototype.toString,ap=Object.prototype.hasOwnProperty,g=Array.prototype.push,F=Array.prototype.slice,s=Array.prototype.indexOf;a.fn=a.prototype={init:function(aY,a1){var a0,a2,aZ,a3;if(!aY){return this}if(aY.nodeType){this.context=this[0]=aY;this.length=1;return this}if(aY==="body"&&!a1){this.context=ab;this[0]=ab.body;this.selector="body";this.length=1;return this}if(typeof aY==="string"){a0=P.exec(aY);if(a0&&(a0[1]||!a1)){if(a0[1]){a3=(a1?a1.ownerDocument||a1:ab);aZ=e.exec(aY);if(aZ){if(a.isPlainObject(a1)){aY=[ab.createElement(aZ[1])];a.fn.attr.call(aY,a1,true)}else{aY=[a3.createElement(aZ[1])]}}else{aZ=J([a0[1]],[a3]);aY=(aZ.cacheable?aZ.fragment.cloneNode(true):aZ.fragment).childNodes}return a.merge(this,aY)}else{a2=ab.getElementById(a0[2]);if(a2){if(a2.id!==a0[2]){return X.find(aY)}this.length=1;this[0]=a2}this.context=ab;this.selector=aY;return this}}else{if(!a1&&/^\w+$/.test(aY)){this.selector=aY;this.context=ab;aY=ab.getElementsByTagName(aY);return a.merge(this,aY)}else{if(!a1||a1.jquery){return(a1||X).find(aY)}else{return a(a1).find(aY)}}}}else{if(a.isFunction(aY)){return X.ready(aY)}}if(aY.selector!==C){this.selector=aY.selector;this.context=aY.context}return a.makeArray(aY,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(aY){return aY==null?this.toArray():(aY<0?this.slice(aY)[0]:this[aY])},pushStack:function(aZ,a1,aY){var a0=a();if(a.isArray(aZ)){g.apply(a0,aZ)}else{a.merge(a0,aZ)}a0.prevObject=this;a0.context=this.context;if(a1==="find"){a0.selector=this.selector+(this.selector?" ":"")+aY}else{if(a1){a0.selector=this.selector+"."+a1+"("+aY+")"}}return a0},each:function(aZ,aY){return a.each(this,aZ,aY)},ready:function(aY){a.bindReady();if(a.isReady){aY.call(ab,a)}else{if(ad){ad.push(aY)}}return this},eq:function(aY){return aY===-1?this.slice(aY):this.slice(aY,+aY+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(aY){return this.pushStack(a.map(this,function(a0,aZ){return aY.call(a0,aZ,a0)}))},end:function(){return this.prevObject||a(null)},push:g,sort:[].sort,splice:[].splice};a.fn.init.prototype=a.fn;a.extend=a.fn.extend=function(){var a3=arguments[0]||{},a2=1,a1=arguments.length,a5=false,a6,a0,aY,aZ;if(typeof a3==="boolean"){a5=a3;a3=arguments[1]||{};a2=2}if(typeof a3!=="object"&&!a.isFunction(a3)){a3={}}if(a1===a2){a3=this;--a2}for(;a2<a1;a2++){if((a6=arguments[a2])!=null){for(a0 in a6){aY=a3[a0];aZ=a6[a0];if(a3===aZ){continue}if(a5&&aZ&&(a.isPlainObject(aZ)||a.isArray(aZ))){var a4=aY&&(a.isPlainObject(aY)||a.isArray(aY))?aY:a.isArray(aZ)?[]:{};a3[a0]=a.extend(a5,a4,aZ)}else{if(aZ!==C){a3[a0]=aZ}}}}}return a3};a.extend({noConflict:function(aY){aM.$=R;if(aY){aM.jQuery=n}return a},isReady:false,ready:function(){if(!a.isReady){if(!ab.body){return setTimeout(a.ready,13)}a.isReady=true;if(ad){var aZ,aY=0;while((aZ=ad[aY++])){aZ.call(ab,a)}ad=null}if(a.fn.triggerHandler){a(ab).triggerHandler("ready")}}},bindReady:function(){if(K){return}K=true;if(ab.readyState==="complete"){return a.ready()}if(ab.addEventListener){ab.addEventListener("DOMContentLoaded",aG,false);aM.addEventListener("load",a.ready,false)}else{if(ab.attachEvent){ab.attachEvent("onreadystatechange",aG);aM.attachEvent("onload",a.ready);var aY=false;try{aY=aM.frameElement==null}catch(aZ){}if(ab.documentElement.doScroll&&aY){x()}}}},isFunction:function(aY){return at.call(aY)==="[object Function]"},isArray:function(aY){return at.call(aY)==="[object Array]"},isPlainObject:function(aZ){if(!aZ||at.call(aZ)!=="[object Object]"||aZ.nodeType||aZ.setInterval){return false}if(aZ.constructor&&!ap.call(aZ,"constructor")&&!ap.call(aZ.constructor.prototype,"isPrototypeOf")){return false}var aY;for(aY in aZ){}return aY===C||ap.call(aZ,aY)},isEmptyObject:function(aZ){for(var aY in aZ){return false}return true},error:function(aY){throw aY},parseJSON:function(aY){if(typeof aY!=="string"||!aY){return null}aY=a.trim(aY);if(/^[\],:{}\s]*$/.test(aY.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){return aM.JSON&&aM.JSON.parse?aM.JSON.parse(aY):(new Function("return "+aY))()}else{a.error("Invalid JSON: "+aY)}},noop:function(){},globalEval:function(a0){if(a0&&ax.test(a0)){var aZ=ab.getElementsByTagName("head")[0]||ab.documentElement,aY=ab.createElement("script");aY.type="text/javascript";if(a.support.scriptEval){aY.appendChild(ab.createTextNode(a0))}else{aY.text=a0}aZ.insertBefore(aY,aZ.firstChild);aZ.removeChild(aY)}},nodeName:function(aZ,aY){return aZ.nodeName&&aZ.nodeName.toUpperCase()===aY.toUpperCase()},each:function(a1,a5,a0){var aZ,a2=0,a3=a1.length,aY=a3===C||a.isFunction(a1);if(a0){if(aY){for(aZ in a1){if(a5.apply(a1[aZ],a0)===false){break}}}else{for(;a2<a3;){if(a5.apply(a1[a2++],a0)===false){break}}}}else{if(aY){for(aZ in a1){if(a5.call(a1[aZ],aZ,a1[aZ])===false){break}}}else{for(var a4=a1[0];a2<a3&&a5.call(a4,a2,a4)!==false;a4=a1[++a2]){}}}return a1},trim:function(aY){return(aY||"").replace(M,"")},makeArray:function(a0,aZ){var aY=aZ||[];if(a0!=null){if(a0.length==null||typeof a0==="string"||a.isFunction(a0)||(typeof a0!=="function"&&a0.setInterval)){g.call(aY,a0)}else{a.merge(aY,a0)}}return aY},inArray:function(a0,a1){if(a1.indexOf){return a1.indexOf(a0)}for(var aY=0,aZ=a1.length;aY<aZ;aY++){if(a1[aY]===a0){return aY}}return -1},merge:function(a2,a0){var a1=a2.length,aZ=0;if(typeof a0.length==="number"){for(var aY=a0.length;aZ<aY;aZ++){a2[a1++]=a0[aZ]}}else{while(a0[aZ]!==C){a2[a1++]=a0[aZ++]}}a2.length=a1;return a2},grep:function(aZ,a3,aY){var a0=[];for(var a1=0,a2=aZ.length;a1<a2;a1++){if(!aY!==!a3(aZ[a1],a1)){a0.push(aZ[a1])}}return a0},map:function(aZ,a4,aY){var a0=[],a3;for(var a1=0,a2=aZ.length;a1<a2;a1++){a3=a4(aZ[a1],a1,aY);if(a3!=null){a0[a0.length]=a3}}return a0.concat.apply([],a0)},guid:1,proxy:function(a0,aZ,aY){if(arguments.length===2){if(typeof aZ==="string"){aY=a0;a0=aY[aZ];aZ=C}else{if(aZ&&!a.isFunction(aZ)){aY=aZ;aZ=C}}}if(!aZ&&a0){aZ=function(){return a0.apply(aY||this,arguments)}}if(a0){aZ.guid=a0.guid=a0.guid||aZ.guid||a.guid++}return aZ},uaMatch:function(aZ){aZ=aZ.toLowerCase();var aY=/(webkit)[ \/]([\w.]+)/.exec(aZ)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(aZ)||/(msie) ([\w.]+)/.exec(aZ)||!/compatible/.test(aZ)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(aZ)||[];return{browser:aY[1]||"",version:aY[2]||"0"}},browser:{}});u=a.uaMatch(b);if(u.browser){a.browser[u.browser]=true;a.browser.version=u.version}if(a.browser.webkit){a.browser.safari=true}if(s){a.inArray=function(aY,aZ){return s.call(aZ,aY)}}X=a(ab);if(ab.addEventListener){aG=function(){ab.removeEventListener("DOMContentLoaded",aG,false);a.ready()}}else{if(ab.attachEvent){aG=function(){if(ab.readyState==="complete"){ab.detachEvent("onreadystatechange",aG);a.ready()}}}}function x(){if(a.isReady){return}try{ab.documentElement.doScroll("left")}catch(aY){setTimeout(x,1);return}a.ready()}function aV(aY,aZ){if(aZ.src){a.ajax({url:aZ.src,async:false,dataType:"script"})}else{a.globalEval(aZ.text||aZ.textContent||aZ.innerHTML||"")}if(aZ.parentNode){aZ.parentNode.removeChild(aZ)}}function an(aY,a6,a4,a0,a3,a5){var aZ=aY.length;if(typeof a6==="object"){for(var a1 in a6){an(aY,a1,a6[a1],a0,a3,a4)}return aY}if(a4!==C){a0=!a5&&a0&&a.isFunction(a4);for(var a2=0;a2<aZ;a2++){a3(aY[a2],a6,a0?a4.call(aY[a2],a2,a3(aY[a2],a6)):a4,a5)}return aY}return aZ?a3(aY[0],a6):C}function aP(){return(new Date).getTime()}(function(){a.support={};var a4=ab.documentElement,a3=ab.createElement("script"),aY=ab.createElement("div"),aZ="script"+aP();aY.style.display="none";aY.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var a6=aY.getElementsByTagName("*"),a5=aY.getElementsByTagName("a")[0];if(!a6||!a6.length||!a5){return}a.support={leadingWhitespace:aY.firstChild.nodeType===3,tbody:!aY.getElementsByTagName("tbody").length,htmlSerialize:!!aY.getElementsByTagName("link").length,style:/red/.test(a5.getAttribute("style")),hrefNormalized:a5.getAttribute("href")==="/a",opacity:/^0.55$/.test(a5.style.opacity),cssFloat:!!a5.style.cssFloat,checkOn:aY.getElementsByTagName("input")[0].value==="on",optSelected:ab.createElement("select").appendChild(ab.createElement("option")).selected,parentNode:aY.removeChild(aY.appendChild(ab.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};a3.type="text/javascript";try{a3.appendChild(ab.createTextNode("window."+aZ+"=1;"))}catch(a1){}a4.insertBefore(a3,a4.firstChild);if(aM[aZ]){a.support.scriptEval=true;delete aM[aZ]}try{delete a3.test}catch(a1){a.support.deleteExpando=false}a4.removeChild(a3);if(aY.attachEvent&&aY.fireEvent){aY.attachEvent("onclick",function a7(){a.support.noCloneEvent=false;aY.detachEvent("onclick",a7)});aY.cloneNode(true).fireEvent("onclick")}aY=ab.createElement("div");aY.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var a0=ab.createDocumentFragment();a0.appendChild(aY.firstChild);a.support.checkClone=a0.cloneNode(true).cloneNode(true).lastChild.checked;a(function(){var a8=ab.createElement("div");a8.style.width=a8.style.paddingLeft="1px";ab.body.appendChild(a8);a.boxModel=a.support.boxModel=a8.offsetWidth===2;ab.body.removeChild(a8).style.display="none";a8=null});var a2=function(a8){var ba=ab.createElement("div");a8="on"+a8;var a9=(a8 in ba);if(!a9){ba.setAttribute(a8,"return;");a9=typeof ba[a8]==="function"}ba=null;return a9};a.support.submitBubbles=a2("submit");a.support.changeBubbles=a2("change");a4=a3=aY=a6=a5=null})();a.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var aI="jQuery"+aP(),aH=0,aT={};a.extend({cache:{},expando:aI,noData:{embed:true,object:true,applet:true},data:function(a0,aZ,a2){if(a0.nodeName&&a.noData[a0.nodeName.toLowerCase()]){return}a0=a0==aM?aT:a0;var a3=a0[aI],aY=a.cache,a1;if(!a3&&typeof aZ==="string"&&a2===C){return null}if(!a3){a3=++aH}if(typeof aZ==="object"){a0[aI]=a3;a1=aY[a3]=a.extend(true,{},aZ)}else{if(!aY[a3]){a0[aI]=a3;aY[a3]={}}}a1=aY[a3];if(a2!==C){a1[aZ]=a2}return typeof aZ==="string"?a1[aZ]:a1},removeData:function(a0,aZ){if(a0.nodeName&&a.noData[a0.nodeName.toLowerCase()]){return}a0=a0==aM?aT:a0;var a2=a0[aI],aY=a.cache,a1=aY[a2];if(aZ){if(a1){delete a1[aZ];if(a.isEmptyObject(a1)){a.removeData(a0)}}}else{if(a.support.deleteExpando){delete a0[a.expando]}else{if(a0.removeAttribute){a0.removeAttribute(a.expando)}}delete aY[a2]}}});a.fn.extend({data:function(aY,a0){if(typeof aY==="undefined"&&this.length){return a.data(this[0])}else{if(typeof aY==="object"){return this.each(function(){a.data(this,aY)})}}var a1=aY.split(".");a1[1]=a1[1]?"."+a1[1]:"";if(a0===C){var aZ=this.triggerHandler("getData"+a1[1]+"!",[a1[0]]);if(aZ===C&&this.length){aZ=a.data(this[0],aY)}return aZ===C&&a1[1]?this.data(a1[0]):aZ}else{return this.trigger("setData"+a1[1]+"!",[a1[0],a0]).each(function(){a.data(this,aY,a0)})}},removeData:function(aY){return this.each(function(){a.removeData(this,aY)})}});a.extend({queue:function(aZ,aY,a1){if(!aZ){return}aY=(aY||"fx")+"queue";var a0=a.data(aZ,aY);if(!a1){return a0||[]}if(!a0||a.isArray(a1)){a0=a.data(aZ,aY,a.makeArray(a1))}else{a0.push(a1)}return a0},dequeue:function(a1,a0){a0=a0||"fx";var aY=a.queue(a1,a0),aZ=aY.shift();if(aZ==="inprogress"){aZ=aY.shift()}if(aZ){if(a0==="fx"){aY.unshift("inprogress")}aZ.call(a1,function(){a.dequeue(a1,a0)})}}});a.fn.extend({queue:function(aY,aZ){if(typeof aY!=="string"){aZ=aY;aY="fx"}if(aZ===C){return a.queue(this[0],aY)}return this.each(function(a1,a2){var a0=a.queue(this,aY,aZ);if(aY==="fx"&&a0[0]!=="inprogress"){a.dequeue(this,aY)}})},dequeue:function(aY){return this.each(function(){a.dequeue(this,aY)})},delay:function(aZ,aY){aZ=a.fx?a.fx.speeds[aZ]||aZ:aZ;aY=aY||"fx";return this.queue(aY,function(){var a0=this;setTimeout(function(){a.dequeue(a0,aY)},aZ)})},clearQueue:function(aY){return this.queue(aY||"fx",[])}});var ao=/[\n\t]/g,S=/\s+/,av=/\r/g,aQ=/href|src|style/,d=/(button|input)/i,z=/(button|input|object|select|textarea)/i,j=/^(a|area)$/i,I=/radio|checkbox/;a.fn.extend({attr:function(aY,aZ){return an(this,aY,aZ,true,a.attr)},removeAttr:function(aY,aZ){return this.each(function(){a.attr(this,aY,"");if(this.nodeType===1){this.removeAttribute(aY)}})},addClass:function(a5){if(a.isFunction(a5)){return this.each(function(a8){var a7=a(this);a7.addClass(a5.call(this,a8,a7.attr("class")))})}if(a5&&typeof a5==="string"){var aY=(a5||"").split(S);for(var a1=0,a0=this.length;a1<a0;a1++){var aZ=this[a1];if(aZ.nodeType===1){if(!aZ.className){aZ.className=a5}else{var a2=" "+aZ.className+" ",a4=aZ.className;for(var a3=0,a6=aY.length;a3<a6;a3++){if(a2.indexOf(" "+aY[a3]+" ")<0){a4+=" "+aY[a3]}}aZ.className=a.trim(a4)}}}}return this},removeClass:function(a3){if(a.isFunction(a3)){return this.each(function(a7){var a6=a(this);a6.removeClass(a3.call(this,a7,a6.attr("class")))})}if((a3&&typeof a3==="string")||a3===C){var a4=(a3||"").split(S);for(var a0=0,aZ=this.length;a0<aZ;a0++){var a2=this[a0];if(a2.nodeType===1&&a2.className){if(a3){var a1=(" "+a2.className+" ").replace(ao," ");for(var a5=0,aY=a4.length;a5<aY;a5++){a1=a1.replace(" "+a4[a5]+" "," ")}a2.className=a.trim(a1)}else{a2.className=""}}}}return this},toggleClass:function(a1,aZ){var a0=typeof a1,aY=typeof aZ==="boolean";if(a.isFunction(a1)){return this.each(function(a3){var a2=a(this);a2.toggleClass(a1.call(this,a3,a2.attr("class"),aZ),aZ)})}return this.each(function(){if(a0==="string"){var a4,a3=0,a2=a(this),a5=aZ,a6=a1.split(S);while((a4=a6[a3++])){a5=aY?a5:!a2.hasClass(a4);a2[a5?"addClass":"removeClass"](a4)}}else{if(a0==="undefined"||a0==="boolean"){if(this.className){a.data(this,"__className__",this.className)}this.className=this.className||a1===false?"":a.data(this,"__className__")||""}}})},hasClass:function(aY){var a1=" "+aY+" ";for(var a0=0,aZ=this.length;a0<aZ;a0++){if((" "+this[a0].className+" ").replace(ao," ").indexOf(a1)>-1){return true}}return false},val:function(a5){if(a5===C){var aZ=this[0];if(aZ){if(a.nodeName(aZ,"option")){return(aZ.attributes.value||{}).specified?aZ.value:aZ.text}if(a.nodeName(aZ,"select")){var a3=aZ.selectedIndex,a6=[],a7=aZ.options,a2=aZ.type==="select-one";if(a3<0){return null}for(var a0=a2?a3:0,a4=a2?a3+1:a7.length;a0<a4;a0++){var a1=a7[a0];if(a1.selected){a5=a(a1).val();if(a2){return a5}a6.push(a5)}}return a6}if(I.test(aZ.type)&&!a.support.checkOn){return aZ.getAttribute("value")===null?"on":aZ.value}return(aZ.value||"").replace(av,"")}return C}var aY=a.isFunction(a5);return this.each(function(ba){var a9=a(this),bb=a5;if(this.nodeType!==1){return}if(aY){bb=a5.call(this,ba,a9.val())}if(typeof bb==="number"){bb+=""}if(a.isArray(bb)&&I.test(this.type)){this.checked=a.inArray(a9.val(),bb)>=0}else{if(a.nodeName(this,"select")){var a8=a.makeArray(bb);a("option",this).each(function(){this.selected=a.inArray(a(this).val(),a8)>=0});if(!a8.length){this.selectedIndex=-1}}else{this.value=bb}}})}});a.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(aZ,aY,a4,a7){if(!aZ||aZ.nodeType===3||aZ.nodeType===8){return C}if(a7&&aY in a.attrFn){return a(aZ)[aY](a4)}var a0=aZ.nodeType!==1||!a.isXMLDoc(aZ),a3=a4!==C;aY=a0&&a.props[aY]||aY;if(aZ.nodeType===1){var a2=aQ.test(aY);if(aY==="selected"&&!a.support.optSelected){var a5=aZ.parentNode;if(a5){a5.selectedIndex;if(a5.parentNode){a5.parentNode.selectedIndex}}}if(aY in aZ&&a0&&!a2){if(a3){if(aY==="type"&&d.test(aZ.nodeName)&&aZ.parentNode){a.error("type property can't be changed")}aZ[aY]=a4}if(a.nodeName(aZ,"form")&&aZ.getAttributeNode(aY)){return aZ.getAttributeNode(aY).nodeValue}if(aY==="tabIndex"){var a6=aZ.getAttributeNode("tabIndex");return a6&&a6.specified?a6.value:z.test(aZ.nodeName)||j.test(aZ.nodeName)&&aZ.href?0:C}return aZ[aY]}if(!a.support.style&&a0&&aY==="style"){if(a3){aZ.style.cssText=""+a4}return aZ.style.cssText}if(a3){aZ.setAttribute(aY,""+a4)}var a1=!a.support.hrefNormalized&&a0&&a2?aZ.getAttribute(aY,2):aZ.getAttribute(aY);return a1===null?C:a1}return a.style(aZ,aY,a4)}});var aC=/\.(.*)$/,A=function(aY){return aY.replace(/[^\w\s\.\|`]/g,function(aZ){return"\\"+aZ})};a.event={add:function(a1,a5,ba,a3){if(a1.nodeType===3||a1.nodeType===8){return}if(a1.setInterval&&(a1!==aM&&!a1.frameElement)){a1=aM}var aZ,a9;if(ba.handler){aZ=ba;ba=aZ.handler}if(!ba.guid){ba.guid=a.guid++}var a6=a.data(a1);if(!a6){return}var bb=a6.events=a6.events||{},a4=a6.handle,a4;if(!a4){a6.handle=a4=function(){return typeof a!=="undefined"&&!a.event.triggered?a.event.handle.apply(a4.elem,arguments):C}}a4.elem=a1;a5=a5.split(" ");var a8,a2=0,aY;while((a8=a5[a2++])){a9=aZ?a.extend({},aZ):{handler:ba,data:a3};if(a8.indexOf(".")>-1){aY=a8.split(".");a8=aY.shift();a9.namespace=aY.slice(0).sort().join(".")}else{aY=[];a9.namespace=""}a9.type=a8;a9.guid=ba.guid;var a0=bb[a8],a7=a.event.special[a8]||{};if(!a0){a0=bb[a8]=[];if(!a7.setup||a7.setup.call(a1,a3,aY,a4)===false){if(a1.addEventListener){a1.addEventListener(a8,a4,false)}else{if(a1.attachEvent){a1.attachEvent("on"+a8,a4)}}}}if(a7.add){a7.add.call(a1,a9);if(!a9.handler.guid){a9.handler.guid=ba.guid}}a0.push(a9);a.event.global[a8]=true}a1=null},global:{},remove:function(bd,a8,aZ,a4){if(bd.nodeType===3||bd.nodeType===8){return}var bg,a3,a5,bb=0,a1,a6,a9,a2,a7,aY,bf,bc=a.data(bd),a0=bc&&bc.events;if(!bc||!a0){return}if(a8&&a8.type){aZ=a8.handler;a8=a8.type}if(!a8||typeof a8==="string"&&a8.charAt(0)==="."){a8=a8||"";for(a3 in a0){a.event.remove(bd,a3+a8)}return}a8=a8.split(" ");while((a3=a8[bb++])){bf=a3;aY=null;a1=a3.indexOf(".")<0;a6=[];if(!a1){a6=a3.split(".");a3=a6.shift();a9=new RegExp("(^|\\.)"+a.map(a6.slice(0).sort(),A).join("\\.(?:.*\\.)?")+"(\\.|$)")}a7=a0[a3];if(!a7){continue}if(!aZ){for(var ba=0;ba<a7.length;ba++){aY=a7[ba];if(a1||a9.test(aY.namespace)){a.event.remove(bd,bf,aY.handler,ba);a7.splice(ba--,1)}}continue}a2=a.event.special[a3]||{};for(var ba=a4||0;ba<a7.length;ba++){aY=a7[ba];if(aZ.guid===aY.guid){if(a1||a9.test(aY.namespace)){if(a4==null){a7.splice(ba--,1)}if(a2.remove){a2.remove.call(bd,aY)}}if(a4!=null){break}}}if(a7.length===0||a4!=null&&a7.length===1){if(!a2.teardown||a2.teardown.call(bd,a6)===false){ag(bd,a3,bc.handle)}bg=null;delete a0[a3]}}if(a.isEmptyObject(a0)){var be=bc.handle;if(be){be.elem=null}delete bc.events;delete bc.handle;if(a.isEmptyObject(bc)){a.removeData(bd)}}},trigger:function(aY,a2,a0){var a7=aY.type||aY,a1=arguments[3];if(!a1){aY=typeof aY==="object"?aY[aI]?aY:a.extend(a.Event(a7),aY):a.Event(a7);if(a7.indexOf("!")>=0){aY.type=a7=a7.slice(0,-1);aY.exclusive=true}if(!a0){aY.stopPropagation();if(a.event.global[a7]){a.each(a.cache,function(){if(this.events&&this.events[a7]){a.event.trigger(aY,a2,this.handle.elem)}})}}if(!a0||a0.nodeType===3||a0.nodeType===8){return C}aY.result=C;aY.target=a0;a2=a.makeArray(a2);a2.unshift(aY)}aY.currentTarget=a0;var a3=a.data(a0,"handle");if(a3){a3.apply(a0,a2)}var a8=a0.parentNode||a0.ownerDocument;try{if(!(a0&&a0.nodeName&&a.noData[a0.nodeName.toLowerCase()])){if(a0["on"+a7]&&a0["on"+a7].apply(a0,a2)===false){aY.result=false}}}catch(a5){}if(!aY.isPropagationStopped()&&a8){a.event.trigger(aY,a2,a8,true)}else{if(!aY.isDefaultPrevented()){var a4=aY.target,aZ,a9=a.nodeName(a4,"a")&&a7==="click",a6=a.event.special[a7]||{};if((!a6._default||a6._default.call(a0,aY)===false)&&!a9&&!(a4&&a4.nodeName&&a.noData[a4.nodeName.toLowerCase()])){try{if(a4[a7]){aZ=a4["on"+a7];if(aZ){a4["on"+a7]=null}a.event.triggered=true;a4[a7]()}}catch(a5){}if(aZ){a4["on"+a7]=aZ}a.event.triggered=false}}}},handle:function(aY){var a6,a0,aZ,a1,a7;aY=arguments[0]=a.event.fix(aY||aM.event);aY.currentTarget=this;a6=aY.type.indexOf(".")<0&&!aY.exclusive;if(!a6){aZ=aY.type.split(".");aY.type=aZ.shift();a1=new RegExp("(^|\\.)"+aZ.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}var a7=a.data(this,"events"),a0=a7[aY.type];if(a7&&a0){a0=a0.slice(0);for(var a3=0,a2=a0.length;a3<a2;a3++){var a5=a0[a3];if(a6||a1.test(a5.namespace)){aY.handler=a5.handler;aY.data=a5.data;aY.handleObj=a5;var a4=a5.handler.apply(this,arguments);if(a4!==C){aY.result=a4;if(a4===false){aY.preventDefault();aY.stopPropagation()}}if(aY.isImmediatePropagationStopped()){break}}}}return aY.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a1){if(a1[aI]){return a1}var aZ=a1;a1=a.Event(aZ);for(var a0=this.props.length,a3;a0;){a3=this.props[--a0];a1[a3]=aZ[a3]}if(!a1.target){a1.target=a1.srcElement||ab}if(a1.target.nodeType===3){a1.target=a1.target.parentNode}if(!a1.relatedTarget&&a1.fromElement){a1.relatedTarget=a1.fromElement===a1.target?a1.toElement:a1.fromElement}if(a1.pageX==null&&a1.clientX!=null){var a2=ab.documentElement,aY=ab.body;a1.pageX=a1.clientX+(a2&&a2.scrollLeft||aY&&aY.scrollLeft||0)-(a2&&a2.clientLeft||aY&&aY.clientLeft||0);a1.pageY=a1.clientY+(a2&&a2.scrollTop||aY&&aY.scrollTop||0)-(a2&&a2.clientTop||aY&&aY.clientTop||0)}if(!a1.which&&((a1.charCode||a1.charCode===0)?a1.charCode:a1.keyCode)){a1.which=a1.charCode||a1.keyCode}if(!a1.metaKey&&a1.ctrlKey){a1.metaKey=a1.ctrlKey}if(!a1.which&&a1.button!==C){a1.which=(a1.button&1?1:(a1.button&2?3:(a1.button&4?2:0)))}return a1},guid:100000000,proxy:a.proxy,special:{ready:{setup:a.bindReady,teardown:a.noop},live:{add:function(aY){a.event.add(this,aY.origType,a.extend({},aY,{handler:V}))},remove:function(aZ){var aY=true,a0=aZ.origType.replace(aC,"");a.each(a.data(this,"events").live||[],function(){if(a0===this.origType.replace(aC,"")){aY=false;return false}});if(aY){a.event.remove(this,aZ.origType,V)}}},beforeunload:{setup:function(a0,aZ,aY){if(this.setInterval){this.onbeforeunload=aY}return false},teardown:function(aZ,aY){if(this.onbeforeunload===aY){this.onbeforeunload=null}}}}};var ag=ab.removeEventListener?function(aZ,aY,a0){aZ.removeEventListener(aY,a0,false)}:function(aZ,aY,a0){aZ.detachEvent("on"+aY,a0)};a.Event=function(aY){if(!this.preventDefault){return new a.Event(aY)}if(aY&&aY.type){this.originalEvent=aY;this.type=aY.type}else{this.type=aY}this.timeStamp=aP();this[aI]=true};function aR(){return false}function f(){return true}a.Event.prototype={preventDefault:function(){this.isDefaultPrevented=f;var aY=this.originalEvent;if(!aY){return}if(aY.preventDefault){aY.preventDefault()}aY.returnValue=false},stopPropagation:function(){this.isPropagationStopped=f;var aY=this.originalEvent;if(!aY){return}if(aY.stopPropagation){aY.stopPropagation()}aY.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=f;this.stopPropagation()},isDefaultPrevented:aR,isPropagationStopped:aR,isImmediatePropagationStopped:aR};var Q=function(aZ){var aY=aZ.relatedTarget;try{while(aY&&aY!==this){aY=aY.parentNode}if(aY!==this){aZ.type=aZ.data;a.event.handle.apply(this,arguments)}}catch(a0){}},ay=function(aY){aY.type=aY.data;a.event.handle.apply(this,arguments)};a.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(aZ,aY){a.event.special[aZ]={setup:function(a0){a.event.add(this,aY,a0&&a0.selector?ay:Q,aZ)},teardown:function(a0){a.event.remove(this,aY,a0&&a0.selector?ay:Q)}}});if(!a.support.submitBubbles){a.event.special.submit={setup:function(aZ,aY){if(this.nodeName.toLowerCase()!=="form"){a.event.add(this,"click.specialSubmit",function(a2){var a1=a2.target,a0=a1.type;if((a0==="submit"||a0==="image")&&a(a1).closest("form").length){return aA("submit",this,arguments)}});a.event.add(this,"keypress.specialSubmit",function(a2){var a1=a2.target,a0=a1.type;if((a0==="text"||a0==="password")&&a(a1).closest("form").length&&a2.keyCode===13){return aA("submit",this,arguments)}})}else{return false}},teardown:function(aY){a.event.remove(this,".specialSubmit")}}}if(!a.support.changeBubbles){var aq=/textarea|input|select/i,aS,i=function(aZ){var aY=aZ.type,a0=aZ.value;if(aY==="radio"||aY==="checkbox"){a0=aZ.checked}else{if(aY==="select-multiple"){a0=aZ.selectedIndex>-1?a.map(aZ.options,function(a1){return a1.selected}).join("-"):""}else{if(aZ.nodeName.toLowerCase()==="select"){a0=aZ.selectedIndex}}}return a0},O=function O(a0){var aY=a0.target,aZ,a1;if(!aq.test(aY.nodeName)||aY.readOnly){return}aZ=a.data(aY,"_change_data");a1=i(aY);if(a0.type!=="focusout"||aY.type!=="radio"){a.data(aY,"_change_data",a1)}if(aZ===C||a1===aZ){return}if(aZ!=null||a1){a0.type="change";return a.event.trigger(a0,arguments[1],aY)}};a.event.special.change={filters:{focusout:O,click:function(a0){var aZ=a0.target,aY=aZ.type;if(aY==="radio"||aY==="checkbox"||aZ.nodeName.toLowerCase()==="select"){return O.call(this,a0)}},keydown:function(a0){var aZ=a0.target,aY=aZ.type;if((a0.keyCode===13&&aZ.nodeName.toLowerCase()!=="textarea")||(a0.keyCode===32&&(aY==="checkbox"||aY==="radio"))||aY==="select-multiple"){return O.call(this,a0)}},beforeactivate:function(aZ){var aY=aZ.target;a.data(aY,"_change_data",i(aY))}},setup:function(a0,aZ){if(this.type==="file"){return false}for(var aY in aS){a.event.add(this,aY+".specialChange",aS[aY])}return aq.test(this.nodeName)},teardown:function(aY){a.event.remove(this,".specialChange");return aq.test(this.nodeName)}};aS=a.event.special.change.filters}function aA(aZ,a0,aY){aY[0].type=aZ;return a.event.handle.apply(a0,aY)}if(ab.addEventListener){a.each({focus:"focusin",blur:"focusout"},function(a0,aY){a.event.special[aY]={setup:function(){this.addEventListener(a0,aZ,true)},teardown:function(){this.removeEventListener(a0,aZ,true)}};function aZ(a1){a1=a.event.fix(a1);a1.type=aY;return a.event.handle.call(this,a1)}})}a.each(["bind","one"],function(aZ,aY){a.fn[aY]=function(a5,a6,a4){if(typeof a5==="object"){for(var a2 in a5){this[aY](a2,a6,a5[a2],a4)}return this}if(a.isFunction(a6)){a4=a6;a6=C}var a3=aY==="one"?a.proxy(a4,function(a7){a(this).unbind(a7,a3);return a4.apply(this,arguments)}):a4;if(a5==="unload"&&aY!=="one"){this.one(a5,a6,a4)}else{for(var a1=0,a0=this.length;a1<a0;a1++){a.event.add(this[a1],a5,a3,a6)}}return this}});a.fn.extend({unbind:function(a2,a1){if(typeof a2==="object"&&!a2.preventDefault){for(var a0 in a2){this.unbind(a0,a2[a0])}}else{for(var aZ=0,aY=this.length;aZ<aY;aZ++){a.event.remove(this[aZ],a2,a1)}}return this},delegate:function(aY,aZ,a1,a0){return this.live(aZ,a1,a0,aY)},undelegate:function(aY,aZ,a0){if(arguments.length===0){return this.unbind("live")}else{return this.die(aZ,null,a0,aY)}},trigger:function(aY,aZ){return this.each(function(){a.event.trigger(aY,aZ,this)})},triggerHandler:function(aY,a0){if(this[0]){var aZ=a.Event(aY);aZ.preventDefault();aZ.stopPropagation();a.event.trigger(aZ,a0,this[0]);return aZ.result}},toggle:function(a0){var aY=arguments,aZ=1;while(aZ<aY.length){a.proxy(a0,aY[aZ++])}return this.click(a.proxy(a0,function(a1){var a2=(a.data(this,"lastToggle"+a0.guid)||0)%aZ;a.data(this,"lastToggle"+a0.guid,a2+1);a1.preventDefault();return aY[a2].apply(this,arguments)||false}))},hover:function(aY,aZ){return this.mouseenter(aY).mouseleave(aZ||aY)}});var aw={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};a.each(["live","die"],function(aZ,aY){a.fn[aY]=function(a7,a4,a9,a2){var a8,a5=0,a6,a1,ba,a3=a2||this.selector,a0=a2?this:a(this.context);if(a.isFunction(a4)){a9=a4;a4=C}a7=(a7||"").split(" ");while((a8=a7[a5++])!=null){a6=aC.exec(a8);a1="";if(a6){a1=a6[0];a8=a8.replace(aC,"")}if(a8==="hover"){a7.push("mouseenter"+a1,"mouseleave"+a1);continue}ba=a8;if(a8==="focus"||a8==="blur"){a7.push(aw[a8]+a1);a8=a8+a1}else{a8=(aw[a8]||a8)+a1}if(aY==="live"){a0.each(function(){a.event.add(this,m(a8,a3),{data:a4,selector:a3,handler:a9,origType:a8,origHandler:a9,preType:ba})})}else{a0.unbind(m(a8,a3),a9)}}return this}});function V(aY){var a8,aZ=[],bb=[],a7=arguments,ba,a6,a9,a1,a3,a5,a2,a4,bc=a.data(this,"events");if(aY.liveFired===this||!bc||!bc.live||aY.button&&aY.type==="click"){return}aY.liveFired=this;var a0=bc.live.slice(0);for(a3=0;a3<a0.length;a3++){a9=a0[a3];if(a9.origType.replace(aC,"")===aY.type){bb.push(a9.selector)}else{a0.splice(a3--,1)}}a6=a(aY.target).closest(bb,aY.currentTarget);for(a5=0,a2=a6.length;a5<a2;a5++){for(a3=0;a3<a0.length;a3++){a9=a0[a3];if(a6[a5].selector===a9.selector){a1=a6[a5].elem;ba=null;if(a9.preType==="mouseenter"||a9.preType==="mouseleave"){ba=a(aY.relatedTarget).closest(a9.selector)[0]}if(!ba||ba!==a1){aZ.push({elem:a1,handleObj:a9})}}}}for(a5=0,a2=aZ.length;a5<a2;a5++){a6=aZ[a5];aY.currentTarget=a6.elem;aY.data=a6.handleObj.data;aY.handleObj=a6.handleObj;if(a6.handleObj.origHandler.apply(a6.elem,a7)===false){a8=false;break}}return a8}function m(aZ,aY){return"live."+(aZ&&aZ!=="*"?aZ+".":"")+aY.replace(/\./g,"`").replace(/ /g,"&")}a.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").split(" "),function(aZ,aY){a.fn[aY]=function(a0){return a0?this.bind(aY,a0):this.trigger(aY)};if(a.attrFn){a.attrFn[aY]=true}});if(aM.attachEvent&&!aM.addEventListener){aM.attachEvent("onunload",function(){for(var aZ in a.cache){if(a.cache[aZ].handle){try{a.event.remove(a.cache[aZ].handle.elem)}catch(aY){}}}}); /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ }(function(){var a9=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,ba=0,bc=Object.prototype.toString,a4=false,a3=true;[0,0].sort(function(){a3=false;return 0});var a0=function(bl,bg,bo,bp){bo=bo||[];var br=bg=bg||ab;if(bg.nodeType!==1&&bg.nodeType!==9){return[]}if(!bl||typeof bl!=="string"){return bo}var bm=[],bi,bt,bw,bh,bk=true,bj=a1(bg),bq=bl;while((a9.exec(""),bi=a9.exec(bq))!==null){bq=bi[3];bm.push(bi[1]);if(bi[2]){bh=bi[3];break}}if(bm.length>1&&a5.exec(bl)){if(bm.length===2&&a6.relative[bm[0]]){bt=bd(bm[0]+bm[1],bg)}else{bt=a6.relative[bm[0]]?[bg]:a0(bm.shift(),bg);while(bm.length){bl=bm.shift();if(a6.relative[bl]){bl+=bm.shift()}bt=bd(bl,bt)}}}else{if(!bp&&bm.length>1&&bg.nodeType===9&&!bj&&a6.match.ID.test(bm[0])&&!a6.match.ID.test(bm[bm.length-1])){var bs=a0.find(bm.shift(),bg,bj);bg=bs.expr?a0.filter(bs.expr,bs.set)[0]:bs.set[0]}if(bg){var bs=bp?{expr:bm.pop(),set:a8(bp)}:a0.find(bm.pop(),bm.length===1&&(bm[0]==="~"||bm[0]==="+")&&bg.parentNode?bg.parentNode:bg,bj);bt=bs.expr?a0.filter(bs.expr,bs.set):bs.set;if(bm.length>0){bw=a8(bt)}else{bk=false}while(bm.length){var bv=bm.pop(),bu=bv;if(!a6.relative[bv]){bv=""}else{bu=bm.pop()}if(bu==null){bu=bg}a6.relative[bv](bw,bu,bj)}}else{bw=bm=[]}}if(!bw){bw=bt}if(!bw){a0.error(bv||bl)}if(bc.call(bw)==="[object Array]"){if(!bk){bo.push.apply(bo,bw)}else{if(bg&&bg.nodeType===1){for(var bn=0;bw[bn]!=null;bn++){if(bw[bn]&&(bw[bn]===true||bw[bn].nodeType===1&&a7(bg,bw[bn]))){bo.push(bt[bn])}}}else{for(var bn=0;bw[bn]!=null;bn++){if(bw[bn]&&bw[bn].nodeType===1){bo.push(bt[bn])}}}}}else{a8(bw,bo)}if(bh){a0(bh,br,bo,bp);a0.uniqueSort(bo)}return bo};a0.uniqueSort=function(bh){if(bb){a4=a3;bh.sort(bb);if(a4){for(var bg=1;bg<bh.length;bg++){if(bh[bg]===bh[bg-1]){bh.splice(bg--,1)}}}}return bh};a0.matches=function(bg,bh){return a0(bg,null,null,bh)};a0.find=function(bn,bg,bo){var bm,bk;if(!bn){return[]}for(var bj=0,bi=a6.order.length;bj<bi;bj++){var bl=a6.order[bj],bk;if((bk=a6.leftMatch[bl].exec(bn))){var bh=bk[1];bk.splice(1,1);if(bh.substr(bh.length-1)!=="\\"){bk[1]=(bk[1]||"").replace(/\\/g,"");bm=a6.find[bl](bk,bg,bo);if(bm!=null){bn=bn.replace(a6.match[bl],"");break}}}}if(!bm){bm=bg.getElementsByTagName("*")}return{set:bm,expr:bn}};a0.filter=function(br,bq,bu,bk){var bi=br,bw=[],bo=bq,bm,bg,bn=bq&&bq[0]&&a1(bq[0]);while(br&&bq.length){for(var bp in a6.filter){if((bm=a6.leftMatch[bp].exec(br))!=null&&bm[2]){var bh=a6.filter[bp],bv,bt,bj=bm[1];bg=false;bm.splice(1,1);if(bj.substr(bj.length-1)==="\\"){continue}if(bo===bw){bw=[]}if(a6.preFilter[bp]){bm=a6.preFilter[bp](bm,bo,bu,bw,bk,bn);if(!bm){bg=bv=true}else{if(bm===true){continue}}}if(bm){for(var bl=0;(bt=bo[bl])!=null;bl++){if(bt){bv=bh(bt,bm,bl,bo);var bs=bk^!!bv;if(bu&&bv!=null){if(bs){bg=true}else{bo[bl]=false}}else{if(bs){bw.push(bt);bg=true}}}}}if(bv!==C){if(!bu){bo=bw}br=br.replace(a6.match[bp],"");if(!bg){return[]}break}}}if(br===bi){if(bg==null){a0.error(br)}else{break}}bi=br}return bo};a0.error=function(bg){throw"Syntax error, unrecognized expression: "+bg};var a6=a0.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|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(bg){return bg.getAttribute("href")}},relative:{"+":function(bm,bh){var bj=typeof bh==="string",bl=bj&&!/\W/.test(bh),bn=bj&&!bl;if(bl){bh=bh.toLowerCase()}for(var bi=0,bg=bm.length,bk;bi<bg;bi++){if((bk=bm[bi])){while((bk=bk.previousSibling)&&bk.nodeType!==1){}bm[bi]=bn||bk&&bk.nodeName.toLowerCase()===bh?bk||false:bk===bh}}if(bn){a0.filter(bh,bm,true)}},">":function(bm,bh){var bk=typeof bh==="string";if(bk&&!/\W/.test(bh)){bh=bh.toLowerCase();for(var bi=0,bg=bm.length;bi<bg;bi++){var bl=bm[bi];if(bl){var bj=bl.parentNode;bm[bi]=bj.nodeName.toLowerCase()===bh?bj:false}}}else{for(var bi=0,bg=bm.length;bi<bg;bi++){var bl=bm[bi];if(bl){bm[bi]=bk?bl.parentNode:bl.parentNode===bh}}if(bk){a0.filter(bh,bm,true)}}},"":function(bj,bh,bl){var bi=ba++,bg=be;if(typeof bh==="string"&&!/\W/.test(bh)){var bk=bh=bh.toLowerCase();bg=aY}bg("parentNode",bh,bi,bj,bk,bl)},"~":function(bj,bh,bl){var bi=ba++,bg=be;if(typeof bh==="string"&&!/\W/.test(bh)){var bk=bh=bh.toLowerCase();bg=aY}bg("previousSibling",bh,bi,bj,bk,bl)}},find:{ID:function(bh,bi,bj){if(typeof bi.getElementById!=="undefined"&&!bj){var bg=bi.getElementById(bh[1]);return bg?[bg]:[]}},NAME:function(bi,bl){if(typeof bl.getElementsByName!=="undefined"){var bh=[],bk=bl.getElementsByName(bi[1]);for(var bj=0,bg=bk.length;bj<bg;bj++){if(bk[bj].getAttribute("name")===bi[1]){bh.push(bk[bj])}}return bh.length===0?null:bh}},TAG:function(bg,bh){return bh.getElementsByTagName(bg[1])}},preFilter:{CLASS:function(bj,bh,bi,bg,bm,bn){bj=" "+bj[1].replace(/\\/g,"")+" ";if(bn){return bj}for(var bk=0,bl;(bl=bh[bk])!=null;bk++){if(bl){if(bm^(bl.className&&(" "+bl.className+" ").replace(/[\t\n]/g," ").indexOf(bj)>=0)){if(!bi){bg.push(bl)}}else{if(bi){bh[bk]=false}}}}return false},ID:function(bg){return bg[1].replace(/\\/g,"")},TAG:function(bh,bg){return bh[1].toLowerCase()},CHILD:function(bg){if(bg[1]==="nth"){var bh=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(bg[2]==="even"&&"2n"||bg[2]==="odd"&&"2n+1"||!/\D/.test(bg[2])&&"0n+"+bg[2]||bg[2]);bg[2]=(bh[1]+(bh[2]||1))-0;bg[3]=bh[3]-0}bg[0]=ba++;return bg},ATTR:function(bk,bh,bi,bg,bl,bm){var bj=bk[1].replace(/\\/g,"");if(!bm&&a6.attrMap[bj]){bk[1]=a6.attrMap[bj]}if(bk[2]==="~="){bk[4]=" "+bk[4]+" "}return bk},PSEUDO:function(bk,bh,bi,bg,bl){if(bk[1]==="not"){if((a9.exec(bk[3])||"").length>1||/^\w/.test(bk[3])){bk[3]=a0(bk[3],null,null,bh)}else{var bj=a0.filter(bk[3],bh,bi,true^bl);if(!bi){bg.push.apply(bg,bj)}return false}}else{if(a6.match.POS.test(bk[0])||a6.match.CHILD.test(bk[0])){return true}}return bk},POS:function(bg){bg.unshift(true);return bg}},filters:{enabled:function(bg){return bg.disabled===false&&bg.type!=="hidden"},disabled:function(bg){return bg.disabled===true},checked:function(bg){return bg.checked===true},selected:function(bg){bg.parentNode.selectedIndex;return bg.selected===true},parent:function(bg){return !!bg.firstChild},empty:function(bg){return !bg.firstChild},has:function(bi,bh,bg){return !!a0(bg[3],bi).length},header:function(bg){return/h\d/i.test(bg.nodeName)},text:function(bg){return"text"===bg.type},radio:function(bg){return"radio"===bg.type},checkbox:function(bg){return"checkbox"===bg.type},file:function(bg){return"file"===bg.type},password:function(bg){return"password"===bg.type},submit:function(bg){return"submit"===bg.type},image:function(bg){return"image"===bg.type},reset:function(bg){return"reset"===bg.type},button:function(bg){return"button"===bg.type||bg.nodeName.toLowerCase()==="button"},input:function(bg){return/input|select|textarea|button/i.test(bg.nodeName)}},setFilters:{first:function(bh,bg){return bg===0},last:function(bi,bh,bg,bj){return bh===bj.length-1},even:function(bh,bg){return bg%2===0},odd:function(bh,bg){return bg%2===1},lt:function(bi,bh,bg){return bh<bg[3]-0},gt:function(bi,bh,bg){return bh>bg[3]-0},nth:function(bi,bh,bg){return bg[3]-0===bh},eq:function(bi,bh,bg){return bg[3]-0===bh}},filter:{PSEUDO:function(bm,bi,bj,bn){var bh=bi[1],bk=a6.filters[bh];if(bk){return bk(bm,bj,bi,bn)}else{if(bh==="contains"){return(bm.textContent||bm.innerText||aZ([bm])||"").indexOf(bi[3])>=0}else{if(bh==="not"){var bl=bi[3];for(var bj=0,bg=bl.length;bj<bg;bj++){if(bl[bj]===bm){return false}}return true}else{a0.error("Syntax error, unrecognized expression: "+bh)}}}},CHILD:function(bg,bj){var bm=bj[1],bh=bg;switch(bm){case"only":case"first":while((bh=bh.previousSibling)){if(bh.nodeType===1){return false}}if(bm==="first"){return true}bh=bg;case"last":while((bh=bh.nextSibling)){if(bh.nodeType===1){return false}}return true;case"nth":var bi=bj[2],bp=bj[3];if(bi===1&&bp===0){return true}var bl=bj[0],bo=bg.parentNode;if(bo&&(bo.sizcache!==bl||!bg.nodeIndex)){var bk=0;for(bh=bo.firstChild;bh;bh=bh.nextSibling){if(bh.nodeType===1){bh.nodeIndex=++bk}}bo.sizcache=bl}var bn=bg.nodeIndex-bp;if(bi===0){return bn===0}else{return(bn%bi===0&&bn/bi>=0)}}},ID:function(bh,bg){return bh.nodeType===1&&bh.getAttribute("id")===bg},TAG:function(bh,bg){return(bg==="*"&&bh.nodeType===1)||bh.nodeName.toLowerCase()===bg},CLASS:function(bh,bg){return(" "+(bh.className||bh.getAttribute("class"))+" ").indexOf(bg)>-1},ATTR:function(bl,bj){var bi=bj[1],bg=a6.attrHandle[bi]?a6.attrHandle[bi](bl):bl[bi]!=null?bl[bi]:bl.getAttribute(bi),bm=bg+"",bk=bj[2],bh=bj[4];return bg==null?bk==="!=":bk==="="?bm===bh:bk==="*="?bm.indexOf(bh)>=0:bk==="~="?(" "+bm+" ").indexOf(bh)>=0:!bh?bm&&bg!==false:bk==="!="?bm!==bh:bk==="^="?bm.indexOf(bh)===0:bk==="$="?bm.substr(bm.length-bh.length)===bh:bk==="|="?bm===bh||bm.substr(0,bh.length+1)===bh+"-":false},POS:function(bk,bh,bi,bl){var bg=bh[2],bj=a6.setFilters[bg];if(bj){return bj(bk,bi,bh,bl)}}}};var a5=a6.match.POS;for(var a2 in a6.match){a6.match[a2]=new RegExp(a6.match[a2].source+/(?![^\[]*\])(?![^\(]*\))/.source);a6.leftMatch[a2]=new RegExp(/(^(?:.|\r|\n)*?)/.source+a6.match[a2].source.replace(/\\(\d+)/g,function(bh,bg){return"\\"+(bg-0+1)}))}var a8=function(bh,bg){bh=Array.prototype.slice.call(bh,0);if(bg){bg.push.apply(bg,bh);return bg}return bh};try{Array.prototype.slice.call(ab.documentElement.childNodes,0)[0].nodeType}catch(bf){a8=function(bk,bj){var bh=bj||[];if(bc.call(bk)==="[object Array]"){Array.prototype.push.apply(bh,bk)}else{if(typeof bk.length==="number"){for(var bi=0,bg=bk.length;bi<bg;bi++){bh.push(bk[bi])}}else{for(var bi=0;bk[bi];bi++){bh.push(bk[bi])}}}return bh}}var bb;if(ab.documentElement.compareDocumentPosition){bb=function(bh,bg){if(!bh.compareDocumentPosition||!bg.compareDocumentPosition){if(bh==bg){a4=true}return bh.compareDocumentPosition?-1:1}var bi=bh.compareDocumentPosition(bg)&4?-1:bh===bg?0:1;if(bi===0){a4=true}return bi}}else{if("sourceIndex" in ab.documentElement){bb=function(bh,bg){if(!bh.sourceIndex||!bg.sourceIndex){if(bh==bg){a4=true}return bh.sourceIndex?-1:1}var bi=bh.sourceIndex-bg.sourceIndex;if(bi===0){a4=true}return bi}}else{if(ab.createRange){bb=function(bj,bh){if(!bj.ownerDocument||!bh.ownerDocument){if(bj==bh){a4=true}return bj.ownerDocument?-1:1}var bi=bj.ownerDocument.createRange(),bg=bh.ownerDocument.createRange();bi.setStart(bj,0);bi.setEnd(bj,0);bg.setStart(bh,0);bg.setEnd(bh,0);var bk=bi.compareBoundaryPoints(Range.START_TO_END,bg);if(bk===0){a4=true}return bk}}}}function aZ(bg){var bh="",bj;for(var bi=0;bg[bi];bi++){bj=bg[bi];if(bj.nodeType===3||bj.nodeType===4){bh+=bj.nodeValue}else{if(bj.nodeType!==8){bh+=aZ(bj.childNodes)}}}return bh}(function(){var bh=ab.createElement("div"),bi="script"+(new Date).getTime();bh.innerHTML="<a name='"+bi+"'/>";var bg=ab.documentElement;bg.insertBefore(bh,bg.firstChild);if(ab.getElementById(bi)){a6.find.ID=function(bk,bl,bm){if(typeof bl.getElementById!=="undefined"&&!bm){var bj=bl.getElementById(bk[1]);return bj?bj.id===bk[1]||typeof bj.getAttributeNode!=="undefined"&&bj.getAttributeNode("id").nodeValue===bk[1]?[bj]:C:[]}};a6.filter.ID=function(bl,bj){var bk=typeof bl.getAttributeNode!=="undefined"&&bl.getAttributeNode("id");return bl.nodeType===1&&bk&&bk.nodeValue===bj}}bg.removeChild(bh);bg=bh=null})();(function(){var bg=ab.createElement("div");bg.appendChild(ab.createComment(""));if(bg.getElementsByTagName("*").length>0){a6.find.TAG=function(bh,bl){var bk=bl.getElementsByTagName(bh[1]);if(bh[1]==="*"){var bj=[];for(var bi=0;bk[bi];bi++){if(bk[bi].nodeType===1){bj.push(bk[bi])}}bk=bj}return bk}}bg.innerHTML="<a href='#'></a>";if(bg.firstChild&&typeof bg.firstChild.getAttribute!=="undefined"&&bg.firstChild.getAttribute("href")!=="#"){a6.attrHandle.href=function(bh){return bh.getAttribute("href",2)}}bg=null})();if(ab.querySelectorAll){(function(){var bg=a0,bi=ab.createElement("div");bi.innerHTML="<p class='TEST'></p>";if(bi.querySelectorAll&&bi.querySelectorAll(".TEST").length===0){return}a0=function(bm,bl,bj,bk){bl=bl||ab;if(!bk&&bl.nodeType===9&&!a1(bl)){try{return a8(bl.querySelectorAll(bm),bj)}catch(bn){}}return bg(bm,bl,bj,bk)};for(var bh in bg){a0[bh]=bg[bh]}bi=null})()}(function(){var bg=ab.createElement("div");bg.innerHTML="<div class='test e'></div><div class='test'></div>";if(!bg.getElementsByClassName||bg.getElementsByClassName("e").length===0){return}bg.lastChild.className="e";if(bg.getElementsByClassName("e").length===1){return}a6.order.splice(1,0,"CLASS");a6.find.CLASS=function(bh,bi,bj){if(typeof bi.getElementsByClassName!=="undefined"&&!bj){return bi.getElementsByClassName(bh[1])}};bg=null})();function aY(bh,bm,bl,bp,bn,bo){for(var bj=0,bi=bp.length;bj<bi;bj++){var bg=bp[bj];if(bg){bg=bg[bh];var bk=false;while(bg){if(bg.sizcache===bl){bk=bp[bg.sizset];break}if(bg.nodeType===1&&!bo){bg.sizcache=bl;bg.sizset=bj}if(bg.nodeName.toLowerCase()===bm){bk=bg;break}bg=bg[bh]}bp[bj]=bk}}}function be(bh,bm,bl,bp,bn,bo){for(var bj=0,bi=bp.length;bj<bi;bj++){var bg=bp[bj];if(bg){bg=bg[bh];var bk=false;while(bg){if(bg.sizcache===bl){bk=bp[bg.sizset];break}if(bg.nodeType===1){if(!bo){bg.sizcache=bl;bg.sizset=bj}if(typeof bm!=="string"){if(bg===bm){bk=true;break}}else{if(a0.filter(bm,[bg]).length>0){bk=bg;break}}}bg=bg[bh]}bp[bj]=bk}}}var a7=ab.compareDocumentPosition?function(bh,bg){return !!(bh.compareDocumentPosition(bg)&16)}:function(bh,bg){return bh!==bg&&(bh.contains?bh.contains(bg):true)};var a1=function(bg){var bh=(bg?bg.ownerDocument||bg:0).documentElement;return bh?bh.nodeName!=="HTML":false};var bd=function(bg,bn){var bj=[],bk="",bl,bi=bn.nodeType?[bn]:bn;while((bl=a6.match.PSEUDO.exec(bg))){bk+=bl[0];bg=bg.replace(a6.match.PSEUDO,"")}bg=a6.relative[bg]?bg+"*":bg;for(var bm=0,bh=bi.length;bm<bh;bm++){a0(bg,bi[bm],bj)}return a0.filter(bk,bj)};a.find=a0;a.expr=a0.selectors;a.expr[":"]=a.expr.filters;a.unique=a0.uniqueSort;a.text=aZ;a.isXMLDoc=a1;a.contains=a7;return;aM.Sizzle=a0})();var N=/Until$/,Y=/^(?:parents|prevUntil|prevAll)/,aL=/,/,F=Array.prototype.slice;var ai=function(a1,a0,aY){if(a.isFunction(a0)){return a.grep(a1,function(a3,a2){return !!a0.call(a3,a2,a3)===aY})}else{if(a0.nodeType){return a.grep(a1,function(a3,a2){return(a3===a0)===aY})}else{if(typeof a0==="string"){var aZ=a.grep(a1,function(a2){return a2.nodeType===1});if(aW.test(a0)){return a.filter(a0,aZ,!aY)}else{a0=a.filter(a0,aZ)}}}}return a.grep(a1,function(a3,a2){return(a.inArray(a3,a0)>=0)===aY})};a.fn.extend({find:function(aY){var a0=this.pushStack("","find",aY),a3=0;for(var a1=0,aZ=this.length;a1<aZ;a1++){a3=a0.length;a.find(aY,this[a1],a0);if(a1>0){for(var a4=a3;a4<a0.length;a4++){for(var a2=0;a2<a3;a2++){if(a0[a2]===a0[a4]){a0.splice(a4--,1);break}}}}}return a0},has:function(aZ){var aY=a(aZ);return this.filter(function(){for(var a1=0,a0=aY.length;a1<a0;a1++){if(a.contains(this,aY[a1])){return true}}})},not:function(aY){return this.pushStack(ai(this,aY,false),"not",aY)},filter:function(aY){return this.pushStack(ai(this,aY,true),"filter",aY)},is:function(aY){return !!aY&&a.filter(aY,this).length>0},closest:function(a7,aY){if(a.isArray(a7)){var a4=[],a6=this[0],a3,a2={},a0;if(a6&&a7.length){for(var a1=0,aZ=a7.length;a1<aZ;a1++){a0=a7[a1];if(!a2[a0]){a2[a0]=a.expr.match.POS.test(a0)?a(a0,aY||this.context):a0}}while(a6&&a6.ownerDocument&&a6!==aY){for(a0 in a2){a3=a2[a0];if(a3.jquery?a3.index(a6)>-1:a(a6).is(a3)){a4.push({selector:a0,elem:a6});delete a2[a0]}}a6=a6.parentNode}}return a4}var a5=a.expr.match.POS.test(a7)?a(a7,aY||this.context):null;return this.map(function(a8,a9){while(a9&&a9.ownerDocument&&a9!==aY){if(a5?a5.index(a9)>-1:a(a9).is(a7)){return a9}a9=a9.parentNode}return null})},index:function(aY){if(!aY||typeof aY==="string"){return a.inArray(this[0],aY?a(aY):this.parent().children())}return a.inArray(aY.jquery?aY[0]:aY,this)},add:function(aY,aZ){var a1=typeof aY==="string"?a(aY,aZ||this.context):a.makeArray(aY),a0=a.merge(this.get(),a1);return this.pushStack(y(a1[0])||y(a0[0])?a0:a.unique(a0))},andSelf:function(){return this.add(this.prevObject)}});function y(aY){return !aY||!aY.parentNode||aY.parentNode.nodeType===11}a.each({parent:function(aZ){var aY=aZ.parentNode;return aY&&aY.nodeType!==11?aY:null},parents:function(aY){return a.dir(aY,"parentNode")},parentsUntil:function(aZ,aY,a0){return a.dir(aZ,"parentNode",a0)},next:function(aY){return a.nth(aY,2,"nextSibling")},prev:function(aY){return a.nth(aY,2,"previousSibling")},nextAll:function(aY){return a.dir(aY,"nextSibling")},prevAll:function(aY){return a.dir(aY,"previousSibling")},nextUntil:function(aZ,aY,a0){return a.dir(aZ,"nextSibling",a0)},prevUntil:function(aZ,aY,a0){return a.dir(aZ,"previousSibling",a0)},siblings:function(aY){return a.sibling(aY.parentNode.firstChild,aY)},children:function(aY){return a.sibling(aY.firstChild)},contents:function(aY){return a.nodeName(aY,"iframe")?aY.contentDocument||aY.contentWindow.document:a.makeArray(aY.childNodes)}},function(aY,aZ){a.fn[aY]=function(a2,a0){var a1=a.map(this,aZ,a2);if(!N.test(aY)){a0=a2}if(a0&&typeof a0==="string"){a1=a.filter(a0,a1)}a1=this.length>1?a.unique(a1):a1;if((this.length>1||aL.test(a0))&&Y.test(aY)){a1=a1.reverse()}return this.pushStack(a1,aY,F.call(arguments).join(","))}});a.extend({filter:function(a0,aY,aZ){if(aZ){a0=":not("+a0+")"}return a.find.matches(a0,aY)},dir:function(a0,aZ,a2){var aY=[],a1=a0[aZ];while(a1&&a1.nodeType!==9&&(a2===C||a1.nodeType!==1||!a(a1).is(a2))){if(a1.nodeType===1){aY.push(a1)}a1=a1[aZ]}return aY},nth:function(a2,aY,a0,a1){aY=aY||1;var aZ=0;for(;a2;a2=a2[a0]){if(a2.nodeType===1&&++aZ===aY){break}}return a2},sibling:function(a0,aZ){var aY=[];for(;a0;a0=a0.nextSibling){if(a0.nodeType===1&&a0!==aZ){aY.push(a0)}}return aY}});var T=/ jQuery\d+="(?:\d+|null)"/g,Z=/^\s+/,H=/(<([\w:]+)[^>]*?)\/>/g,al=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,c=/<([\w:]+)/,t=/<tbody/i,L=/<|&#?\w+;/,E=/<script|<object|<embed|<option|<style/i,l=/checked\s*(?:[^=]|=\s*.checked.)/i,p=function(aZ,a0,aY){return al.test(aY)?aZ:a0+"></"+aY+">"},ac={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,"",""]};ac.optgroup=ac.option;ac.tbody=ac.tfoot=ac.colgroup=ac.caption=ac.thead;ac.th=ac.td;if(!a.support.htmlSerialize){ac._default=[1,"div<div>","</div>"]}a.fn.extend({text:function(aY){if(a.isFunction(aY)){return this.each(function(a0){var aZ=a(this);aZ.text(aY.call(this,a0,aZ.text()))})}if(typeof aY!=="object"&&aY!==C){return this.empty().append((this[0]&&this[0].ownerDocument||ab).createTextNode(aY))}return a.text(this)},wrapAll:function(aY){if(a.isFunction(aY)){return this.each(function(a0){a(this).wrapAll(aY.call(this,a0))})}if(this[0]){var aZ=a(aY,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){aZ.insertBefore(this[0])}aZ.map(function(){var a0=this;while(a0.firstChild&&a0.firstChild.nodeType===1){a0=a0.firstChild}return a0}).append(this)}return this},wrapInner:function(aY){if(a.isFunction(aY)){return this.each(function(aZ){a(this).wrapInner(aY.call(this,aZ))})}return this.each(function(){var aZ=a(this),a0=aZ.contents();if(a0.length){a0.wrapAll(aY)}else{aZ.append(aY)}})},wrap:function(aY){return this.each(function(){a(this).wrapAll(aY)})},unwrap:function(){return this.parent().each(function(){if(!a.nodeName(this,"body")){a(this).replaceWith(this.childNodes)}}).end()},append:function(){return this.domManip(arguments,true,function(aY){if(this.nodeType===1){this.appendChild(aY)}})},prepend:function(){return this.domManip(arguments,true,function(aY){if(this.nodeType===1){this.insertBefore(aY,this.firstChild)}})},before:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(aZ){this.parentNode.insertBefore(aZ,this)})}else{if(arguments.length){var aY=a(arguments[0]);aY.push.apply(aY,this.toArray());return this.pushStack(aY,"before",arguments)}}},after:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(aZ){this.parentNode.insertBefore(aZ,this.nextSibling)})}else{if(arguments.length){var aY=this.pushStack(this,"after",arguments);aY.push.apply(aY,a(arguments[0]).toArray());return aY}}},remove:function(aY,a1){for(var aZ=0,a0;(a0=this[aZ])!=null;aZ++){if(!aY||a.filter(aY,[a0]).length){if(!a1&&a0.nodeType===1){a.cleanData(a0.getElementsByTagName("*"));a.cleanData([a0])}if(a0.parentNode){a0.parentNode.removeChild(a0)}}}return this},empty:function(){for(var aY=0,aZ;(aZ=this[aY])!=null;aY++){if(aZ.nodeType===1){a.cleanData(aZ.getElementsByTagName("*"))}while(aZ.firstChild){aZ.removeChild(aZ.firstChild)}}return this},clone:function(aZ){var aY=this.map(function(){if(!a.support.noCloneEvent&&!a.isXMLDoc(this)){var a1=this.outerHTML,a0=this.ownerDocument;if(!a1){var a2=a0.createElement("div");a2.appendChild(this.cloneNode(true));a1=a2.innerHTML}return a.clean([a1.replace(T,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(Z,"")],a0)[0]}else{return this.cloneNode(true)}});if(aZ===true){q(this,aY);q(this.find("*"),aY.find("*"))}return aY},html:function(a0){if(a0===C){return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(T,""):null}else{if(typeof a0==="string"&&!E.test(a0)&&(a.support.leadingWhitespace||!Z.test(a0))&&!ac[(c.exec(a0)||["",""])[1].toLowerCase()]){a0=a0.replace(H,p);try{for(var aZ=0,aY=this.length;aZ<aY;aZ++){if(this[aZ].nodeType===1){a.cleanData(this[aZ].getElementsByTagName("*"));this[aZ].innerHTML=a0}}}catch(a1){this.empty().append(a0)}}else{if(a.isFunction(a0)){this.each(function(a4){var a3=a(this),a2=a3.html();a3.empty().append(function(){return a0.call(this,a4,a2)})})}else{this.empty().append(a0)}}}return this},replaceWith:function(aY){if(this[0]&&this[0].parentNode){if(a.isFunction(aY)){return this.each(function(a1){var a0=a(this),aZ=a0.html();a0.replaceWith(aY.call(this,a1,aZ))})}if(typeof aY!=="string"){aY=a(aY).detach()}return this.each(function(){var a0=this.nextSibling,aZ=this.parentNode;a(this).remove();if(a0){a(a0).before(aY)}else{a(aZ).append(aY)}})}else{return this.pushStack(a(a.isFunction(aY)?aY():aY),"replaceWith",aY)}},detach:function(aY){return this.remove(aY,true)},domManip:function(a4,a9,a8){var a1,a2,a7=a4[0],aZ=[],a3,a6;if(!a.support.checkClone&&arguments.length===3&&typeof a7==="string"&&l.test(a7)){return this.each(function(){a(this).domManip(a4,a9,a8,true)})}if(a.isFunction(a7)){return this.each(function(bb){var ba=a(this);a4[0]=a7.call(this,bb,a9?ba.html():C);ba.domManip(a4,a9,a8)})}if(this[0]){a6=a7&&a7.parentNode;if(a.support.parentNode&&a6&&a6.nodeType===11&&a6.childNodes.length===this.length){a1={fragment:a6}}else{a1=J(a4,this,aZ)}a3=a1.fragment;if(a3.childNodes.length===1){a2=a3=a3.firstChild}else{a2=a3.firstChild}if(a2){a9=a9&&a.nodeName(a2,"tr");for(var a0=0,aY=this.length;a0<aY;a0++){a8.call(a9?a5(this[a0],a2):this[a0],a0>0||a1.cacheable||this.length>1?a3.cloneNode(true):a3)}}if(aZ.length){a.each(aZ,aV)}}return this;function a5(ba,bb){return a.nodeName(ba,"table")?(ba.getElementsByTagName("tbody")[0]||ba.appendChild(ba.ownerDocument.createElement("tbody"))):ba}}});function q(a0,aY){var aZ=0;aY.each(function(){if(this.nodeName!==(a0[aZ]&&a0[aZ].nodeName)){return}var a5=a.data(a0[aZ++]),a4=a.data(this,a5),a1=a5&&a5.events;if(a1){delete a4.handle;a4.events={};for(var a3 in a1){for(var a2 in a1[a3]){a.event.add(this,a3,a1[a3][a2],a1[a3][a2].data)}}}})}function J(a3,a1,aZ){var a2,aY,a0,a4=(a1&&a1[0]?a1[0].ownerDocument||a1[0]:ab);if(a3.length===1&&typeof a3[0]==="string"&&a3[0].length<512&&a4===ab&&!E.test(a3[0])&&(a.support.checkClone||!l.test(a3[0]))){aY=true;a0=a.fragments[a3[0]];if(a0){if(a0!==1){a2=a0}}}if(!a2){a2=a4.createDocumentFragment();a.clean(a3,a4,a2,aZ)}if(aY){a.fragments[a3[0]]=a0?a2:1}return{fragment:a2,cacheable:aY}}a.fragments={};a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(aY,aZ){a.fn[aY]=function(a0){var a3=[],a6=a(a0),a5=this.length===1&&this[0].parentNode;if(a5&&a5.nodeType===11&&a5.childNodes.length===1&&a6.length===1){a6[aZ](this[0]);return this}else{for(var a4=0,a1=a6.length;a4<a1;a4++){var a2=(a4>0?this.clone(true):this).get();a.fn[aZ].apply(a(a6[a4]),a2);a3=a3.concat(a2)}return this.pushStack(a3,aY,a6.selector)}}});a.extend({clean:function(a0,a2,a9,a4){a2=a2||ab;if(typeof a2.createElement==="undefined"){a2=a2.ownerDocument||a2[0]&&a2[0].ownerDocument||ab}var ba=[];for(var a8=0,a3;(a3=a0[a8])!=null;a8++){if(typeof a3==="number"){a3+=""}if(!a3){continue}if(typeof a3==="string"&&!L.test(a3)){a3=a2.createTextNode(a3)}else{if(typeof a3==="string"){a3=a3.replace(H,p);var bb=(c.exec(a3)||["",""])[1].toLowerCase(),a1=ac[bb]||ac._default,a7=a1[0],aZ=a2.createElement("div");aZ.innerHTML=a1[1]+a3+a1[2];while(a7--){aZ=aZ.lastChild}if(!a.support.tbody){var aY=t.test(a3),a6=bb==="table"&&!aY?aZ.firstChild&&aZ.firstChild.childNodes:a1[1]==="<table>"&&!aY?aZ.childNodes:[];for(var a5=a6.length-1;a5>=0;--a5){if(a.nodeName(a6[a5],"tbody")&&!a6[a5].childNodes.length){a6[a5].parentNode.removeChild(a6[a5])}}}if(!a.support.leadingWhitespace&&Z.test(a3)){aZ.insertBefore(a2.createTextNode(Z.exec(a3)[0]),aZ.firstChild)}a3=aZ.childNodes}}if(a3.nodeType){ba.push(a3)}else{ba=a.merge(ba,a3)}}if(a9){for(var a8=0;ba[a8];a8++){if(a4&&a.nodeName(ba[a8],"script")&&(!ba[a8].type||ba[a8].type.toLowerCase()==="text/javascript")){a4.push(ba[a8].parentNode?ba[a8].parentNode.removeChild(ba[a8]):ba[a8])}else{if(ba[a8].nodeType===1){ba.splice.apply(ba,[a8+1,0].concat(a.makeArray(ba[a8].getElementsByTagName("script"))))}a9.appendChild(ba[a8])}}}return ba},cleanData:function(aZ){var a2,a0,aY=a.cache,a5=a.event.special,a4=a.support.deleteExpando;for(var a3=0,a1;(a1=aZ[a3])!=null;a3++){a0=a1[a.expando];if(a0){a2=aY[a0];if(a2.events){for(var a6 in a2.events){if(a5[a6]){a.event.remove(a1,a6)}else{ag(a1,a6,a2.handle)}}}if(a4){delete a1[a.expando]}else{if(a1.removeAttribute){a1.removeAttribute(a.expando)}}delete aY[a0]}}}});var ar=/z-?index|font-?weight|opacity|zoom|line-?height/i,U=/alpha\([^)]*\)/,aa=/opacity=([^)]*)/,ah=/float/i,az=/-([a-z])/ig,v=/([A-Z])/g,aO=/^-?\d+(?:px)?$/i,aU=/^-?\d/,aK={position:"absolute",visibility:"hidden",display:"block"},W=["Left","Right"],aE=["Top","Bottom"],ak=ab.defaultView&&ab.defaultView.getComputedStyle,aN=a.support.cssFloat?"cssFloat":"styleFloat",k=function(aY,aZ){return aZ.toUpperCase()};a.fn.css=function(aY,aZ){return an(this,aY,aZ,true,function(a1,a0,a2){if(a2===C){return a.curCSS(a1,a0)}if(typeof a2==="number"&&!ar.test(a0)){a2+="px"}a.style(a1,a0,a2)})};a.extend({style:function(a2,aZ,a3){if(!a2||a2.nodeType===3||a2.nodeType===8){return C}if((aZ==="width"||aZ==="height")&&parseFloat(a3)<0){a3=C}var a1=a2.style||a2,a4=a3!==C;if(!a.support.opacity&&aZ==="opacity"){if(a4){a1.zoom=1;var aY=parseInt(a3,10)+""==="NaN"?"":"alpha(opacity="+a3*100+")";var a0=a1.filter||a.curCSS(a2,"filter")||"";a1.filter=U.test(a0)?a0.replace(U,aY):aY}return a1.filter&&a1.filter.indexOf("opacity=")>=0?(parseFloat(aa.exec(a1.filter)[1])/100)+"":""}if(ah.test(aZ)){aZ=aN}aZ=aZ.replace(az,k);if(a4){a1[aZ]=a3}return a1[aZ]},css:function(a1,aZ,a3,aY){if(aZ==="width"||aZ==="height"){var a5,a0=aK,a4=aZ==="width"?W:aE;function a2(){a5=aZ==="width"?a1.offsetWidth:a1.offsetHeight;if(aY==="border"){return}a.each(a4,function(){if(!aY){a5-=parseFloat(a.curCSS(a1,"padding"+this,true))||0}if(aY==="margin"){a5+=parseFloat(a.curCSS(a1,"margin"+this,true))||0}else{a5-=parseFloat(a.curCSS(a1,"border"+this+"Width",true))||0}})}if(a1.offsetWidth!==0){a2()}else{a.swap(a1,a0,a2)}return Math.max(0,Math.round(a5))}return a.curCSS(a1,aZ,a3)},curCSS:function(a4,aZ,a0){var a7,aY=a4.style,a1;if(!a.support.opacity&&aZ==="opacity"&&a4.currentStyle){a7=aa.test(a4.currentStyle.filter||"")?(parseFloat(RegExp.$1)/100)+"":"";return a7===""?"1":a7}if(ah.test(aZ)){aZ=aN}if(!a0&&aY&&aY[aZ]){a7=aY[aZ]}else{if(ak){if(ah.test(aZ)){aZ="float"}aZ=aZ.replace(v,"-$1").toLowerCase();var a6=a4.ownerDocument.defaultView;if(!a6){return null}var a8=a6.getComputedStyle(a4,null);if(a8){a7=a8.getPropertyValue(aZ)}if(aZ==="opacity"&&a7===""){a7="1"}}else{if(a4.currentStyle){var a3=aZ.replace(az,k);a7=a4.currentStyle[aZ]||a4.currentStyle[a3];if(!aO.test(a7)&&aU.test(a7)){var a2=aY.left,a5=a4.runtimeStyle.left;a4.runtimeStyle.left=a4.currentStyle.left;aY.left=a3==="fontSize"?"1em":(a7||0);a7=aY.pixelLeft+"px";aY.left=a2;a4.runtimeStyle.left=a5}}}}return a7},swap:function(a1,a0,a2){var aY={};for(var aZ in a0){aY[aZ]=a1.style[aZ];a1.style[aZ]=a0[aZ]}a2.call(a1);for(var aZ in a0){a1.style[aZ]=aY[aZ]}}});if(a.expr&&a.expr.filters){a.expr.filters.hidden=function(a1){var aZ=a1.offsetWidth,aY=a1.offsetHeight,a0=a1.nodeName.toLowerCase()==="tr";return aZ===0&&aY===0&&!a0?true:aZ>0&&aY>0&&!a0?false:a.curCSS(a1,"display")==="none"};a.expr.filters.visible=function(aY){return !a.expr.filters.hidden(aY)}}var af=aP(),aJ=/<script(.|\s)*?\/script>/gi,o=/select|textarea/i,aB=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,r=/=\?(&|$)/,D=/\?/,aX=/(\?|&)_=.*?(&|$)/,B=/^(\w+:)?\/\/([^\/?#]+)/,h=/%20/g,w=a.fn.load;a.fn.extend({load:function(a0,a3,a4){if(typeof a0!=="string"){return w.call(this,a0)}else{if(!this.length){return this}}var a2=a0.indexOf(" ");if(a2>=0){var aY=a0.slice(a2,a0.length);a0=a0.slice(0,a2)}var a1="GET";if(a3){if(a.isFunction(a3)){a4=a3;a3=null}else{if(typeof a3==="object"){a3=a.param(a3,a.ajaxSettings.traditional);a1="POST"}}}var aZ=this;a.ajax({url:a0,type:a1,dataType:"html",data:a3,complete:function(a6,a5){if(a5==="success"||a5==="notmodified"){aZ.html(aY?a("<div />").append(a6.responseText.replace(aJ,"")).find(aY):a6.responseText)}if(a4){aZ.each(a4,[a6.responseText,a5,a6])}}});return this},serialize:function(){return a.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?a.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||o.test(this.nodeName)||aB.test(this.type))}).map(function(aY,aZ){var a0=a(this).val();return a0==null?null:a.isArray(a0)?a.map(a0,function(a2,a1){return{name:aZ.name,value:a2}}):{name:aZ.name,value:a0}}).get()}});a.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(aY,aZ){a.fn[aZ]=function(a0){return this.bind(aZ,a0)}});a.extend({get:function(aY,a0,a1,aZ){if(a.isFunction(a0)){aZ=aZ||a1;a1=a0;a0=null}return a.ajax({type:"GET",url:aY,data:a0,success:a1,dataType:aZ})},getScript:function(aY,aZ){return a.get(aY,null,aZ,"script")},getJSON:function(aY,aZ,a0){return a.get(aY,aZ,a0,"json")},post:function(aY,a0,a1,aZ){if(a.isFunction(a0)){aZ=aZ||a1;a1=a0;a0={}}return a.ajax({type:"POST",url:aY,data:a0,success:a1,dataType:aZ})},ajaxSetup:function(aY){a.extend(a.ajaxSettings,aY)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:aM.XMLHttpRequest&&(aM.location.protocol!=="file:"||!aM.ActiveXObject)?function(){return new aM.XMLHttpRequest()}:function(){try{return new aM.ActiveXObject("Microsoft.XMLHTTP")}catch(aY){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(bd){var a8=a.extend(true,{},a.ajaxSettings,bd);var bi,bc,bh,bj=bd&&bd.context||a8,a0=a8.type.toUpperCase();if(a8.data&&a8.processData&&typeof a8.data!=="string"){a8.data=a.param(a8.data,a8.traditional)}if(a8.dataType==="jsonp"){if(a0==="GET"){if(!r.test(a8.url)){a8.url+=(D.test(a8.url)?"&":"?")+(a8.jsonp||"callback")+"=?"}}else{if(!a8.data||!r.test(a8.data)){a8.data=(a8.data?a8.data+"&":"")+(a8.jsonp||"callback")+"=?"}}a8.dataType="json"}if(a8.dataType==="json"&&(a8.data&&r.test(a8.data)||r.test(a8.url))){bi=a8.jsonpCallback||("jsonp"+af++);if(a8.data){a8.data=(a8.data+"").replace(r,"="+bi+"$1")}a8.url=a8.url.replace(r,"="+bi+"$1");a8.dataType="script";aM[bi]=aM[bi]||function(bk){bh=bk;a3();a6();aM[bi]=C;try{delete aM[bi]}catch(bl){}if(a1){a1.removeChild(bf)}}}if(a8.dataType==="script"&&a8.cache===null){a8.cache=false}if(a8.cache===false&&a0==="GET"){var aY=aP();var bg=a8.url.replace(aX,"$1_="+aY+"$2");a8.url=bg+((bg===a8.url)?(D.test(a8.url)?"&":"?")+"_="+aY:"")}if(a8.data&&a0==="GET"){a8.url+=(D.test(a8.url)?"&":"?")+a8.data}if(a8.global&&!a.active++){a.event.trigger("ajaxStart")}var bb=B.exec(a8.url),a2=bb&&(bb[1]&&bb[1]!==location.protocol||bb[2]!==location.host);if(a8.dataType==="script"&&a0==="GET"&&a2){var a1=ab.getElementsByTagName("head")[0]||ab.documentElement;var bf=ab.createElement("script");bf.src=a8.url;if(a8.scriptCharset){bf.charset=a8.scriptCharset}if(!bi){var ba=false;bf.onload=bf.onreadystatechange=function(){if(!ba&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){ba=true;a3();a6();bf.onload=bf.onreadystatechange=null;if(a1&&bf.parentNode){a1.removeChild(bf)}}}}a1.insertBefore(bf,a1.firstChild);return C}var a5=false;var a4=a8.xhr();if(!a4){return}if(a8.username){a4.open(a0,a8.url,a8.async,a8.username,a8.password)}else{a4.open(a0,a8.url,a8.async)}try{if(a8.data||bd&&bd.contentType){a4.setRequestHeader("Content-Type",a8.contentType)}if(a8.ifModified){if(a.lastModified[a8.url]){a4.setRequestHeader("If-Modified-Since",a.lastModified[a8.url])}if(a.etag[a8.url]){a4.setRequestHeader("If-None-Match",a.etag[a8.url])}}if(!a2){a4.setRequestHeader("X-Requested-With","XMLHttpRequest")}a4.setRequestHeader("Accept",a8.dataType&&a8.accepts[a8.dataType]?a8.accepts[a8.dataType]+", */*":a8.accepts._default)}catch(be){}if(a8.beforeSend&&a8.beforeSend.call(bj,a4,a8)===false){if(a8.global&&!--a.active){a.event.trigger("ajaxStop")}a4.abort();return false}if(a8.global){a9("ajaxSend",[a4,a8])}var a7=a4.onreadystatechange=function(bk){if(!a4||a4.readyState===0||bk==="abort"){if(!a5){a6()}a5=true;if(a4){a4.onreadystatechange=a.noop}}else{if(!a5&&a4&&(a4.readyState===4||bk==="timeout")){a5=true;a4.onreadystatechange=a.noop;bc=bk==="timeout"?"timeout":!a.httpSuccess(a4)?"error":a8.ifModified&&a.httpNotModified(a4,a8.url)?"notmodified":"success";var bm;if(bc==="success"){try{bh=a.httpData(a4,a8.dataType,a8)}catch(bl){bc="parsererror";bm=bl}}if(bc==="success"||bc==="notmodified"){if(!bi){a3()}}else{a.handleError(a8,a4,bc,bm)}a6();if(bk==="timeout"){a4.abort()}if(a8.async){a4=null}}}};try{var aZ=a4.abort;a4.abort=function(){if(a4){aZ.call(a4)}a7("abort")}}catch(be){}if(a8.async&&a8.timeout>0){setTimeout(function(){if(a4&&!a5){a7("timeout")}},a8.timeout)}try{a4.send(a0==="POST"||a0==="PUT"||a0==="DELETE"?a8.data:null)}catch(be){a.handleError(a8,a4,null,be);a6()}if(!a8.async){a7()}function a3(){if(a8.success){a8.success.call(bj,bh,bc,a4)}if(a8.global){a9("ajaxSuccess",[a4,a8])}}function a6(){if(a8.complete){a8.complete.call(bj,a4,bc)}if(a8.global){a9("ajaxComplete",[a4,a8])}if(a8.global&&!--a.active){a.event.trigger("ajaxStop")}}function a9(bl,bk){(a8.context?a(a8.context):a.event).trigger(bl,bk)}return a4},handleError:function(aZ,a1,aY,a0){if(aZ.error){aZ.error.call(aZ.context||aZ,a1,aY,a0)}if(aZ.global){(aZ.context?a(aZ.context):a.event).trigger("ajaxError",[a1,aZ,a0])}},active:0,httpSuccess:function(aZ){try{return !aZ.status&&location.protocol==="file:"||(aZ.status>=200&&aZ.status<300)||aZ.status===304||aZ.status===1223||aZ.status===0}catch(aY){}return false},httpNotModified:function(a1,aY){var a0=a1.getResponseHeader("Last-Modified"),aZ=a1.getResponseHeader("Etag");if(a0){a.lastModified[aY]=a0}if(aZ){a.etag[aY]=aZ}return a1.status===304||a1.status===0},httpData:function(a3,a1,a0){var aZ=a3.getResponseHeader("content-type")||"",aY=a1==="xml"||!a1&&aZ.indexOf("xml")>=0,a2=aY?a3.responseXML:a3.responseText;if(aY&&a2.documentElement.nodeName==="parsererror"){a.error("parsererror")}if(a0&&a0.dataFilter){a2=a0.dataFilter(a2,a1)}if(typeof a2==="string"){if(a1==="json"||!a1&&aZ.indexOf("json")>=0){a2=a.parseJSON(a2)}else{if(a1==="script"||!a1&&aZ.indexOf("javascript")>=0){a.globalEval(a2)}}}return a2},param:function(aY,a1){var aZ=[];if(a1===C){a1=a.ajaxSettings.traditional}if(a.isArray(aY)||aY.jquery){a.each(aY,function(){a3(this.name,this.value)})}else{for(var a2 in aY){a0(a2,aY[a2])}}return aZ.join("&").replace(h,"+");function a0(a4,a5){if(a.isArray(a5)){a.each(a5,function(a7,a6){if(a1||/\[\]$/.test(a4)){a3(a4,a6)}else{a0(a4+"["+(typeof a6==="object"||a.isArray(a6)?a7:"")+"]",a6)}})}else{if(!a1&&a5!=null&&typeof a5==="object"){a.each(a5,function(a7,a6){a0(a4+"["+a7+"]",a6)})}else{a3(a4,a5)}}}function a3(a4,a5){a5=a.isFunction(a5)?a5():a5;aZ[aZ.length]=encodeURIComponent(a4)+"="+encodeURIComponent(a5)}}});var G={},ae=/toggle|show|hide/,au=/^([+-]=)?([\d+-.]+)(.*)$/,aF,aj=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];a.fn.extend({show:function(aZ,a7){if(aZ||aZ===0){return this.animate(aD("show",3),aZ,a7)}else{for(var a4=0,a1=this.length;a4<a1;a4++){var aY=a.data(this[a4],"olddisplay");this[a4].style.display=aY||"";if(a.css(this[a4],"display")==="none"){var a6=this[a4].nodeName,a5;if(G[a6]){a5=G[a6]}else{var a0=a("<"+a6+" />").appendTo("body");a5=a0.css("display");if(a5==="none"){a5="block"}a0.remove();G[a6]=a5}a.data(this[a4],"olddisplay",a5)}}for(var a3=0,a2=this.length;a3<a2;a3++){this[a3].style.display=a.data(this[a3],"olddisplay")||""}return this}},hide:function(a3,a4){if(a3||a3===0){return this.animate(aD("hide",3),a3,a4)}else{for(var a2=0,aZ=this.length;a2<aZ;a2++){var aY=a.data(this[a2],"olddisplay");if(!aY&&aY!=="none"){a.data(this[a2],"olddisplay",a.css(this[a2],"display"))}}for(var a1=0,a0=this.length;a1<a0;a1++){this[a1].style.display="none"}return this}},_toggle:a.fn.toggle,toggle:function(a0,aZ){var aY=typeof a0==="boolean";if(a.isFunction(a0)&&a.isFunction(aZ)){this._toggle.apply(this,arguments)}else{if(a0==null||aY){this.each(function(){var a1=aY?a0:a(this).is(":hidden");a(this)[a1?"show":"hide"]()})}else{this.animate(aD("toggle",3),a0,aZ)}}return this},fadeTo:function(aY,a0,aZ){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:a0},aY,aZ)},animate:function(a2,aZ,a1,a0){var aY=a.speed(aZ,a1,a0);if(a.isEmptyObject(a2)){return this.each(aY.complete)}return this[aY.queue===false?"each":"queue"](function(){var a5=a.extend({},aY),a7,a6=this.nodeType===1&&a(this).is(":hidden"),a3=this;for(a7 in a2){var a4=a7.replace(az,k);if(a7!==a4){a2[a4]=a2[a7];delete a2[a7];a7=a4}if(a2[a7]==="hide"&&a6||a2[a7]==="show"&&!a6){return a5.complete.call(this)}if((a7==="height"||a7==="width")&&this.style){a5.display=a.css(this,"display");a5.overflow=this.style.overflow}if(a.isArray(a2[a7])){(a5.specialEasing=a5.specialEasing||{})[a7]=a2[a7][1];a2[a7]=a2[a7][0]}}if(a5.overflow!=null){this.style.overflow="hidden"}a5.curAnim=a.extend({},a2);a.each(a2,function(a9,bd){var bc=new a.fx(a3,a5,a9);if(ae.test(bd)){bc[bd==="toggle"?a6?"show":"hide":bd](a2)}else{var bb=au.exec(bd),be=bc.cur(true)||0;if(bb){var a8=parseFloat(bb[2]),ba=bb[3]||"px";if(ba!=="px"){a3.style[a9]=(a8||1)+ba;be=((a8||1)/bc.cur(true))*be;a3.style[a9]=be+ba}if(bb[1]){a8=((bb[1]==="-="?-1:1)*a8)+be}bc.custom(be,a8,ba)}else{bc.custom(be,bd,"")}}});return true})},stop:function(aZ,aY){var a0=a.timers;if(aZ){this.queue([])}this.each(function(){for(var a1=a0.length-1;a1>=0;a1--){if(a0[a1].elem===this){if(aY){a0[a1](true)}a0.splice(a1,1)}}});if(!aY){this.dequeue()}return this}});a.each({slideDown:aD("show",1),slideUp:aD("hide",1),slideToggle:aD("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(aY,aZ){a.fn[aY]=function(a0,a1){return this.animate(aZ,a0,a1)}});a.extend({speed:function(a0,a1,aZ){var aY=a0&&typeof a0==="object"?a0:{complete:aZ||!aZ&&a1||a.isFunction(a0)&&a0,duration:a0,easing:aZ&&a1||a1&&!a.isFunction(a1)&&a1};aY.duration=a.fx.off?0:typeof aY.duration==="number"?aY.duration:a.fx.speeds[aY.duration]||a.fx.speeds._default;aY.old=aY.complete;aY.complete=function(){if(aY.queue!==false){a(this).dequeue()}if(a.isFunction(aY.old)){aY.old.call(this)}};return aY},easing:{linear:function(a0,a1,aY,aZ){return aY+aZ*a0},swing:function(a0,a1,aY,aZ){return((-Math.cos(a0*Math.PI)/2)+0.5)*aZ+aY}},timers:[],fx:function(aZ,aY,a0){this.options=aY;this.elem=aZ;this.prop=a0;if(!aY.orig){aY.orig={}}}});a.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(a.fx.step[this.prop]||a.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(aZ){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var aY=parseFloat(a.css(this.elem,this.prop,aZ));return aY&&aY>-10000?aY:parseFloat(a.curCSS(this.elem,this.prop))||0},custom:function(a2,a1,a0){this.startTime=aP();this.start=a2;this.end=a1;this.unit=a0||this.unit||"px";this.now=this.start;this.pos=this.state=0;var aY=this;function aZ(a3){return aY.step(a3)}aZ.elem=this.elem;if(aZ()&&a.timers.push(aZ)&&!aF){aF=setInterval(a.fx.tick,13)}},show:function(){this.options.orig[this.prop]=a.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());a(this.elem).show()},hide:function(){this.options.orig[this.prop]=a.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a1){var a6=aP(),a2=true;if(a1||a6>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var a3 in this.options.curAnim){if(this.options.curAnim[a3]!==true){a2=false}}if(a2){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;var a0=a.data(this.elem,"olddisplay");this.elem.style.display=a0?a0:this.options.display;if(a.css(this.elem,"display")==="none"){this.elem.style.display="block"}}if(this.options.hide){a(this.elem).hide()}if(this.options.hide||this.options.show){for(var aY in this.options.curAnim){a.style(this.elem,aY,this.options.orig[aY])}}this.options.complete.call(this.elem)}return false}else{var aZ=a6-this.startTime;this.state=aZ/this.options.duration;var a4=this.options.specialEasing&&this.options.specialEasing[this.prop];var a5=this.options.easing||(a.easing.swing?"swing":"linear");this.pos=a.easing[a4||a5](this.state,aZ,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};a.extend(a.fx,{tick:function(){var aZ=a.timers;for(var aY=0;aY<aZ.length;aY++){if(!aZ[aY]()){aZ.splice(aY--,1)}}if(!aZ.length){a.fx.stop()}},stop:function(){clearInterval(aF);aF=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(aY){a.style(aY.elem,"opacity",aY.now)},_default:function(aY){if(aY.elem.style&&aY.elem.style[aY.prop]!=null){aY.elem.style[aY.prop]=(aY.prop==="width"||aY.prop==="height"?Math.max(0,aY.now):aY.now)+aY.unit}else{aY.elem[aY.prop]=aY.now}}}});if(a.expr&&a.expr.filters){a.expr.filters.animated=function(aY){return a.grep(a.timers,function(aZ){return aY===aZ.elem}).length}}function aD(aZ,aY){var a0={};a.each(aj.concat.apply([],aj.slice(0,aY)),function(){a0[this]=aZ});return a0}if("getBoundingClientRect" in ab.documentElement){a.fn.offset=function(a7){var a0=this[0];if(a7){return this.each(function(a8){a.offset.setOffset(this,a7,a8)})}if(!a0||!a0.ownerDocument){return null}if(a0===a0.ownerDocument.body){return a.offset.bodyOffset(a0)}var a2=a0.getBoundingClientRect(),a6=a0.ownerDocument,a3=a6.body,aY=a6.documentElement,a1=aY.clientTop||a3.clientTop||0,a4=aY.clientLeft||a3.clientLeft||0,a5=a2.top+(self.pageYOffset||a.support.boxModel&&aY.scrollTop||a3.scrollTop)-a1,aZ=a2.left+(self.pageXOffset||a.support.boxModel&&aY.scrollLeft||a3.scrollLeft)-a4;return{top:a5,left:aZ}}}else{a.fn.offset=function(a9){var a3=this[0];if(a9){return this.each(function(ba){a.offset.setOffset(this,a9,ba)})}if(!a3||!a3.ownerDocument){return null}if(a3===a3.ownerDocument.body){return a.offset.bodyOffset(a3)}a.offset.initialize();var a0=a3.offsetParent,aZ=a3,a8=a3.ownerDocument,a6,a1=a8.documentElement,a4=a8.body,a5=a8.defaultView,aY=a5?a5.getComputedStyle(a3,null):a3.currentStyle,a7=a3.offsetTop,a2=a3.offsetLeft;while((a3=a3.parentNode)&&a3!==a4&&a3!==a1){if(a.offset.supportsFixedPosition&&aY.position==="fixed"){break}a6=a5?a5.getComputedStyle(a3,null):a3.currentStyle;a7-=a3.scrollTop;a2-=a3.scrollLeft;if(a3===a0){a7+=a3.offsetTop;a2+=a3.offsetLeft;if(a.offset.doesNotAddBorder&&!(a.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(a3.nodeName))){a7+=parseFloat(a6.borderTopWidth)||0;a2+=parseFloat(a6.borderLeftWidth)||0}aZ=a0,a0=a3.offsetParent}if(a.offset.subtractsBorderForOverflowNotVisible&&a6.overflow!=="visible"){a7+=parseFloat(a6.borderTopWidth)||0;a2+=parseFloat(a6.borderLeftWidth)||0}aY=a6}if(aY.position==="relative"||aY.position==="static"){a7+=a4.offsetTop;a2+=a4.offsetLeft}if(a.offset.supportsFixedPosition&&aY.position==="fixed"){a7+=Math.max(a1.scrollTop,a4.scrollTop);a2+=Math.max(a1.scrollLeft,a4.scrollLeft)}return{top:a7,left:a2}}}a.offset={initialize:function(){var aY=ab.body,aZ=ab.createElement("div"),a2,a4,a3,a5,a0=parseFloat(a.curCSS(aY,"marginTop",true))||0,a1="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.extend(aZ.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});aZ.innerHTML=a1;aY.insertBefore(aZ,aY.firstChild);a2=aZ.firstChild;a4=a2.firstChild;a5=a2.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(a4.offsetTop!==5);this.doesAddBorderForTableAndCells=(a5.offsetTop===5);a4.style.position="fixed",a4.style.top="20px";this.supportsFixedPosition=(a4.offsetTop===20||a4.offsetTop===15);a4.style.position=a4.style.top="";a2.style.overflow="hidden",a2.style.position="relative";this.subtractsBorderForOverflowNotVisible=(a4.offsetTop===-5);this.doesNotIncludeMarginInBodyOffset=(aY.offsetTop!==a0);aY.removeChild(aZ);aY=aZ=a2=a4=a3=a5=null;a.offset.initialize=a.noop},bodyOffset:function(aY){var a0=aY.offsetTop,aZ=aY.offsetLeft;a.offset.initialize();if(a.offset.doesNotIncludeMarginInBodyOffset){a0+=parseFloat(a.curCSS(aY,"marginTop",true))||0;aZ+=parseFloat(a.curCSS(aY,"marginLeft",true))||0}return{top:a0,left:aZ}},setOffset:function(a3,aZ,a0){if(/static/.test(a.curCSS(a3,"position"))){a3.style.position="relative"}var a2=a(a3),a5=a2.offset(),aY=parseInt(a.curCSS(a3,"top",true),10)||0,a4=parseInt(a.curCSS(a3,"left",true),10)||0;if(a.isFunction(aZ)){aZ=aZ.call(a3,a0,a5)}var a1={top:(aZ.top-a5.top)+aY,left:(aZ.left-a5.left)+a4};if("using" in aZ){aZ.using.call(a3,a1)}else{a2.css(a1)}}};a.fn.extend({position:function(){if(!this[0]){return null}var a0=this[0],aZ=this.offsetParent(),a1=this.offset(),aY=/^body|html$/i.test(aZ[0].nodeName)?{top:0,left:0}:aZ.offset();a1.top-=parseFloat(a.curCSS(a0,"marginTop",true))||0;a1.left-=parseFloat(a.curCSS(a0,"marginLeft",true))||0;aY.top+=parseFloat(a.curCSS(aZ[0],"borderTopWidth",true))||0;aY.left+=parseFloat(a.curCSS(aZ[0],"borderLeftWidth",true))||0;return{top:a1.top-aY.top,left:a1.left-aY.left}},offsetParent:function(){return this.map(function(){var aY=this.offsetParent||ab.body;while(aY&&(!/^body|html$/i.test(aY.nodeName)&&a.css(aY,"position")==="static")){aY=aY.offsetParent}return aY})}});a.each(["Left","Top"],function(aZ,aY){var a0="scroll"+aY;a.fn[a0]=function(a3){var a1=this[0],a2;if(!a1){return null}if(a3!==C){return this.each(function(){a2=am(this);if(a2){a2.scrollTo(!aZ?a3:a(a2).scrollLeft(),aZ?a3:a(a2).scrollTop())}else{this[a0]=a3}})}else{a2=am(a1);return a2?("pageXOffset" in a2)?a2[aZ?"pageYOffset":"pageXOffset"]:a.support.boxModel&&a2.document.documentElement[a0]||a2.document.body[a0]:a1[a0]}}});function am(aY){return("scrollTo" in aY&&aY.document)?aY:aY.nodeType===9?aY.defaultView||aY.parentWindow:false}a.each(["Height","Width"],function(aZ,aY){var a0=aY.toLowerCase();a.fn["inner"+aY]=function(){return this[0]?a.css(this[0],a0,false,"padding"):null};a.fn["outer"+aY]=function(a1){return this[0]?a.css(this[0],a0,false,a1?"margin":"border"):null};a.fn[a0]=function(a1){var a2=this[0];if(!a2){return a1==null?null:this}if(a.isFunction(a1)){return this.each(function(a4){var a3=a(this);a3[a0](a1.call(this,a4,a3[a0]()))})}return("scrollTo" in a2&&a2.document)?a2.document.compatMode==="CSS1Compat"&&a2.document.documentElement["client"+aY]||a2.document.body["client"+aY]:(a2.nodeType===9)?Math.max(a2.documentElement["client"+aY],a2.body["scroll"+aY],a2.documentElement["scroll"+aY],a2.body["offset"+aY],a2.documentElement["offset"+aY]):a1===C?a.css(a2,a0):this.css(a0,typeof a1==="string"?a1:a1+"px")}});aM.jQuery=aM.$=a})(window);(function(bL,r,a8){var bZ=bL.jQuery.noConflict(true);if(typeof r.getAttribute==q){r.getAttribute=function(){}}var al=function(cM){return b9(cM)?cM.toLowerCase():cM};var bx=function(cM){return b9(cM)?cM.toUpperCase():cM};var aA=function(cM){return b9(cM)?cM.replace(/[A-Z]/g,function(cN){return H(cN.charCodeAt(0)|32)}):cM};var b5=function(cM){return b9(cM)?cM.replace(/[a-z]/g,function(cN){return H(cN.charCodeAt(0)&~32)}):cM};if("i"!=="I".toLowerCase()){al=aA;bx=manulaUppercase}function H(cM){return String.fromCharCode(cM)}var cI=undefined,a1=null,bo="$element",S="angular",aY="array",b0="boolean",bq="console",a5="date",aG="display",ct="element",bp="function",ah="length",Z="name",b="none",cv="noop",v="null",b8="number",aK="object",Q="string",q="undefined",a="ng-exception",k="ng-validation-error",o="noop",bf=-99999,am=-1000,b7=99999,aH={FIRST:bf,LAST:b7,WATCH:am},co=bL.jQuery||bL["$"],b1=bL._,ar=parseInt((/msie (\d+)/.exec(al(navigator.userAgent))||[])[1],10),cb=co||cB,ac=Array.prototype.slice,B=Array.prototype.push,cw=bL[bq]?bu(bL[bq],bL[bq]["error"]||j):j,ax=bL[S]||(bL[S]={}),ae=be(ax,"markup"),s=be(ax,"attrMarkup"),aa=be(ax,"directive"),A=be(ax,"widget",al),aF=be(ax,"validator"),cl=be(ax,"filter"),l=be(ax,"formatter"),bi=be(ax,"service"),a7=be(ax,"callbacks"),at,ab=/^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/;function aN(cP,cO,cN){var cM;if(cP){if(D(cP)){for(cM in cP){if(cM!="prototype"&&cM!=ah&&cM!=Z&&cP.hasOwnProperty(cM)){cO.call(cN,cP[cM],cM)}}}else{if(cP.forEach){cP.forEach(cO,cN)}else{if(cH(cP)&&aP(cP.length)){for(cM=0;cM<cP.length;cM++){cO.call(cN,cP[cM],cM)}}else{for(cM in cP){cO.call(cN,cP[cM],cM)}}}}}return cP}function aq(cR,cP,cO){var cQ=[];for(var cN in cR){cQ.push(cN)}cQ.sort();for(var cM=0;cM<cQ.length;cM++){cP.call(cO,cR[cQ[cM]],cQ[cM])}return cQ}function bY(cM){aN(arguments,function(cN){if(cN!==cM){aN(cN,function(cP,cO){cM[cO]=cP})}});return cM}function bW(cN,cM){return bY(new (bY(function(){},{prototype:cN}))(),cM)}function j(){}function aB(cM){return cM}function ci(cM){return function(){return cM}}function be(cO,cN,cM){var cP;return cO[cN]||(cP=cO[cN]=function(cQ,cR,cS){cQ=(cM||aB)(cQ);if(cm(cR)){cP[cQ]=bY(cR,cS||{})}return cP[cQ]})}function cB(cM){if(cM){if(b9(cM)){var cN=r.createElement("div");cN.innerHTML=cM;cM=new bk(cN.childNodes)}else{if(!(cM instanceof bk)&&by(cM)){cM=new bk(cM)}}}return cM}function br(cM){return typeof cM==q}function cm(cM){return typeof cM!=q}function cH(cM){return cM!=a1&&typeof cM==aK}function b9(cM){return typeof cM==Q}function aP(cM){return typeof cM==b8}function a3(cM){return cM instanceof Array}function D(cM){return typeof cM==bp}function t(cM){return at(cM)=="#text"}function au(cM){return b9(cM)?cM.replace(/^\s*/,"").replace(/\s*$/,""):cM}function by(cM){return cM&&(cM.nodeName||cM instanceof bk||(co&&cM instanceof co))}function aR(cN,cO){this.html=cN;this.get=al(cO)=="unsafe"?ci(cN):function cM(){var cP=[];aM(cN,a0(cP));return cP.join("")}}if(ar){at=function(cM){cM=cM.nodeName?cM:cM[0];return(cM.scopeName&&cM.scopeName!="HTML")?bx(cM.scopeName+":"+cM.nodeName):cM.nodeName}}else{at=function(cM){return cM.nodeName?cM.nodeName:cM[0].nodeName}}function z(cM){return cb(cM[0].cloneNode(true))}function aL(cN){var cP=cN[0].getBoundingClientRect(),cO=(cP.width||(cP.right||0-cP.left||0)),cM=(cP.height||(cP.bottom||0-cP.top||0));return cO>0&&cM>0}function aD(cP,cO,cN){var cM=[];aN(cP,function(cS,cQ,cR){cM.push(cO.call(cN,cS,cQ,cR))});return cM}function av(cN){var cM=0;if(cN){if(aP(cN.length)){return cN.length}else{if(cH(cN)){for(key in cN){cM++}}}}return cM}function u(cO,cN){for(var cM=0;cM<cO.length;cM++){if(cN===cO[cM]){return true}}return false}function cE(cO,cN){for(var cM=0;cM<cO.length;cM++){if(cN===cO[cM]){return cM}}return -1}function bV(cM){if(cM){switch(cM.nodeName){case"OPTION":case"PRE":case"TITLE":return true}}return false}function bl(cP,cM){if(!cM){cM=cP;if(cP){if(a3(cP)){cM=bl(cP,[])}else{if(cP instanceof Date){cM=new Date(cP.getTime())}else{if(cH(cP)){cM=bl(cP,{})}}}}}else{if(a3(cP)){while(cM.length){cM.pop()}for(var cO=0;cO<cP.length;cO++){cM.push(bl(cP[cO]))}}else{aN(cM,function(cR,cQ){delete cM[cQ]});for(var cN in cP){cM[cN]=bl(cP[cN])}}}return cM}function p(cS,cR){if(cS==cR){return true}var cQ=typeof cS,cO=typeof cR,cP,cN,cM;if(cQ==cO&&cQ=="object"){if(cS instanceof Array){if((cP=cS.length)==cR.length){for(cN=0;cN<cP;cN++){if(!p(cS[cN],cR[cN])){return false}}return true}}else{cM={};for(cN in cS){if(cN.charAt(0)!=="$"&&!D(cS[cN])&&!p(cS[cN],cR[cN])){return false}cM[cN]=true}for(cN in cR){if(!cM[cN]&&cN.charAt(0)!=="$"&&!D(cR[cN])){return false}}return true}}return false}function V(cN,cM){if(bV(cN)){if(ar){cN.innerText=cM}else{cN.textContent=cM}}else{cN.innerHTML=cM}}function bB(cN){var cM=cN&&cN[0]&&cN[0].nodeName;return cM&&cM.charAt(0)!="#"&&!u(["TR","COL","COLGROUP","TBODY","THEAD","TFOOT"],cM)}function bR(cN,cO,cM){while(!bB(cN)){cN=cN.parent()||cb(r.body)}if(cN[0]["$NG_ERROR"]!==cM){cN[0]["$NG_ERROR"]=cM;if(cM){cN.addClass(cO);cN.attr(cO,cM)}else{cN.removeClass(cO);cN.removeAttr(cO)}}}function a6(cO,cN,cM){return cO.concat(ac.call(cN,cM,cN.length))}function bu(cN,cO){var cM=arguments.length>2?ac.call(arguments,2,arguments.length):[];if(typeof cO==bp){return cM.length?function(){return arguments.length?cO.apply(cN,cM.concat(ac.call(arguments,0,arguments.length))):cO.apply(cN,cM)}:function(){return arguments.length?cO.apply(cN,arguments):cO.call(cN)}}else{return cO}}function cg(cN){if(cN&&cN.length!==0){var cM=al(""+cN);cN=!(cM=="f"||cM=="0"||cM=="false"||cM=="no"||cM=="n"||cM=="[]")}else{cN=false}return cN}function bc(cP,cQ){for(var cM in cP){var cO=cQ[cM];var cN=typeof cO;if(cN==q){cQ[cM]=R(cd(cP[cM]))}else{if(cN=="object"&&cO.constructor!=G&&cM.substring(0,1)!="$"){bc(cP[cM],cO)}}}}function aX(cO,cN){var cP=new a4(ae,s,aa,A),cM=cb(cO);return cP.compile(cM)(cM,cN)}function af(cP){var cO={},cM,cN;aN((cP||"").split("&"),function(cQ){if(cQ){cM=cQ.split("=");cN=unescape(cM[0]);cO[cN]=cm(cM[1])?unescape(cM[1]):true}});return cO}function O(cN){var cM=[];aN(cN,function(cP,cO){cM.push(escape(cO)+(cP===true?"":"="+escape(cP)))});return cM.length?cM.join("&"):""}function bm(cN){if(cN.autobind){var cO=aX(bL.document,a1,{"$config":cN}),cM=cO.$inject("$browser");if(cN.css){cM.addCss(cN.base_url+cN.css)}else{if(ar<8){cM.addJs(cN.base_url+cN.ie_compat,cN.ie_compat_id)}}cO.$init()}}function bw(cN,cQ){var cM=cN.getElementsByTagName("script"),cP;cQ=bY({ie_compat_id:"ng-ie-compat"},cQ);for(var cO=0;cO<cM.length;cO++){cP=(cM[cO].src||"").match(ab);if(cP){cQ.base_url=cP[1];cQ.ie_compat=cP[1]+"angular-ie-compat"+(cP[2]||"")+".js";bY(cQ,af(cP[6]));aZ(cb(cM[cO]),function(cS,cR){if(/^ng:/.exec(cR)){cR=cR.substring(3).replace(/-/g,"_");if(cR=="autobind"){cS=true}cQ[cR]=cS}})}}return cQ}var G=[].constructor;function cd(cO,cN){var cM=[];bI(cM,cO,cN?"\n ":a1,[]);return cM.join("")}function R(cM){if(!cM){return cM}try{var cO=T(cM,true);var cP=cO.primary();cO.assertAllConsumed();return cP()}catch(cN){cw("fromJson error: ",cM,cN);throw cN}}ax.toJson=cd;ax.fromJson=R;function bI(cN,cP,cS,cU){if(typeof cP=="object"){if(u(cU,cP)){cN.push("RECURSION");return}cU.push(cP)}var cT=typeof cP;if(cP===a1){cN.push(v)}else{if(cT===bp){return}else{if(cT===b0){cN.push(""+cP)}else{if(cT===b8){if(isNaN(cP)){cN.push(v)}else{cN.push(""+cP)}}else{if(cT===Q){return cN.push(ax.String["quoteUnicode"](cP))}else{if(cT===aK){if(cP instanceof Array){cN.push("[");var cR=cP.length;var c1=false;for(var cQ=0;cQ<cR;cQ++){var cY=cP[cQ];if(c1){cN.push(",")}if(typeof cY==bp||typeof cY==q){cN.push(v)}else{bI(cN,cY,cS,cU)}c1=true}cN.push("]")}else{if(cP instanceof Date){cN.push(ax.String["quoteUnicode"](ax.Date["toString"](cP)))}else{cN.push("{");if(cS){cN.push(cS)}var c0=false;var cZ=cS?cS+" ":false;var cX=[];for(var cO in cP){if(cO.indexOf("$")===0||cP[cO]===cI){continue}cX.push(cO)}cX.sort();for(var cM=0;cM<cX.length;cM++){var cW=cX[cM];var cV=cP[cW];if(typeof cV!=bp){if(c0){cN.push(",");if(cS){cN.push(cS)}}cN.push(ax.String["quote"](cW));cN.push(":");bI(cN,cV,cZ,cU);c0=true}}cN.push("}")}}}}}}}}if(typeof cP==aK){cU.pop()}}function cn(cM){this.paths=[];this.children=[];this.inits=[];this.priority=cM;this.newScope=false}cn.prototype={init:function(cM,cN){var cO={};this.collectInits(cM,cO,cN);aq(cO,function(cP){aN(cP,function(cQ){cQ()})})},collectInits:function(cO,cR,cU){var cQ=cR[this.priority],cS=cU;if(!cQ){cR[this.priority]=cQ=[]}cO=cb(cO);if(this.newScope){cS=bM(cU);cU.$onEval(cS.$eval)}aN(this.inits,function(cW){cQ.push(function(){cS.$tryEval(function(){return cS.$inject(cW,cS,cO)},cO)})});var cP,cT=cO[0].childNodes,cN=this.children,cV=this.paths,cM=cV.length;for(cP=0;cP<cM;cP++){cN[cP].collectInits(cT[cV[cP]],cR,cS)}},addInit:function(cM){if(cM){this.inits.push(cM)}},addChild:function(cM,cN){if(cN){this.paths.push(cM);this.children.push(cN)}},empty:function(){return this.inits.length===0&&this.paths.length===0}};function a4(cM,cN,cP,cO){this.markup=cM;this.attrMarkup=cN;this.directives=cP;this.widgets=cO}a4.prototype={compile:function(cQ){cQ=cb(cQ);var cM=0,cP,cO=cQ.parent();if(cO&&cO[0]){cO=cO[0];for(var cN=0;cN<cO.childNodes.length;cN++){if(cO.childNodes[cN]==cQ[0]){cM=cN}}}cP=this.templatize(cQ,cM,0)||new cn();return function(cR,cT){cR=cb(cR);var cS=cT&&cT.$eval?cT:bM(cT);return bY(cS,{$element:cR,$init:function(){cP.init(cR,cS);cS.$eval();delete cS.$init;return cS}})}},templatize:function(cR,cN,cV){var cZ=this,cS,cO=cZ.directives,cU=true,cP=true,cY,cX={compile:bu(cZ,cZ.compile),comment:function(c0){return cb(r.createComment(c0))},element:function(c0){return cb(r.createElement(c0))},text:function(c0){return cb(r.createTextNode(c0))},descend:function(c0){if(cm(c0)){cU=c0}return cU},directives:function(c0){if(cm(c0)){cP=c0}return cP},scope:function(c0){if(cm(c0)){cY.newScope=cY.newScope||c0}return cY.newScope}};try{cV=cR.attr("ng:eval-order")||cV||0}catch(cT){cV=cV||0}if(b9(cV)){cV=aH[bx(cV)]||parseInt(cV,10)}cY=new cn(cV);aZ(cR,function(c1,c0){if(!cS){if(cS=cZ.widgets("@"+c0)){cS=bu(cX,cS,c1,cR)}}});if(!cS){if(cS=cZ.widgets(at(cR))){cS=bu(cX,cS,cR)}}if(cS){cU=false;cP=false;var cW=cR.parent();cY.addInit(cS.call(cX,cR));if(cW&&cW[0]){cR=cb(cW[0].childNodes[cN])}}if(cU){for(var cQ=0,cM=cR[0].childNodes;cQ<cM.length;cQ++){if(t(cM[cQ])){aN(cZ.markup,function(c0){if(cQ<cM.length){var c1=cb(cM[cQ]);c0.call(cX,c1.text(),c1,cR)}})}}}if(cP){aZ(cR,function(c1,c0){aN(cZ.attrMarkup,function(c2){c2.call(cX,c1,c0,cR)})});aZ(cR,function(c1,c0){cY.addInit((cO[c0]||j).call(cX,c1,cR))})}if(cU){aS(cR,function(c1,c0){cY.addChild(c0,cZ.templatize(c1,c0,cV))})}return cY.empty()?a1:cY}};function aS(cN,cO){var cM,cQ=cN[0].childNodes||[],cP;for(cM=0;cM<cQ.length;cM++){if(!t(cP=cQ[cM])){cO(cb(cP),cM)}}}function aZ(cN,cR){var cO,cU=cN[0].attributes||[],cT,cQ,cM,cS,cP={};for(cO=0;cO<cU.length;cO++){cQ=cU[cO];cM=cQ.name;cS=cQ.value;if(ar&&cM=="href"){cS=decodeURIComponent(cN[0].getAttribute(cM,2))}cP[cM]=cS}aq(cP,cR)}function bH(cU,cV,cS){if(!cV){return cU}var cN=cV.split(".");var cT;var cM=cU;var cP=cN.length;for(var cO=0;cO<cP;cO++){cT=cN[cO];if(!cT.match(/^[\$\w][\$\w\d]*$/)){throw"Expression '"+cV+"' is not a valid expression for accesing variables."}if(cU){cM=cU;cU=cU[cT]}if(br(cU)&&cT.charAt(0)=="$"){var cQ=ax.Global["typeOf"](cM);cQ=ax[cQ.charAt(0).toUpperCase()+cQ.substring(1)];var cR=cQ?cQ[[cT.substring(1)]]:cI;if(cR){cU=bu(cM,cR,cM);return cU}}}if(!cS&&D(cU)){return bu(cM,cU)}return cU}function b4(cM,cS,cR){var cQ=cS.split(".");for(var cP=0;cQ.length>1;cP++){var cO=cQ.shift();var cN=cM[cO];if(!cN){cN={};cM[cO]=cN}cM=cN}cM[cQ.shift()]=cR;return cR}var aw=0,cu={},aI={},cD={};aN(["abstract","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","export","extends","false","final","finally","float","for",bp,"goto","if","implements","import","ininstanceof","intinterface","long","native","new",v,"package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","volatile","void",q,"while","with"],function(cM){cD[cM]=true});function cf(cO){var cM=cu[cO];if(cM){return cM}var cN="var l, fn, t;\n";aN(cO.split("."),function(cQ){cQ=(cD[cQ])?'["'+cQ+'"]':"."+cQ;cN+="if(!s) return s;\nl=s;\ns=s"+cQ+';\nif(typeof s=="function") s = function(){ return l'+cQ+".apply(l, arguments); };\n";if(cQ.charAt(1)=="$"){var cP=cQ.substr(2);cN+='if(!s) {\n t = angular.Global.typeOf(l);\n fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["'+cP+'"];\n if (fn) s = function(){ return fn.apply(l, [l].concat(Array.prototype.slice.call(arguments, 0, arguments.length))); };\n}\n'}});cN+="return s;";cM=Function("s",cN);cM.toString=function(){return cN};return cu[cO]=cM}function bj(cP){if(typeof cP===bp){return cP}var cM=aI[cP];if(!cM){var cN=T(cP);var cO=cN.statements();cN.assertAllConsumed();cM=aI[cP]=bY(function(){return cO(this)},{fnSelf:cO})}return cM}function an(cN,cM){bR(cN,a,cm(cM)?cd(cM):cM)}function bM(cT,cR,cP){function cM(){}cT=cM.prototype=(cT||{});var cU=new cM();var cV={sorted:[]};var cQ=[],cN={},cO=0;bY(cU,{"this":cU,$id:(aw++),$parent:cT,$bind:bu(cU,bu,cU),$get:bu(cU,bH,cU),$set:bu(cU,b4,cU),$eval:function cS(c2){var c1=typeof c2;var cZ,cY;var cX,c3;var cW;var c0;if(c1==q){for(cZ=0,cY=cV.sorted.length;cZ<cY;cZ++){for(cW=cV.sorted[cZ],c3=cW.length,cX=0;cX<c3;cX++){cU.$tryEval(cW[cX].fn,cW[cX].handler)}}while(cQ.length){c0=cQ.shift();delete cN[c0.$postEvalId];cU.$tryEval(c0)}}else{if(c1===bp){return c2.call(cU)}else{if(c1==="string"){return bj(c2).call(cU)}}}},$tryEval:function(cZ,cW){var cX=typeof cZ;try{if(cX==bp){return cZ.call(cU)}else{if(cX=="string"){return bj(cZ).call(cU)}}}catch(cY){(cU.$log||{error:cw}).error(cY);if(D(cW)){cW(cY)}else{if(cW){an(cW,cY)}else{if(D(cU.$exceptionHandler)){cU.$exceptionHandler(cY)}}}}},$watch:function(c0,cZ,cW){var c1=bj(c0),cY;cZ=bj(cZ);function cX(){var c3=c1.call(cU),c2=cY;if(cY!==c3){cY=c3;cU.$tryEval(function(){return cZ.call(cU,c3,c2)},cW)}}cU.$onEval(am,cX);cX()},$onEval:function(cX,cZ,cW){if(!aP(cX)){cW=cZ;cZ=cX;cX=0}var cY=cV[cX];if(!cY){cY=cV[cX]=[];cY.priority=cX;cV.sorted.push(cY);cV.sorted.sort(function(c1,c0){return c1.priority-c0.priority})}cY.push({fn:bj(cZ),handler:cW})},$postEval:function(cX){if(cX){var cW=bj(cX);var cY=cW.$postEvalId;if(!cY){cY="$"+cU.$id+"_"+(cO++);cW.$postEvalId=cY}if(!cN[cY]){cQ.push(cN[cY]=cW)}}},$become:function(cW){if(D(cW)){cU.constructor=cW;aN(cW.prototype,function(cY,cX){cU[cX]=bu(cU,cY)});cU.$inject.apply(cU,a6([cW,cU],arguments,1));if(D(cW.prototype.init)){cU.init()}}},$new:function(cW){var cX=bM(cU);cX.$become.apply(cU,a6([cW],arguments,1));cU.$onEval(cX.$eval);return cX}});if(!cT.$root){cU.$root=cU;cU.$parent=cU;(cU.$inject=bP(cU,cR,cP))()}return cU}function bP(cN,cP,cM){cP=cP||bi;cM=cM||{};cN=cN||{};return function cO(cU,cT,cR){var cS,cV,cQ;if(b9(cU)){if(!cM.hasOwnProperty(cU)){cV=cP[cU];if(!cV){throw"Unknown provider for '"+cU+"'."}cM[cU]=cO(cV,cN)}cS=cM[cU]}else{if(a3(cU)){cS=[];aN(cU,function(cW){cS.push(cO(cW))})}else{if(D(cU)){cS=cO(cU.$inject||[]);cS=cU.apply(cT,a6(cS,arguments,2))}else{if(cH(cU)){aN(cP,function(cX,cW){cQ=cX.$creation;if(cQ=="eager"){cO(cW)}if(cQ=="eager-published"){b4(cU,cW,cO(cW))}})}else{cS=cO(cN)}}}}return cS}}var K={"null":function(cM){return a1},"true":function(cM){return true},"false":function(cM){return false},$undefined:j,"+":function(cO,cN,cM){return(cm(cN)?cN:0)+(cm(cM)?cM:0)},"-":function(cO,cN,cM){return(cm(cN)?cN:0)-(cm(cM)?cM:0)},"*":function(cO,cN,cM){return cN*cM},"/":function(cO,cN,cM){return cN/cM},"%":function(cO,cN,cM){return cN%cM},"^":function(cO,cN,cM){return cN^cM},"=":function(cO,cN,cM){return b4(cO,cN,cM)},"==":function(cO,cN,cM){return cN==cM},"!=":function(cO,cN,cM){return cN!=cM},"<":function(cO,cN,cM){return cN<cM},">":function(cO,cN,cM){return cN>cM},"<=":function(cO,cN,cM){return cN<=cM},">=":function(cO,cN,cM){return cN>=cM},"&&":function(cO,cN,cM){return cN&&cM},"||":function(cO,cN,cM){return cN||cM},"&":function(cO,cN,cM){return cN&cM},"|":function(cO,cN,cM){return cM(cO,cN)},"!":function(cN,cM){return !cM}};var U={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'};function bg(c0,cQ){var c5=cQ?20:-1,c2=[],cV,cU=0,c7=[],cY,c8=":";while(cU<c0.length){cY=c0.charAt(cU);if(cT("\"'")){cO(cY)}else{if(c1(cY)||cT(".")&&c1(c4())){cP()}else{if(cX("({[:,;")&&cT("/")){cN()}else{if(c3(cY)){cZ();if(cX("{,")&&c7[0]=="{"&&(cV=c2[c2.length-1])){cV.json=cV.text.indexOf(".")==-1}}else{if(cT("(){}[].,;:")){c2.push({index:cU,text:cY,json:cT("{}[]:,")});if(cT("{[")){c7.unshift(cY)}if(cT("}]")){c7.shift()}cU++}else{if(cS(cY)){cU++;continue}else{var cM=cY+c4(),cW=K[cY],c6=K[cM];if(c6){c2.push({index:cU,text:cM,fn:c6});cU+=2}else{if(cW){c2.push({index:cU,text:cY,fn:cW,json:cX("[,:")&&cT("+-")});cU+=1}else{throw"Lexer Error: Unexpected next character ["+c0.substring(cU)+"] in expression '"+c0+"' at column '"+(cU+1)+"'."}}}}}}}}c8=cY}return c2;function cT(c9){return c9.indexOf(cY)!=-1}function cX(c9){return c9.indexOf(c8)!=-1}function c4(){return cU+1<c0.length?c0.charAt(cU+1):false}function c1(c9){return"0"<=c9&&c9<="9"}function cS(c9){return c9==" "||c9=="\r"||c9=="\t"||c9=="\n"||c9=="\v"||c9=="\u00A0"}function c3(c9){return"a"<=c9&&c9<="z"||"A"<=c9&&c9<="Z"||"_"==c9||c9=="$"}function cR(c9){return c9=="-"||c9=="+"}function cP(){var db="";var dc=cU;while(cU<c0.length){var da=c0.charAt(cU);if(da=="."||c1(da)){db+=da}else{var c9=c4();if(da=="E"&&cR(c9)){db+=da}else{if(cR(da)&&c9&&c1(c9)&&db.charAt(db.length-1)=="E"){db+=da}else{if(cR(da)&&(!c9||!c1(c9))&&db.charAt(db.length-1)=="E"){throw'Lexer found invalid exponential value "'+c0+'"'}else{break}}}}cU++}db=1*db;c2.push({index:dc,text:db,json:true,fn:function(){return db}})}function cZ(){var db="";var dc=cU;while(cU<c0.length){var da=c0.charAt(cU);if(da=="."||c3(da)||c1(da)){db+=da}else{break}cU++}var c9=K[db];if(!c9){c9=cf(db);c9.isAssignable=db}c2.push({index:dc,text:db,fn:c9,json:K[db]})}function cO(c9){var dg=cU;cU++;var da="";var db=c9;var de=false;while(cU<c0.length){var dc=c0.charAt(cU);db+=dc;if(de){if(dc=="u"){var dd=c0.substring(cU+1,cU+5);if(!dd.match(/[\da-f]{4}/i)){throw"Lexer Error: Invalid unicode escape [\\u"+dd+"] starting at column '"+dg+"' in expression '"+c0+"'."}cU+=4;da+=String.fromCharCode(parseInt(dd,16))}else{var df=U[dc];if(df){da+=df}else{da+=dc}}de=false}else{if(dc=="\\"){de=true}else{if(dc==c9){cU++;c2.push({index:dg,text:db,string:da,json:true,fn:function(){return(da.length==c5)?ax.String["toDate"](da):da}});return}else{da+=dc}}}cU++}throw"Lexer Error: Unterminated quote ["+c0.substring(dg)+"] starting at column '"+(dg+1)+"' in expression '"+c0+"'."}function cN(db){var df=cU;cU++;var de="";var dd=false;while(cU<c0.length){var dc=c0.charAt(cU);if(dd){de+=dc;dd=false}else{if(dc==="\\"){de+=dc;dd=true}else{if(dc==="/"){cU++;var c9="";if(c3(c0.charAt(cU))){cZ();c9=c2.pop().text}var da=new RegExp(de,c9);c2.push({index:df,text:de,flags:c9,fn:function(){return da}});return}else{de+=dc}}}cU++}throw"Lexer Error: Unterminated RegExp ["+c0.substring(df)+"] starting at column '"+(df+1)+"' in expression '"+c0+"'."}}function T(db,dj){var cZ=ci(0),de=bg(db,dj);return{assertAllConsumed:c5,primary:c2,statements:cR,validator:dk,filter:df,watch:c3};function da(dp,dn){throw"Token '"+dn.text+"' is "+dp+" at column='"+(dn.index+1)+"' of expression '"+db+"' starting at '"+db.substring(dn.index)+"'."}function cS(){if(de.length===0){throw"Unexpected end of expression: "+db}return de[0]}function cU(dt,ds,dr,dq){if(de.length>0){var dp=de[0];var dn=dp.text;if(dn==dt||dn==ds||dn==dr||dn==dq||(!dt&&!ds&&!dr&&!dq)){return dp}}return false}function cO(ds,dr,dq,dp){var dn=cU(ds,dr,dq,dp);if(dn){if(dj&&!dn.json){index=dn.index;throw"Expression at column='"+dn.index+"' of expression '"+db+"' starting at '"+db.substring(dn.index)+"' is not valid json."}de.shift();this.currentToken=dn;return dn}return false}function c7(dp){if(!cO(dp)){var dn=cU();throw"Expecting '"+dp+"' at column '"+(dn.index+1)+"' in '"+db+"' got '"+db.substring(dn.index)+"'."}}function cY(dp,dn){return function(dq){return dp(dq,dn(dq))}}function dl(dq,dp,dn){return function(dr){return dp(dr,dq(dr),dn(dr))}}function cX(){return de.length>0}function c5(){if(de.length!==0){throw"Did not understand '"+db.substring(de[0].index)+"' while evaluating '"+db+"'."}}function cR(){var dn=[];while(true){if(de.length>0&&!cU("}",")",";","]")){dn.push(cV())}if(!cO(";")){return function(dp){var ds;for(var dq=0;dq<dn.length;dq++){var dr=dn[dq];if(dr){ds=dr(dp)}}return ds}}}}function cV(){var dp=c9();var dn;while(true){if((dn=cO("|"))){dp=dl(dp,dn.fn,df())}else{return dp}}}function df(){return cM(cl)}function dk(){return cM(aF)}function cM(dq){var dr=cP(dq);var dn=[];var dp;while(true){if((dp=cO(":"))){dn.push(c9())}else{var ds=function(du,dt){var dv=[dt];for(var dw=0;dw<dn.length;dw++){dv.push(dn[dw](du))}return dr.apply(du,dv)};return function(){return ds}}}}function c9(){return c4()}function c4(){if(cO("throw")){var dn=c0();return function(dp){throw dn(dp)}}else{return c0()}}function c0(){var dq=dh();var dn;if(dn=cO("=")){if(!dq.isAssignable){throw"Left hand side '"+db.substring(0,dn.index)+"' of assignment '"+db.substring(dn.index)+"' is not assignable."}var dp=function(){return dq.isAssignable};return dl(dp,dn.fn,dh())}else{return dq}}function dh(){var dp=cW();var dn;while(true){if((dn=cO("||"))){dp=dl(dp,dn.fn,cW())}else{return dp}}}function cW(){var dp=cQ();var dn;if((dn=cO("&&"))){dp=dl(dp,dn.fn,cW())}return dp}function cQ(){var dp=dc();var dn;if((dn=cO("==","!="))){dp=dl(dp,dn.fn,cQ())}return dp}function dc(){var dp=dd();var dn;if(dn=cO("<",">","<=",">=")){dp=dl(dp,dn.fn,dc())}return dp}function dd(){var dp=cN();var dn;while(dn=cO("+","-")){dp=dl(dp,dn.fn,cN())}return dp}function cN(){var dp=c6();var dn;while(dn=cO("*","/","%")){dp=dl(dp,dn.fn,c6())}return dp}function c6(){var dn;if(cO("+")){return c2()}else{if(dn=cO("-")){return dl(cZ,dn.fn,c6())}else{if(dn=cO("!")){return cY(dn.fn,c6())}else{return c2()}}}}function cP(dt){var ds=cO();var dr=ds.text.split(".");var dn=dt;var dq;for(var dp=0;dp<dr.length;dp++){dq=dr[dp];if(dn){dn=dn[dq]}}if(typeof dn!=bp){throw"Function '"+ds.text+"' at column '"+(ds.index+1)+"' in '"+db+"' is not defined."}return dn}function c2(){var dq;if(cO("(")){var dr=cV();c7(")");dq=dr}else{if(cO("[")){dq=cT()}else{if(cO("{")){dq=di()}else{var dn=cO();dq=dn.fn;if(!dq){da("not a primary expression",dn)}}}}var dp;while(dp=cO("(","[",".")){if(dp.text==="("){dq=c8(dq)}else{if(dp.text==="["){dq=c1(dq)}else{if(dp.text==="."){dq=dg(dq)}else{throw"IMPOSSIBLE"}}}}return dq}function dg(dp){var dr=cO().text;var dn=cf(dr);var dq=function(ds){return dn(dp(ds))};dq.isAssignable=dr;return dq}function c1(dp){var dn=c9();c7("]");if(cO("=")){var dq=c9();return function(dr){return dp(dr)[dn(dr)]=dq(dr)}}else{return function(dr){var dt=dp(dr);var ds=dn(dr);return(dt)?dt[ds]:cI}}}function c8(dp){var dn=[];if(cS().text!=")"){do{dn.push(c9())}while(cO(","))}c7(")");return function(dr){var ds=[];for(var dt=0;dt<dn.length;dt++){ds.push(dn[dt](dr))}var dq=dp(dr)||j;return dq.apply?dq.apply(dr,ds):dq(ds[0],ds[1],ds[2],ds[3],ds[4])}}function cT(){var dn=[];if(cS().text!="]"){do{dn.push(c9())}while(cO(","))}c7("]");return function(dp){var dr=[];for(var dq=0;dq<dn.length;dq++){dr.push(dn[dq](dp))}return dr}}function di(){var dn=[];if(cS().text!="}"){do{var dq=cO(),dp=dq.string||dq.text;c7(":");var dr=c9();dn.push({key:dp,value:dr})}while(cO(","))}c7("}");return function(ds){var dt={};for(var du=0;du<dn.length;du++){var dw=dn[du];var dv=dw.value(ds);dt[dw.key]=dv}return dt}}function c3(){var dn=[];while(cX()){dn.push(dm());if(!cO(";")){c5()}}c5();return function(dp){for(var dq=0;dq<dn.length;dq++){var dr=dn[dq](dp);dp.addListener(dr.name,dr.fn)}}}function dm(){var dn=cO().text;c7(":");var dp;if(cS().text=="{"){c7("{");dp=cR();c7("}")}else{dp=c9()}return function(dq){return{name:dn,fn:dp}}}}function bO(cN,cO){this.template=cN=cN+"#";this.defaults=cO||{};var cM=this.urlParams={};aN(cN.split(/\W/),function(cP){if(cP&&cN.match(new RegExp(":"+cP+"\\W"))){cM[cP]=true}})}bO.prototype={url:function(cQ){var cP=[];var cM=this;var cN=this.template;cQ=cQ||{};aN(this.urlParams,function(cS,cR){var cT=cQ[cR]||cM.defaults[cR]||"";cN=cN.replace(new RegExp(":"+cR+"(\\W)"),cT+"$1")});cN=cN.replace(/\/?#$/,"");var cO=[];aq(cQ,function(cS,cR){if(!cM.urlParams[cR]){cO.push(encodeURI(cR)+"="+encodeURI(cS))}});cN=cN.replace(/\/*$/,"");return cN+(cO.length?"?"+cO.join("&"):"")}};function bE(cM){this.xhr=cM}bE.DEFAULT_ACTIONS={get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:true},remove:{method:"DELETE"},"delete":{method:"DELETE"}};bE.prototype={route:function(cP,cQ,cS){var cN=this;var cM=new bO(cP);cS=bY({},bE.DEFAULT_ACTIONS,cS);function cO(cU){var cT={};aN(cQ||{},function(cW,cV){cT[cV]=cW.charAt&&cW.charAt(0)=="@"?bH(cU,cW.substr(1)):cW});return cT}function cR(cT){bl(cT||{},this)}aN(cS,function(cV,cU){var cT=cV.method=="POST"||cV.method=="PUT";cR[cU]=function(cX,cW,c2){var c0={};var cZ;var c1=j;switch(arguments.length){case 3:c1=c2;case 2:if(D(cW)){c1=cW}else{c0=cX;cZ=cW;break}case 1:if(D(cX)){c1=cX}else{if(cT){cZ=cX}else{c0=cX}}break;case 0:break;default:throw"Expected between 0-3 arguments [params, data, callback], got "+arguments.length+" arguments."}var cY=this instanceof cR?this:(cV.isArray?[]:new cR(cZ));cN.xhr(cV.method,cM.url(bY({},cV.params||{},cO(cZ),c0)),cZ,function(c4,c5,c3){if(c4==200){if(cV.isArray){cY.length=0;aN(c5,function(c6){cY.push(new cR(c6))})}else{bl(c5,cY)}(c1||j)(cY)}else{throw {status:c4,response:c5,message:c4+": "+c5}}},cV.verifyCache);return cY};cR.bind=function(cW){return cN.route(cP,bY({},cQ,cW),cS)};cR.prototype["$"+cU]=function(cX,cW){var cZ=cO(this);var c0=j;switch(arguments.length){case 2:cZ=cX;c0=cW;case 1:if(typeof cX==bp){c0=cX}else{cZ=cX}case 0:break;default:throw"Expected between 1-2 arguments [params, callback], got "+arguments.length+" arguments."}var cY=cT?this:cI;cR[cU].call(this,cZ,cY,c0)}});return cR}};var M=bL.XMLHttpRequest||function(){try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(cO){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(cN){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(cM){}throw new Error("This browser does not support XMLHttpRequest.")};function aJ(cX,cV,cW,cT,c0){var cY=this;cY.isMock=false;var cQ=0;var cS=0;var cZ=[];cY.xhr=function(c7,c2,c3,c6){if(D(c3)){c6=c3;c3=a1}if(al(c7)=="json"){var c4="angular_"+Math.random()+"_"+(cQ++);c4=c4.replace(/\d\./,"");var c1=cV[0].createElement("script");c1.type="text/javascript";c1.src=c2.replace("JSON_CALLBACK",c4);bL[c4]=function(c8){bL[c4]=cI;c6(200,c8)};cW.append(c1)}else{var c5=new cT();c5.open(c7,c2,true);c5.setRequestHeader("Content-Type","application/x-www-form-urlencoded");c5.setRequestHeader("Accept","application/json, text/plain, */*");c5.setRequestHeader("X-Requested-With","XMLHttpRequest");cS++;c5.onreadystatechange=function(){if(c5.readyState==4){try{c6(c5.status||200,c5.responseText)}finally{cS--;if(cS===0){while(cZ.length){try{cZ.pop()()}catch(c8){}}}}}};c5.send(c3||"")}};cY.notifyWhenNoOutstandingRequests=function(c1){if(cS===0){c1()}else{cZ.push(c1)}};var cP=[];function cU(){aN(cP,function(c1){c1()})}cY.poll=cU;cY.addPollFn=function(c1){cP.push(c1);return c1};cY.startPoller=function(c2,c3){(function c1(){cU();c3(c1,c2)})()};cY.setUrl=function(c2){var c1=cX.href;if(!c1.match(/#/)){c1+="#"}if(!c2.match(/#/)){c2+="#"}cX.href=c2};cY.getUrl=function(){return cX.href};var cM=cV[0];var cO={};var cN="";cY.cookies=function(c2,c4){var c6,c1,c3,c5;if(c2){if(c4===cI){cM.cookie=escape(c2)+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT"}else{if(b9(c4)){cM.cookie=escape(c2)+"="+escape(c4);c6=c2.length+c4.length+1;if(c6>4096){c0.warn("Cookie '"+c2+"' possibly not set or overflowed because it was too large ("+c6+" > 4096 bytes)!")}if(cO.length>20){c0.warn("Cookie '"+c2+"' possibly not set or overflowed because too many cookies were already set ("+cO.length+" > 20 )")}}}}else{if(cM.cookie!==cN){cN=cM.cookie;c1=cN.split("; ");cO={};for(c3=0;c3<c1.length;c3++){c5=c1[c3].split("=");if(c5.length===2){cO[unescape(c5[0])]=unescape(c5[1])}}}return cO}};var cR=j;cY.hover=function(c1){cR=c1};cY.bind=function(){cV.bind("mouseover",function(c1){cR(cb(ar?c1.srcElement:c1.target),true);return true});cV.bind("mouseleave mouseout click dblclick keypress keyup",function(c1){cR(cb(c1.target),false);return true})};cY.addCss=function(c1){var c2=cb(cM.createElement("link"));c2.attr("rel","stylesheet");c2.attr("type","text/css");c2.attr("href",c1);cW.append(c2)};cY.addJs=function(c3,c2){var c1=cb(cM.createElement("script"));c1.attr("type","text/javascript");c1.attr("src",c3);if(c2){c1.attr("id",c2)}cW.append(c1)}}var bX=/^<\s*([\w:]+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,n=/^<\s*\/\s*([\w:]+)[^>]*>/,cj=/(\w+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g,cp=/^</,g=/^<\s*\//,az=/<!--(.*?)-->/g,bN=/<!\[CDATA\[(.*?)]]>/g;var aQ=cx("area,base,basefont,br,col,hr,img,input,isindex,link,param");var bT=cx("address,blockquote,button,center,dd,del,dir,div,dl,dt,fieldset,form,hr,ins,isindex,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");var ak=cx("a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");var L=cx("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");var aW=cx("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");var bF=cx("script,style");var bn=bY({},aQ,bT,ak,L);var a2=bY({},aW,cx("abbr,align,alink,alt,archive,axis,background,bgcolor,border,cellpadding,cellspacing,cite,class,classid,clear,code,codebase,codetype,color,cols,colspan,content,coords,data,dir,face,for,headers,height,href,hreflang,hspace,id,label,lang,language,link,longdesc,marginheight,marginwidth,maxlength,media,method,name,nowrap,profile,prompt,rel,rev,rows,rowspan,rules,scheme,scope,scrolling,shape,size,span,src,standby,start,summary,tabindex,target,text,title,type,usemap,valign,value,valuetype,vlink,vspace,width"));var aM=function(cN,cV){var cQ,cR,cO,cS=[],cT=cN;cS.last=function(){return cS[cS.length-1]};while(cN){cR=true;if(!cS.last()||!bF[cS.last()]){if(cN.indexOf("<!--")===0){cQ=cN.indexOf("-->");if(cQ>=0){if(cV.comment){cV.comment(cN.substring(4,cQ))}cN=cN.substring(cQ+3);cR=false}}else{if(g.test(cN)){cO=cN.match(n);if(cO){cN=cN.substring(cO[0].length);cO[0].replace(n,cP);cR=false}}else{if(cp.test(cN)){cO=cN.match(bX);if(cO){cN=cN.substring(cO[0].length);cO[0].replace(bX,cM);cR=false}}}}if(cR){cQ=cN.indexOf("<");var cU=cQ<0?cN:cN.substring(0,cQ);cN=cQ<0?"":cN.substring(cQ);if(cV.chars){cV.chars(cU)}}}else{cN=cN.replace(new RegExp("(.*)<\\s*\\/\\s*"+cS.last()+"[^>]*>","i"),function(cW,cX){cX=cX.replace(az,"$1").replace(bN,"$1");if(cV.chars){cV.chars(cX)}return""});cP("",cS.last())}if(cN==cT){throw"Parse Error: "+cN}cT=cN}cP();function cM(cW,cZ,c0,cX){cZ=al(cZ);if(bT[cZ]){while(cS.last()&&ak[cS.last()]){cP("",cS.last())}}if(L[cZ]&&cS.last()==cZ){cP("",cZ)}cX=aQ[cZ]||!!cX;if(!cX){cS.push(cZ)}if(cV.start){var cY={};c0.replace(cj,function(c2,c1){var c3=arguments[2]?arguments[2]:arguments[3]?arguments[3]:arguments[4]?arguments[4]:aW[c1]?c1:"";cY[c1]=c3});if(cV.start){cV.start(cZ,cY,cX)}}}function cP(cW,cY){var cZ=0,cX;cY=al(cY);if(cY){for(cZ=cS.length-1;cZ>=0;cZ--){if(cS[cZ]==cY){break}}}if(cZ>=0){for(cX=cS.length-1;cX>=cZ;cX--){if(cV.end){cV.end(cS[cX])}}cS.length=cZ}}};function cx(cP){var cO={},cM=cP.split(","),cN;for(cN=0;cN<cM.length;cN++){cO[cM[cN]]=true}return cO}var ag=/^javascript:/i,E=/&nbsp;/gim,F=/&#x([\da-f]*);?/igm,cL=/&#(\d+);?/igm,bD=/[\w:]/gm,bK=function(cM,cN){return H(parseInt(cN,16))},cA=function(cM,cN){return H(cN)};function bG(cM){var cN=[];cM.replace(E,"").replace(F,bK).replace(cL,cA).replace(bD,function(cO){cN.push(cO)});return ag.test(al(cN.join("")))}function a0(cN){var cO=false;var cM=bu(cN,cN.push);return{start:function(cP,cR,cQ){cP=al(cP);if(!cO&&bF[cP]){cO=cP}if(!cO&&bn[cP]){cM("<");cM(cP);aN(cR,function(cT,cS){if(a2[al(cS)]&&!bG(cT)){cM(" ");cM(cS);cM('="');cM(cT.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;"));cM('"')}});cM(cQ?"/>":">")}},end:function(cP){cP=al(cP);if(!cO&&bn[cP]){cM("</");cM(cP);cM(">")}if(cP==cO){cO=false}},chars:function(cP){if(!cO){cM(cP.replace(/&(\w+[&;\W])?/g,function(cR,cQ){return cQ?cR:"&amp;"}).replace(/</g,"&lt;").replace(/>/g,"&gt;"))}}}}var b3={},cs="ng-"+new Date().getTime(),ai=1,ay=(bL.document.attachEvent?function(cM,cO,cN){cM.attachEvent("on"+cO,cN)}:function(cM,cO,cN){cM.addEventListener(cO,cN,false)}),e=(bL.document.detachEvent?function(cM,cO,cN){cM.detachEvent("on"+cO,cN)}:function(cM,cO,cN){cM.removeEventListener(cO,cN,false)});function b6(){return(ai++)}function cK(cN){var cO=cN[cs],cM=b3[cO];if(cM){aN(cM.bind||{},function(cQ,cP){e(cN,cP,cQ)});delete b3[cO];if(ar){cN[cs]=""}else{delete cN[cs]}}}function b2(cO){var cR={},cP=cO[0].style,cQ,cM,cN;if(typeof cP.length=="number"){for(cN=0;cN<cP.length;cN++){cM=cP[cN];cR[cM]=cP[cM]}}else{for(cM in cP){cQ=cP[cM];if(1*cM!=cM&&cM!="cssText"&&cQ&&typeof cQ=="string"&&cQ!="false"){cR[cM]=cQ}}}return cR}function bk(cN){if(by(cN)){this[0]=cN;this.length=1}else{if(cm(cN.length)&&cN.item){for(var cM=0;cM<cN.length;cM++){this[cM]=cN[cM]}this.length=cN.length}}}bk.prototype={data:function(cO,cP){var cN=this[0],cQ=cN[cs],cM=b3[cQ||-1];if(cm(cP)){if(!cM){cN[cs]=cQ=b6();cM=b3[cQ]={}}cM[cO]=cP}else{return cM?cM[cO]:a1}},removeData:function(){cK(this[0])},dealoc:function(){(function cM(cP){cK(cP);for(var cO=0,cN=cP.childNodes;cO<cN.length;cO++){cM(cN[cO])}})(this[0])},bind:function(cQ,cP){var cM=this,cO=cM[0],cR=cM.data("bind"),cN;if(!cR){this.data("bind",cR={})}aN(cQ.split(" "),function(cS){cN=cR[cS];if(!cN){cR[cS]=cN=function(cT){if(!cT.preventDefault){cT.preventDefault=function(){cT.returnValue=false}}if(!cT.stopPropagation){cT.stopPropagation=function(){cT.cancelBubble=true}}aN(cN.fns,function(cU){cU.call(cM,cT)})};cN.fns=[];ay(cO,cS,cN)}cN.fns.push(cP)})},replaceWith:function(cM){this[0].parentNode.replaceChild(cb(cM)[0],this[0])},children:function(){return new bk(this[0].childNodes)},append:function(cN){var cM=this[0];cN=cb(cN);aN(cN,function(cO){cM.appendChild(cO)})},remove:function(){this.dealoc();var cM=this[0].parentNode;if(cM){cM.removeChild(this[0])}},removeAttr:function(cM){this[0].removeAttribute(cM)},after:function(cM){this[0].parentNode.insertBefore(cb(cM)[0],this[0].nextSibling)},hasClass:function(cM){var cN=" "+cM+" ";if((" "+this[0].className+" ").replace(/[\n\t]/g," ").indexOf(cN)>-1){return true}return false},removeClass:function(cM){this[0].className=au((" "+this[0].className+" ").replace(/[\n\t]/g," ").replace(" "+cM+" ",""))},toggleClass:function(cM,cO){var cN=this;(cO?cN.addClass:cN.removeClass).call(cN,cM)},addClass:function(cM){if(!this.hasClass(cM)){this[0].className=au(this[0].className+" "+cM)}},css:function(cM,cO){var cN=this[0].style;if(b9(cM)){if(cm(cO)){cN[cM]=cO}else{return cN[cM]}}else{bY(cN,cM)}},attr:function(cM,cN){var cO=this[0];if(cH(cM)){aN(cM,function(cQ,cP){cO.setAttribute(cP,cQ)})}else{if(cm(cN)){cO.setAttribute(cM,cN)}else{return cO.getAttribute(cM,2)}}},text:function(cM){if(cm(cM)){this[0].textContent=cM}return this[0].textContent},val:function(cM){if(cm(cM)){this[0].value=cM}return this[0].value},html:function(cN){if(cm(cN)){var cM=0,cO=this[0].childNodes;for(;cM<cO.length;cM++){cb(cO[cM]).dealoc()}this[0].innerHTML=cN}return this[0].innerHTML},parent:function(){return cb(this[0].parentNode)},clone:function(){return cb(this[0].cloneNode(true))}};if(ar){bY(bk.prototype,{text:function(cM){var cN=this[0];if(cN.nodeType==3){if(cm(cM)){cN.nodeValue=cM}return cN.nodeValue}else{if(cm(cM)){cN.innerText=cM}return cN.innerText}}})}var aT={typeOf:function(cN){if(cN===a1){return v}var cM=typeof cN;if(cM==aK){if(cN instanceof Array){return aY}if(cN instanceof Date){return a5}if(cN.nodeType==1){return ct}}return cM}};var cG={copy:bl,size:av,equals:p};var ba={extend:bY};var N={indexOf:cE,sum:function(cR,cQ){var cO=ax.Function["compile"](cQ);var cN=0;for(var cM=0;cM<cR.length;cM++){var cP=1*cO(cR[cM]);if(!isNaN(cP)){cN+=cP}}return cN},remove:function(cO,cN){var cM=cE(cO,cN);if(cM>=0){cO.splice(cM,1)}return cN},filter:function(cT,cS){var cO=[];cO.check=function(cV){for(var cU=0;cU<cO.length;cU++){if(!cO[cU](cV)){return false}}return true};var cQ=function(cW,cX){if(cX.charAt(0)==="!"){return !cQ(cW,cX.substr(1))}switch(typeof cW){case"boolean":case"number":case"string":return(""+cW).toLowerCase().indexOf(cX)>-1;case"object":for(var cV in cW){if(cV.charAt(0)!=="$"&&cQ(cW[cV],cX)){return true}}return false;case"array":for(var cU=0;cU<cW.length;cU++){if(cQ(cW[cU],cX)){return true}}return false;default:return false}};switch(typeof cS){case"boolean":case"number":case"string":cS={$:cS};case"object":for(var cP in cS){if(cP=="$"){(function(){var cU=(""+cS[cP]).toLowerCase();if(!cU){return}cO.push(function(cV){return cQ(cV,cU)})})()}else{(function(){var cU=cP;var cV=(""+cS[cP]).toLowerCase();if(!cV){return}cO.push(function(cW){return cQ(bH(cW,cU),cV)})})()}}break;case bp:cO.push(cS);break;default:return cT}var cN=[];for(var cM=0;cM<cT.length;cM++){var cR=cT[cM];if(cO.check(cR)){cN.push(cR)}}return cN},add:function(cN,cM){cN.push(br(cM)?{}:cM);return cN},count:function(cP,cO){if(!cO){return cP.length}var cM=ax.Function["compile"](cO),cN=0;aN(cP,function(cQ){if(cM(cQ)){cN++}});return cN},orderBy:function(cT,cS,cQ){cS=a3(cS)?cS:[cS];cS=aD(cS,function(cV){var cW=false,cU=cV||aB;if(b9(cV)){if((cV.charAt(0)=="+"||cV.charAt(0)=="-")){cW=cV.charAt(0)=="-";cV=cV.substring(1)}cU=bj(cV).fnSelf}return cN(function(cY,cX){return cR(cU(cY),cU(cX))},cW)});var cP=[];for(var cO=0;cO<cT.length;cO++){cP.push(cT[cO])}return cP.sort(cN(cM,cQ));function cM(cX,cW){for(var cV=0;cV<cS.length;cV++){var cU=cS[cV](cX,cW);if(cU!==0){return cU}}return 0}function cN(cU,cV){return cg(cV)?function(cX,cW){return cU(cW,cX)}:cU}function cR(cX,cW){var cV=typeof cX;var cU=typeof cW;if(cV==cU){if(cV=="string"){cX=cX.toLowerCase()}if(cV=="string"){cW=cW.toLowerCase()}if(cX===cW){return 0}return cX<cW?-1:1}else{return cV<cU?-1:1}}}};var ap={quote:function(cM){return'"'+cM.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\v/g,"\\v")+'"'},quoteUnicode:function(cM){var cR=ax.String["quote"](cM);var cQ=[];for(var cN=0;cN<cR.length;cN++){var cO=cR.charCodeAt(cN);if(cO<128){cQ.push(cR.charAt(cN))}else{var cP="000"+cO.toString(16);cQ.push("\\u"+cP.substring(cP.length-4))}}return cQ.join("")},toDate:function(cO){var cN;if(typeof cO=="string"&&(cN=cO.match(/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z$/))){var cM=new Date(0);cM.setUTCFullYear(cN[1],cN[2]-1,cN[3]);cM.setUTCHours(cN[4],cN[5],cN[6],0);return cM}return cO}};var ad={toString:function(cM){function cN(cO){return cO<10?"0"+cO:cO}return !cM?cM:cM.getUTCFullYear()+"-"+cN(cM.getUTCMonth()+1)+"-"+cN(cM.getUTCDate())+"T"+cN(cM.getUTCHours())+":"+cN(cM.getUTCMinutes())+":"+cN(cM.getUTCSeconds())+"Z"}};var w={compile:function(cM){if(D(cM)){return cM}else{if(cM){return bj(cM).fnSelf}else{return aB}}}};function J(cN,cM){ax[cN]=ax[cN]||{};aN(cM,function(cO){bY(ax[cN],cO)})}J("Global",[aT]);J("Collection",[aT,cG]);J("Array",[aT,cG,N]);J("Object",[aT,cG,ba]);J("String",[aT,ap]);J("Date",[aT,ad]);ax.Date["toString"]=ad.toString;J("Function",[aT,cG,w]);cl.currency=function(cM){this.$element.toggleClass("ng-format-negative",cM<0);return"$"+cl.number.apply(this,[cM,2])};cl.number=function(cR,cM){if(isNaN(cR)||!isFinite(cR)){return""}cM=typeof cM==q?2:cM;var cN=cR<0;cR=Math.abs(cR);var cS=Math.pow(10,cM);var cU=""+Math.round(cR*cS);var cT=cU.substring(0,cU.length-cM);cT=cT||"0";var cO=cU.substring(cU.length-cM);cU=cN?"-":"";for(var cQ=0;cQ<cT.length;cQ++){if((cT.length-cQ)%3===0&&cQ!==0){cU+=","}cU+=cT.charAt(cQ)}if(cM>0){for(var cP=cO.length;cP<cM;cP++){cO+="0"}cU+="."+cO.substring(0,cM)}return cU};function ce(cN,cO,cM){var cP="";if(cN<0){cP="-";cN=-cN}cN=""+cN;while(cN.length<cO){cN="0"+cN}if(cM){cN=cN.substr(cN.length-cO)}return cP+cN}function bh(cN,cO,cP,cM){return function(cQ){var cR=cQ["get"+cN]();if(cP>0||cR>-cP){cR+=cP}if(cR===0&&cP==-12){cR=12}return ce(cR,cO,cM)}}var bv={yyyy:bh("FullYear",4),yy:bh("FullYear",2,0,true),MM:bh("Month",2,1),M:bh("Month",1,1),dd:bh("Date",2),d:bh("Date",1),HH:bh("Hours",2),H:bh("Hours",1),hh:bh("Hours",2,-12),h:bh("Hours",1,-12),mm:bh("Minutes",2),m:bh("Minutes",1),ss:bh("Seconds",2),s:bh("Seconds",1),a:function(cM){return cM.getHours()<12?"am":"pm"},Z:function(cM){var cN=cM.getTimezoneOffset();return ce(cN/60,2)+ce(Math.abs(cN%60),2)}};var ao=/([^yMdHhmsaZ]*)(y+|M+|d+|H+|h+|m+|s+|a|Z)(.*)/;var ch=/^\d+$/;cl.date=function(cM,cP){if(b9(cM)&&ch.test(cM)){cM=parseInt(cM,10)}if(aP(cM)){cM=new Date(cM)}else{if(!(cM instanceof Date)){return cM}}var cQ=cM.toLocaleDateString(),cN;if(cP&&b9(cP)){cQ="";var cO=[];while(cP){cO=a6(cO,ao.exec(cP),1);cP=cO.pop()}aN(cO,function(cR){cN=bv[cR];cQ+=cN?cN(cM):cR})}return cQ};cl.json=function(cM){this.$element.addClass("ng-monospace");return cd(cM,true)};cl.lowercase=al;cl.uppercase=bx;cl.html=function(cM,cN){return new aR(cM,cN)};cl.linky=function(cT){if(!cT){return cT}function cU(cV){return cV.replace(/([\/\.\*\+\?\|\(\)\[\]\{\}\\])/g,"\\$1")}var cR=/(ftp|http|https|mailto):\/\/([^\(\)|\s]+)/;var cQ;var cS=cT;var cP=[];var cN=a0(cP);var cM;var cO;while(cQ=cS.match(cR)){cM=cQ[0].replace(/[\.\;\,\(\)\{\}\<\>]$/,"");cO=cS.indexOf(cM);cN.chars(cS.substr(0,cO));cN.start("a",{href:cM});cN.chars(cM);cN.end("a");cS=cS.substring(cO+cM.length)}cN.chars(cS);return new aR(cP.join(""))};function aV(cM,cN){return{format:cM,parse:cN||cM}}function C(cM){return(cm(cM)&&cM!==a1)?""+cM:cM}var aO=/^\s*[-+]?\d*(\.\d*)?\s*$/;l.noop=aV(aB,aB);l.json=aV(cd,R);l["boolean"]=aV(C,cg);l.number=aV(C,function(cM){if(cM==a1||aO.exec(cM)){return cM===a1||cM===""?a1:1*cM}else{throw"Not a number"}});l.list=aV(function(cM){return cM?cM.join(", "):cM},function(cN){var cM=[];aN((cN||"").split(","),function(cO){cO=au(cO);if(cO){cM.push(cO)}});return cM});l.trim=aV(function(cM){return cM?au(""+cM):""});aN({noop:function(){return a1},regexp:function(cN,cM,cO){if(!cN.match(cM)){return cO||"Value does not match expected format "+cM+"."}else{return a1}},number:function(cP,cO,cM){var cN=1*cP;if(cN==cP){if(typeof cO!=q&&cN<cO){return"Value can not be less than "+cO+"."}if(typeof cO!=q&&cN>cM){return"Value can not be greater than "+cM+"."}return a1}else{return"Not a number"}},integer:function(cP,cN,cM){var cO=aF.number(cP,cN,cM);if(cO){return cO}if(!(""+cP).match(/^\s*[\d+]*\s*$/)||cP!=Math.round(cP)){return"Not a whole number"}return a1},date:function(cO){var cM=/^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/.exec(cO);var cN=cM?new Date(cM[3],cM[1]-1,cM[2]):0;return(cN&&cN.getFullYear()==cM[3]&&cN.getMonth()==cM[1]-1&&cN.getDate()==cM[2])?a1:"Value is not a date. (Expecting format: 12/31/2009)."},ssn:function(cM){if(cM.match(/^\d\d\d-\d\d-\d\d\d\d$/)){return a1}return"SSN needs to be in 999-99-9999 format."},email:function(cM){if(cM.match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)){return a1}return"Email needs to be in [email protected] format."},phone:function(cM){if(cM.match(/^1\(\d\d\d\)\d\d\d-\d\d\d\d$/)){return a1}if(cM.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)){return a1}return"Phone number needs to be in 1(987)654-3210 format in North America or +999 (123) 45678 906 internationaly."},url:function(cM){if(cM.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)){return a1}return"URL needs to be in http://server[:port]/path format."},json:function(cM){try{R(cM);return a1}catch(cN){return cN.toString()}},asynchronous:function(cP,cS,cN){if(!cP){return}var cR=this;var cQ=cR.$element;var cO=cQ.data("$asyncValidator");if(!cO){cQ.data("$asyncValidator",cO={inputs:{}})}cO.current=cP;var cM=cO.inputs[cP];if(!cM){cO.inputs[cP]=cM={inFlight:true};cR.$invalidWidgets.markInvalid(cR.$element);cQ.addClass("ng-input-indicator-wait");cS(cP,function(cT,cU){cM.response=cU;cM.error=cT;cM.inFlight=false;if(cO.current==cP){cQ.removeClass("ng-input-indicator-wait");cR.$invalidWidgets.markValid(cQ)}cQ.data("$validate")();cR.$root.$eval()})}else{if(cM.inFlight){cR.$invalidWidgets.markInvalid(cR.$element)}else{(cN||j)(cM.response)}}return cM.error}},function(cN,cM){aF[cM]=cN});var I=/^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,y=/^([^\?]*)?(\?([^\?]*))?$/,cr={http:80,https:443,ftp:21},bJ="eager",bz=bJ+"-published";function cc(cN,cP,cO,cM){bi(cN,cP,{$inject:cO,$creation:cM})}cc("$window",bu(bL,aB,bL),[],bz);cc("$document",function(cM){return cb(cM.document)},["$window"],bz);cc("$location",function(cS){var cZ=this,cW={toString:cN,update:cR,updateHash:cV},cP=cS.getUrl(),cT;cS.addPollFn(function(){if(cP!==cS.getUrl()){cR(cP=cS.getUrl());cZ.$eval()}});this.$onEval(bf,cU);this.$onEval(b7,cU);cR(cP);cT=cW.hash;return cW;function cR(c0){if(b9(c0)){bY(cW,cY(c0))}else{if(cm(c0.hash)){bY(c0,cQ(c0.hash))}bY(cW,c0);if(cm(c0.hashPath||c0.hashSearch)){cW.hash=cO(cW)}cW.href=cX(cW)}}function cV(c2,c0){var c1={};if(b9(c2)){c1.hashPath=c2;if(cm(c0)){c1.hashSearch=c0}}else{c1.hashSearch=c2}cR(c1)}function cN(){cM();return cW.href}function cM(){if(cW.href==cP){if(cW.hash==cT){cW.hash=cO(cW)}cW.href=cX(cW)}cR(cW.href)}function cU(){cM();if(cW.href!=cP){cS.setUrl(cP=cW.href);cT=cW.hash}}function cX(c2){var c1=O(c2.search);var c0=(c2.port==cr[c2.protocol]?a1:c2.port);return c2.protocol+"://"+c2.host+(c0?":"+c0:"")+c2.path+(c1?"?"+c1:"")+(c2.hash?"#"+c2.hash:"")}function cO(c1){var c0=O(c1.hashSearch);return escape(c1.hashPath)+(c0?"?"+c0:"")}function cY(c0){var c2={};var c1=I.exec(c0);if(c1){c2.href=c0.replace("#$","");c2.protocol=c1[1];c2.host=c1[3]||"";c2.port=c1[5]||cr[c2.protocol]||a1;c2.path=c1[6]||"";c2.search=af(c1[8]);c2.hash=c1[10]||"";bY(c2,cQ(c2.hash))}return c2}function cQ(c2){var c1={};var c0=y.exec(c2);if(c0){c1.hash=c2;c1.hashPath=unescape(c0[1]||"");c1.hashSearch=af(c0[3])}return c1}},["$browser"],bz);cc("$log",function(cO){var cM=cO.console||{log:j,warn:j,info:j,error:j},cN=cM.log||j;return{log:bu(cM,cN),warn:bu(cM,cM.warn||cN),info:bu(cM,cM.info||cN),error:bu(cM,cM.error||cN)}},["$window"],bz);cc("$exceptionHandler",function(cM){return function(cN){cM.error(cN)}},["$log"],bz);cc("$hover",function(cR,cN){var cT,cP=this,cQ,cS=300,cO=10,cM=cb(cN[0].body);cR.hover(function(cX,cV){if(cV&&(cQ=cX.attr(a)||cX.attr(k))){if(!cT){cT={callout:cb('<div id="ng-callout"></div>'),arrow:cb("<div></div>"),title:cb('<div class="ng-title"></div>'),content:cb('<div class="ng-content"></div>')};cT.callout.append(cT.arrow);cT.callout.append(cT.title);cT.callout.append(cT.content);cM.append(cT.callout)}var cU=cM[0].getBoundingClientRect(),cW=cX[0].getBoundingClientRect(),cY=cU.right-cW.right-cO;cT.title.text(cX.hasClass("ng-exception")?"EXCEPTION:":"Validation error...");cT.content.text(cQ);if(cY<cS){cT.arrow.addClass("ng-arrow-right");cT.arrow.css({left:(cS+1)+"px"});cT.callout.css({position:"fixed",left:(cW.left-cO-cS-4)+"px",top:(cW.top-3)+"px",width:cS+"px"})}else{cT.arrow.addClass("ng-arrow-left");cT.callout.css({position:"fixed",left:(cW.right+cO)+"px",top:(cW.top-3)+"px",width:cS+"px"})}}else{if(cT){cT.callout.remove();cT=a1}}})},["$browser","$document"],bJ);cc("$invalidWidgets",function(){var cN=[];cN.markValid=function(cP){var cO=cE(cN,cP);if(cO!=-1){cN.splice(cO,1)}};cN.markInvalid=function(cP){var cO=cE(cN,cP);if(cO===-1){cN.push(cP)}};cN.visible=function(){var cO=0;aN(cN,function(cP){cO=cO+(aL(cP)?1:0)});return cO};this.$onEval(b7,function(){for(var cO=0;cO<cN.length;){var cP=cN[cO];if(cM(cP[0])){cN.splice(cO,1);if(cP.dealoc){cP.dealoc()}}else{cO++}}});function cM(cP){if(cP==bL.document){return false}var cO=cP.parentNode;return !cO||cM(cO)}return cN},[],bz);function a9(cN,cM,cQ){var cP="^"+cM.replace(/[\.\\\(\)\^\$]/g,"$1")+"$",cR=[],cS={};aN(cM.split(/\W/),function(cU){if(cU){var cT=new RegExp(":"+cU+"([\\W])");if(cP.match(cT)){cP=cP.replace(cT,"([^/]*)$1");cR.push(cU)}}});var cO=cN.match(new RegExp(cP));if(cO){aN(cR,function(cU,cT){cS[cU]=cO[cT+1]});if(cQ){this.$set(cQ,cS)}}return cO?cS:a1}cc("$route",function(cN){var cM={},cO=[],cS=a9,cQ=this,cP=0,cT={routes:cM,onChange:bu(cO,cO.push),when:function(cV,cW){if(ax.isUndefined(cV)){return cM}var cU=cM[cV];if(!cU){cU=cM[cV]={}}if(cW){ax.extend(cU,cW)}cP++;return cU}};function cR(){var cU;cT.current=a1;ax.foreach(cM,function(cV,cW){if(!cU){var cX=cS(cN.hashPath,cW);if(cX){cU=ax.scope(cQ);cT.current=ax.extend({},cV,{scope:cU,params:ax.extend({},cN.hashSearch,cX)})}}});ax.foreach(cO,cQ.$tryEval);if(cU){cU.$become(cT.current.controller)}}this.$watch(function(){return cP+cN.hash},cR);return cT},["$location"],bz);cc("$xhr",function(cN,cM,cP){var cO=this;return function(cT,cQ,cR,cS){if(D(cR)){cS=cR;cR=a1}if(cR&&cH(cR)){cR=cd(cR)}cN.xhr(cT,cQ,cR,function(cV,cU){try{if(b9(cU)&&/^\s*[\[\{]/.exec(cU)&&/[\}\]]\s*$/.exec(cU)){cU=R(cU)}if(cV==200){cS(cV,cU)}else{cM({method:cT,url:cQ,data:cR,callback:cS},{status:cV,body:cU})}}catch(cW){cP.error(cW)}finally{cO.$eval()}})}},["$browser","$xhr.error","$log"]);cc("$xhr.error",function(cM){return function(cO,cN){cM.error("ERROR: XHR: "+cO.url,cO,cN)}},["$log"]);cc("$xhr.bulk",function(cN,cM,cQ){var cR=[],cP=this;function cO(cW,cS,cT,cV){if(D(cT)){cV=cT;cT=a1}var cU;aN(cO.urls,function(cX){if(D(cX.match)?cX.match(cS):cX.match.exec(cS)){cU=cX}});if(cU){if(!cU.requests){cU.requests=[]}cU.requests.push({method:cW,url:cS,data:cT,callback:cV})}else{cN(cW,cS,cT,cV)}}cO.urls={};cO.flush=function(cS){aN(cO.urls,function(cT,cU){var cV=cT.requests;if(cV&&cV.length){cT.requests=[];cT.callbacks=[];cN("POST",cU,{requests:cV},function(cX,cW){aN(cW,function(cY,cZ){try{if(cY.status==200){(cV[cZ].callback||j)(cY.status,cY.response)}else{cM(cV[cZ],cY)}}catch(c0){cQ.error(c0)}});(cS||j)()});cP.$eval()}})};this.$onEval(b7,cO.flush);return cO},["$xhr","$xhr.error","$log"]);cc("$xhr.cache",function(cM){var cP={},cO=this;function cN(cV,cQ,cR,cU,cT){if(D(cR)){cU=cR;cR=a1}if(cV=="GET"){var cS;if(cS=cN.data[cQ]){cU(200,bl(cS.value));if(!cT){return}}if(cS=cP[cQ]){cS.callbacks.push(cU)}else{cP[cQ]={callbacks:[cU]};cN.delegate(cV,cQ,cR,function(cW,cX){if(cW==200){cN.data[cQ]={value:cX}}var cY=cP[cQ].callbacks;delete cP[cQ];aN(cY,function(c0){try{(c0||j)(cW,bl(cX))}catch(cZ){cO.$log.error(cZ)}})})}}else{cN.data={};cN.delegate(cV,cQ,cR,cU)}}cN.data={};cN.delegate=cM;return cN},["$xhr.bulk"]);cc("$resource",function(cM){var cN=new bE(cM);return bu(cN,cN.route)},["$xhr.cache"]);cc("$cookies",function(cN){var cQ=this,cR={},cO={},cM;cN.addPollFn(function(){var cS=cN.cookies();if(cM!=cS){cM=cS;bl(cS,cO);bl(cS,cR);cQ.$eval()}})();this.$onEval(b7,cP);return cR;function cP(){var cT,cU,cS;for(cT in cO){if(br(cR[cT])){cN.cookies(cT,cI)}}for(cT in cR){if(cR[cT]!==cO[cT]){cN.cookies(cT,cR[cT]);cS=true}}if(cS){cS=!cS;cU=cN.cookies();for(cT in cR){if(cR[cT]!==cU[cT]){if(br(cU[cT])){delete cR[cT]}else{cR[cT]=cU[cT]}cS=true}}if(cS){cQ.$eval()}}}},["$browser"],bz);cc("$cookieStore",function(cM){return{get:function(cN){return R(cM[cN])},put:function(cN,cO){cM[cN]=cd(cO)},remove:function(cN){delete cM[cN]}}},["$cookies"]);aa("ng:init",function(cM){return function(cN){this.$tryEval(cM,cN)}});aa("ng:controller",function(cM){this.scope(true);return function(cO){var cN=bH(bL,cM,true)||bH(this,cM,true);if(!cN){throw"Can not find '"+cM+"' controller."}if(!D(cN)){throw"Reference '"+cM+"' is not a class."}this.$become(cN)}});aa("ng:eval",function(cM){return function(cN){this.$onEval(cM,cN)}});aa("ng:bind",function(cM){return function(cO){var cN=j,cP=j;this.$onEval(function(){var cR,cV,cS,cT,cU,cQ=this.hasOwnProperty(bo)?this.$element:cI;this.$element=cO;cV=this.$tryEval(cM,function(cW){cR=cd(cW)});this.$element=cQ;if(cT=(cV instanceof aR)){cV=(cS=cV).html}if(cN===cV&&cP==cR){return}cU=by(cV);if(!cT&&!cU&&cH(cV)){cV=cd(cV)}if(cV!=cN||cR!=cP){cN=cV;cP=cR;bR(cO,a,cR);if(cR){cV=cR}if(cT){cO.html(cS.get())}else{if(cU){cO.html("");cO.append(cV)}else{cO.text(cV===cI?"":cV)}}}},cO)}});var bs={};function cJ(cN){var cM=bs[cN];if(!cM){var cO=[];aN(aU(cN),function(cQ){var cP=cz(cQ);cO.push(cP?function(cS){var cR,cT=this.$tryEval(cP,function(cU){cR=cd(cU)});bR(cS,a,cR);return cR?cR:cT}:function(){return cQ})});bs[cN]=cM=function(cS){var cU=[],cP=this,cQ=this.hasOwnProperty(bo)?cP.$element:cI;cP.$element=cS;for(var cR=0;cR<cO.length;cR++){var cT=cO[cR].call(cP,cS);if(by(cT)){cT=""}else{if(cH(cT)){cT=cd(cT,true)}}cU.push(cT)}cP.$element=cQ;return cU.join("")}}return cM}aa("ng:bind-template",function(cM){var cN=cJ(cM);return function(cP){var cO;this.$onEval(function(){var cQ=cN.call(this,cP);if(cQ!=cO){cP.text(cQ);cO=cQ}},cP)}});var f={disabled:"disabled",readonly:"readOnly",checked:"checked"};aa("ng:bind-attr",function(cM){return function(cP){var cO={};var cN=cP.parent().data("$update");this.$onEval(function(){var cQ=this.$eval(cM);for(var cR in cQ){var cT=cJ(cQ[cR]).call(this,cP),cS=f[al(cR)];if(cO[cR]!==cT){cO[cR]=cT;if(cS){if(cP[cS]=cg(cT)){cP.attr(cS,cT)}else{cP.removeAttr(cR)}(cP.data("$validate")||j)()}else{cP.attr(cR,cT)}this.$postEval(cN)}}},cP)}});A("@ng:non-bindable",j);A("@ng:repeat",function(cO,cM){cM.removeAttr("ng:repeat");cM.replaceWith(this.comment("ng:repeat: "+cO));var cN=this.compile(cM);return function(cP){var cT=cO.match(/^\s*(.+)\s+in\s+(.*)\s*$/),cQ,cW,cR,cV;if(!cT){throw"Expected ng:repeat in form of 'item in collection' but got '"+cO+"'."}cQ=cT[1];cW=cT[2];cT=cQ.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/);if(!cT){throw"'item' in 'item in collection' should be identifier or (key, value) but got '"+keyValue+"'."}cR=cT[3]||cT[1];cV=cT[2];var cU=[],cS=this;this.$onEval(function(){var cZ=0,cY=cU.length,cX,c3=cP,c2=this.$tryEval(cW,cP),c1=a3(c2);for(var c0 in c2){if(!c1||c2.hasOwnProperty(c0)){if(cZ<cY){cX=cU[cZ];cX[cR]=c2[c0];if(cV){cX[cV]=c0}}else{cX=cN(z(cM),bM(cS));cX[cR]=c2[c0];if(cV){cX[cV]=c0}c3.after(cX.$element);cX.$index=cZ;cX.$element.attr("ng:repeat-index",cZ);cX.$init();cU.push(cX)}cX.$eval();c3=cX.$element;cZ++}}while(cU.length>cZ){cU.pop().$element.remove()}},cP)}});aa("ng:click",function(cN,cM){return function(cP){var cO=this;cP.bind("click",function(cQ){cO.$tryEval(cN,cP);cO.$root.$eval();cQ.stopPropagation()})}});aa("ng:submit",function(cN,cM){return function(cP){var cO=this;cP.bind("submit",function(cQ){cO.$tryEval(cN,cP);cO.$root.$eval();cQ.preventDefault()})}});aa("ng:watch",function(cN,cM){return function(cP){var cO=this;T(cN).watch()({addListener:function(cQ,cR){cO.$watch(cQ,function(){return cR(cO)},cP)}})}});function bt(cM){return function(cP,cN){var cO=cN[0].className+" ";return function(cQ){this.$onEval(function(){if(cM(this.$index)){var cR=this.$eval(cP);if(a3(cR)){cR=cR.join(" ")}cQ[0].className=au(cO+cR)}},cQ)}}}aa("ng:class",bt(function(){return true}));aa("ng:class-odd",bt(function(cM){return cM%2===0}));aa("ng:class-even",bt(function(cM){return cM%2===1}));aa("ng:show",function(cN,cM){return function(cO){this.$onEval(function(){cO.css(aG,cg(this.$eval(cN))?"":b)},cO)}});aa("ng:hide",function(cN,cM){return function(cO){this.$onEval(function(){cO.css(aG,cg(this.$eval(cN))?b:"")},cO)}});aa("ng:style",function(cN,cM){return function(cO){var cP=b2(cO);this.$onEval(function(){var cR=this.$eval(cN)||{},cQ,cS={};for(cQ in cR){if(cP[cQ]===cI){cP[cQ]=""}cS[cQ]=cR[cQ]}for(cQ in cP){cS[cQ]=cS[cQ]||cP[cQ]}cO.css(cS)},cO)}});function aU(cN){var cO=[];var cP=0;var cM;while((cM=cN.indexOf("{{",cP))>-1){if(cP<cM){cO.push(cN.substr(cP,cM-cP))}cP=cM;cM=cN.indexOf("}}",cM);cM=cM<0?cN.length:cM+2;cO.push(cN.substr(cP,cM-cP));cP=cM}if(cP!=cN.length){cO.push(cN.substr(cP,cN.length-cP))}return cO.length===0?[cN]:cO}function cz(cM){var cN=cM.replace(/\n/gm," ").match(/^\{\{(.*)\}\}$/);return cN?cN[1]:a1}function cy(cM){return cM.length>1||cz(cM[0])!==a1}ae("{{}}",function(cQ,cP,cM){var cS=aU(cQ),cN=this;if(cy(cS)){if(bV(cM[0])){cM.attr("ng:bind-template",cQ)}else{var cO=cP,cR;aN(aU(cQ),function(cV){var cU=cz(cV);if(cU){cR=cN.element("span");cR.attr("ng:bind",cU)}else{cR=cN.text(cV)}if(ar&&cV.charAt(0)==" "){cR=cb("<span>&nbsp;</span>");var cT=cR.html();cR.text(cV.substr(1));cR.html(cT+cR.html())}cO.after(cR);cO=cR});cP.remove()}}});ae("OPTION",function(cP,cO,cN){if(at(cN)=="OPTION"){var cM=r.createElement("select");cM.insertBefore(cN[0].cloneNode(true),a1);if(!cM.innerHTML.match(/<option(\s.*\s|\s)value\s*=\s*.*>.*<\/\s*option\s*>/gi)){cN.attr("value",cP)}}});var bA="ng:bind-attr";var aC={"ng:src":"src","ng:href":"href"};s("{{}}",function(cP,cN,cO){if(aa(cN)||aa("@"+cN)){return}if(ar&&cN=="src"){cP=decodeURI(cP)}var cQ=aU(cP),cM;if(cy(cQ)){cO.removeAttr(cN);cM=R(cO.attr(bA)||"{}");cM[aC[cN]||cN]=cP;cO.attr(bA,cd(cM))}});function bC(cN,cM){var cO=cM.attr("name");if(!cO){throw"Required field 'name' not found."}return{get:function(){return cN.$eval(cO)},set:function(cP){if(cP!==cI){return cN.$tryEval(cO+"="+cd(cP),cM)}}}}function bd(cP,cO){var cM=bC(cP,cO),cQ=cO.attr("ng:format")||o,cN=l(cQ);if(!cN){throw"Formatter named '"+cQ+"' not found."}return{get:function(){return cN.format(cM.get())},set:function(cR){return cM.set(cN.parse(cR))}}}function d(cM){return T(cM).validator()()}function bS(cX,cQ){var cO=cQ.attr("ng:validate")||o,cN=d(cO),cM=cQ.attr("ng:required"),cY=cQ.attr("ng:format")||o,cW=l(cY),cV,cP,cS,cR,cU=cX.$invalidWidgets||{markValid:j,markInvalid:j};if(!cN){throw"Validator named '"+cO+"' not found."}if(!cW){throw"Formatter named '"+cY+"' not found."}cV=cW.format;cP=cW.parse;if(cM){cX.$watch(cM,function(cZ){cR=cZ;cT()})}else{cR=cM===""}cQ.data("$validate",cT);return{get:function(){if(cS){bR(cQ,k,a1)}try{var cZ=cP(cQ.val());cT();return cZ}catch(c0){cS=c0;bR(cQ,k,c0)}},set:function(c0){var cZ=cQ.val(),c1=cV(c0);if(cZ!=c1){cQ.val(c1||"")}cT()}};function cT(){var c1=au(cQ.val());if(cQ[0].disabled||cQ[0].readOnly){bR(cQ,k,a1);cU.markValid(cQ)}else{var c0,cZ=bW(cX,{$element:cQ});c0=cR&&!c1?"Required":(c1?cN(cZ,c1):a1);bR(cQ,k,c0);cS=c0;if(c0){cU.markInvalid(cQ)}else{cU.markValid(cQ)}}}}function aE(cN,cM){var cP=cM[0],cO=cP.value;return{get:function(){return !!cP.checked},set:function(cQ){cP.checked=cg(cQ)}}}function cF(cN,cM){var cO=cM[0];return{get:function(){return cO.checked?cO.value:a1},set:function(cP){cO.checked=cP==cO.value}}}function cq(cO,cN){var cM=cN[0].options;return{get:function(){var cP=[];aN(cM,function(cQ){if(cQ.selected){cP.push(cQ.value)}});return cP},set:function(cP){var cQ={};aN(cP,function(cR){cQ[cR]=true});aN(cM,function(cR){cR.selected=cQ[cR.value]})}}}function P(){return{get:j,set:j}}var bb=bQ("keyup change",bC,bS,h()),bU=bQ("click",P,P,j),cC={text:bb,textarea:bb,hidden:bb,password:bb,button:bU,submit:bU,reset:bU,image:bU,checkbox:bQ("click",bd,aE,h(false)),radio:bQ("click",bd,cF,ck),"select-one":bQ("change",bd,bS,h(a1)),"select-multiple":bQ("change",bd,cq,h([]))};function h(cM){return function(cO,cN){var cP=cN.get();if(!cP&&cm(cM)){cP=bl(cM)}if(br(cO.get())&&cm(cP)){cO.set(cP)}}}function ck(cP,cM,cQ){var cO=cP.get(),cR=cM.get(),cN=cQ[0];cN.checked=false;cN.name=this.$id+"@"+cN.name;if(br(cO)){cP.set(cO=a1)}if(cO==a1&&cR!==a1){cP.set(cR)}cM.set(cO)}function bQ(cO,cN,cM,cP){return function(cT){var cU=this,cS=cN(cU,cT),cQ=cM(cU,cT),cV=cT.attr("ng:change")||"",cR;cP.call(cU,cS,cQ,cT);this.$eval(cT.attr("ng:init")||"");if(cV||cN!==P){cT.bind(cO,function(cX){cS.set(cQ.get());cR=cS.get();cU.$tryEval(cV,cT);cU.$root.$eval()})}function cW(){cQ.set(cR=cS.get())}cW();cT.data("$update",cW);cU.$watch(cS.get,function(cX){if(cR!==cX){cQ.set(cR=cX)}})}}function Y(cM){this.directives(true);return cC[al(cM[0].type)]||j}A("input",Y);A("textarea",Y);A("button",Y);A("select",function(cM){this.descend(true);return Y.call(this,cM)});A("option",function(){this.descend(true);this.directives(true);return function(cM){this.$postEval(cM.parent().data("$update"))}});A("ng:include",function(cN){var cO=this,cM=cN.attr("src"),cP=cN.attr("scope")||"";if(cN[0]["ng:compiled"]){this.descend(true);this.directives(true)}else{cN[0]["ng:compiled"]=true;return bY(function(cV,cS){var cU=this,cQ;var cW=0;var cT=false;function cR(){cW++}this.$watch(cM,cR);this.$watch(cP,cR);cU.$onEval(function(){if(cQ&&!cT){cT=true;try{cQ.$eval()}finally{cT=false}}});this.$watch(function(){return cW},function(){var cY=this.$eval(cM),cX=this.$eval(cP);if(cY){cV("GET",cY,function(c0,cZ){cS.html(cZ);cQ=cX||bM(cU);cO.compile(cS)(cS,cQ);cQ.$init()})}else{cQ=null;cS.html("")}})},{$inject:["$xhr.cache"]})}});var m=A("ng:switch",function(cQ){var cR=this,cP=cQ.attr("on"),cT=(cQ.attr("using")||"equals"),cM=cT.split(":"),cN=m[cM.shift()],cO=cQ.attr("change")||"",cS=[];if(!cN){throw"Using expression '"+cT+"' unknown."}aS(cQ,function(cV){var cU=cV.attr("ng:switch-when");if(cU){cS.push({when:function(cX,cY){var cW=[cY,cU];aN(cM,function(cZ){cW.push(cZ)});return cN.apply(cX,cW)},change:cO,element:cV,template:cR.compile(cV)})}});aN(cS,function(cU){cU.element.remove()});cQ.html("");return function(cV){var cW=this,cU;this.$watch(cP,function(cX){cV.html("");cU=bM(cW);aN(cS,function(cY){if(cY.when(cU,cX)){var cZ=z(cY.element);cV.append(cZ);cU.$tryEval(cY.change,cV);cY.template(cZ,cU);cU.$init()}})});cW.$onEval(function(){if(cU){cU.$eval()}})}},{equals:function(cN,cM){return cN==cM},route:a9});ax.widget("a",function(){this.descend(true);this.directives(true);return function(cM){if(cM.attr("href")===""){cM.bind("click",function(cN){cN.preventDefault()})}}});var ca;bi("$browser",function(cM){if(!ca){ca=new aJ(bL.location,cb(bL.document),cb(bL.document.getElementsByTagName("head")[0]),M,cM);ca.startPoller(50,function(cN,cO){setTimeout(cN,cO)});ca.bind()}return ca},{inject:["$log"]});bY(ax,{element:cb,compile:aX,scope:bM,copy:bl,extend:bY,equals:p,foreach:aN,injector:bP,noop:j,bind:bu,toJson:cd,fromJson:R,identity:aB,isUndefined:br,isDefined:cm,isString:b9,isFunction:D,isObject:cH,isNumber:aP,isArray:a3});ax.scenario=ax.scenario||{};ax.scenario.output=ax.scenario.output||function(cM,cN){ax.scenario.output[cM]=cN};ax.scenario.dsl=ax.scenario.dsl||function(cM,cN){ax.scenario.dsl[cM]=function(){function cO(cU,cS){var cQ=cU.apply(this,cS);if(ax.isFunction(cQ)||cQ instanceof ax.scenario.Future){return cQ}var cR=this;var cT=ax.extend({},cQ);ax.foreach(cT,function(cW,cV){if(ax.isFunction(cW)){cT[cV]=function(){return cO.call(cR,cW,arguments)}}else{cT[cV]=cW}});return cT}var cP=cN.apply(this,arguments);return function(){return cO.call(this,cP,arguments)}}};ax.scenario.matcher=ax.scenario.matcher||function(cM,cN){ax.scenario.matcher[cM]=function(cP){var cQ="expect "+this.future.name+" ";if(this.inverse){cQ+="not "}var cO=this;this.addFuture(cQ+cM+" "+ax.toJson(cP),function(cR){var cS;cO.actual=cO.future.value;if((cO.inverse&&cN.call(cO,cP))||(!cO.inverse&&!cN.call(cO,cP))){cS="expected "+ax.toJson(cP)+" but was "+ax.toJson(cO.actual)}cR(cS)})}};function i(cQ,cP){var cM=bZ(r.body);var cN=[];if(cP.scenario_output){cN=cP.scenario_output.split(",")}ax.foreach(ax.scenario.output,function(cU,cS){if(!cN.length||cE(cN,cS)!=-1){var cT=cM.append("<div></div>").find("div:last");cT.attr("id",cS);cU.call({},cT,cQ)}});var cR=cM.append('<div id="application"></div>').find("#application");var cO=new ax.scenario.Application(cR);cQ.on("RunnerEnd",function(){cR.css("display","none");cR.find("iframe").attr("src","about:blank")});cQ.on("RunnerError",function(cS){if(bL.console){console.log(W(cS))}else{alert(cS)}});cQ.run(cO)}function X(cQ,cP,cN){var cO=0;function cM(cS,cR){if(cR&&cR>cO){cO=cR}if(cS||cO>=cQ.length){cN(cS)}else{try{cP(cQ[cO++],cM)}catch(cT){cN(cT)}}}cM()}function W(cN,cO){cO=cO||5;var cP=cN.toString();if(cN.stack){var cM=cN.stack.split("\n");if(cM[0].indexOf(cP)===-1){cO++;cM.unshift(cN.message)}cP=cM.slice(0,cO).join("\n")}return cP}function x(cN){var cM=new Error();return function(){var cO=(cM.stack||"").split("\n")[cN];if(cO){if(cO.indexOf("@")!==-1){cO=cO.substring(cO.indexOf("@")+1)}else{cO=cO.substring(cO.indexOf("(")+1).replace(")","")}}return cO||""}}function c(cM,cN){if(cM&&!cM.nodeName){cM=cM[0]}if(!cM){return}if(!cN){cN={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"}[cM.type]||"click"}if(al(at(cM))=="option"){cM.parentNode.value=cM.value;cM=cM.parentNode;cN="change"}if(ar){switch(cM.type){case"radio":case"checkbox":cM.checked=!cM.checked;break}cM.fireEvent("on"+cN);if(al(cM.type)=="submit"){while(cM){if(al(cM.nodeName)=="form"){cM.fireEvent("onsubmit");break}cM=cM.parentNode}}}else{var cO=r.createEvent("MouseEvents");cO.initMouseEvent(cN,true,true,bL,0,0,0,0,0,false,false,false,false,0,cM);cM.dispatchEvent(cO)}}(function(cN){var cM=cN.trigger;cN.trigger=function(cO){if(/(click|change|keyup)/.test(cO)){return this.each(function(cP,cQ){c(cQ,cO)})}return cM.apply(this,arguments)}})(bZ.fn);ax.scenario.Application=function(cM){this.context=cM;cM.append('<h2>Current URL: <a href="about:blank">None</a></h2><div id="test-frames"></div>')};ax.scenario.Application.prototype.getFrame_=function(){return this.context.find("#test-frames iframe:last")};ax.scenario.Application.prototype.getWindow_=function(){var cM=this.getFrame_().attr("contentWindow");if(!cM){throw"Frame window is not accessible."}return cM};ax.scenario.Application.prototype.navigateTo=function(cO,cN){var cM=this;var cP=this.getFrame_();if(cO.charAt(0)==="#"){cO=cP.attr("src").split("#")[0]+cO;cP.attr("src",cO);this.executeAction(cN)}else{cP.css("display","none").attr("src","about:blank");this.context.find("#test-frames").append("<iframe>");cP=this.getFrame_();cP.load(function(){cM.executeAction(cN);cP.unbind()}).attr("src",cO)}this.context.find("> h2 a").attr("href",cO).text(cO)};ax.scenario.Application.prototype.executeAction=function(cO){var cN=this;var cP=this.getWindow_();if(!cP.angular){return cO.call(this,cP,bZ(cP.document))}var cM=cP.angular.service.$browser();cM.poll();cM.notifyWhenNoOutstandingRequests(function(){cO.call(cN,cP,bZ(cP.document))})};ax.scenario.Describe=function(cN,cP){this.only=cP&&cP.only;this.beforeEachFns=[];this.afterEachFns=[];this.its=[];this.children=[];this.name=cN;this.parent=cP;this.id=ax.scenario.Describe.id++;var cM=this.beforeEachFns;this.setupBefore=function(){if(cP){cP.setupBefore.call(this)}ax.foreach(cM,function(cQ){cQ.call(this)},this)};var cO=this.afterEachFns;this.setupAfter=function(){ax.foreach(cO,function(cQ){cQ.call(this)},this);if(cP){cP.setupAfter.call(this)}}};ax.scenario.Describe.id=0;ax.scenario.Describe.prototype.beforeEach=function(cM){this.beforeEachFns.push(cM)};ax.scenario.Describe.prototype.afterEach=function(cM){this.afterEachFns.push(cM)};ax.scenario.Describe.prototype.describe=function(cN,cM){var cO=new ax.scenario.Describe(cN,this);this.children.push(cO);cM.call(cO)};ax.scenario.Describe.prototype.ddescribe=function(cN,cM){var cO=new ax.scenario.Describe(cN,this);cO.only=true;this.children.push(cO);cM.call(cO)};ax.scenario.Describe.prototype.xdescribe=ax.noop;ax.scenario.Describe.prototype.it=function(cN,cM){this.its.push({definition:this,only:this.only,name:cN,before:this.setupBefore,body:cM,after:this.setupAfter})};ax.scenario.Describe.prototype.iit=function(cN,cM){this.it.apply(this,arguments);this.its[this.its.length-1].only=true};ax.scenario.Describe.prototype.xit=ax.noop;ax.scenario.Describe.prototype.getSpecs=function(){var cN=arguments[0]||[];ax.foreach(this.children,function(cO){cO.getSpecs(cN)});ax.foreach(this.its,function(cO){cN.push(cO)});var cM=[];ax.foreach(cN,function(cO){if(cO.only){cM.push(cO)}});return(cM.length&&cM)||cN};ax.scenario.Future=function(cN,cO,cM){this.name=cN;this.behavior=cO;this.fulfilled=false;this.value=undefined;this.parser=ax.identity;this.line=cM||function(){return""}};ax.scenario.Future.prototype.execute=function(cN){var cM=this;this.behavior(function(cP,cO){cM.fulfilled=true;if(cO){try{cO=cM.parser(cO)}catch(cQ){cP=cQ}}cM.value=cP||cO;cN(cP,cO)})};ax.scenario.Future.prototype.parsedWith=function(cM){this.parser=cM;return this};ax.scenario.Future.prototype.fromJson=function(){return this.parsedWith(ax.fromJson)};ax.scenario.Future.prototype.toJson=function(){return this.parsedWith(ax.toJson)};ax.scenario.ObjectModel=function(cO){var cN=this;this.specMap={};this.value={name:"",children:{}};cO.on("SpecBegin",function(cP){var cQ=cN.value;ax.foreach(cN.getDefinitionPath(cP),function(cR){if(!cQ.children[cR.name]){cQ.children[cR.name]={id:cR.id,name:cR.name,children:{},specs:{}}}cQ=cQ.children[cR.name]});cN.specMap[cP.id]=cQ.specs[cP.name]=new ax.scenario.ObjectModel.Spec(cP.id,cP.name)});cO.on("SpecError",function(cP,cQ){var cR=cN.getSpec(cP.id);cR.status="error";cR.error=cQ});cO.on("SpecEnd",function(cP){var cQ=cN.getSpec(cP.id);cM(cQ)});cO.on("StepBegin",function(cP,cR){var cQ=cN.getSpec(cP.id);cQ.steps.push(new ax.scenario.ObjectModel.Step(cR.name))});cO.on("StepEnd",function(cP,cR){var cQ=cN.getSpec(cP.id);if(cQ.getLastStep().name!==cR.name){throw"Events fired in the wrong order. Step names don' match."}cM(cQ.getLastStep())});cO.on("StepFailure",function(cP,cT,cQ){var cR=cN.getSpec(cP.id);var cS=cR.getLastStep();cS.error=cQ;if(!cR.status){cR.status=cS.status="failure"}});cO.on("StepError",function(cP,cT,cQ){var cR=cN.getSpec(cP.id);var cS=cR.getLastStep();cR.status="error";cS.status="error";cS.error=cQ});function cM(cP){cP.endTime=new Date().getTime();cP.duration=cP.endTime-cP.startTime;cP.status=cP.status||"success"}};ax.scenario.ObjectModel.prototype.getDefinitionPath=function(cM){var cO=[];var cN=cM.definition;while(cN&&cN.name){cO.unshift(cN);cN=cN.parent}return cO};ax.scenario.ObjectModel.prototype.getSpec=function(cM){return this.specMap[cM]};ax.scenario.ObjectModel.Spec=function(cN,cM){this.id=cN;this.name=cM;this.startTime=new Date().getTime();this.steps=[]};ax.scenario.ObjectModel.Spec.prototype.addStep=function(cM){var cN=new ax.scenario.ObjectModel.Step(cM);this.steps.push(cN);return cN};ax.scenario.ObjectModel.Spec.prototype.getLastStep=function(){return this.steps[this.steps.length-1]};ax.scenario.ObjectModel.Step=function(cM){this.name=cM;this.startTime=new Date().getTime()};ax.scenario.Describe=function(cN,cP){this.only=cP&&cP.only;this.beforeEachFns=[];this.afterEachFns=[];this.its=[];this.children=[];this.name=cN;this.parent=cP;this.id=ax.scenario.Describe.id++;var cM=this.beforeEachFns;this.setupBefore=function(){if(cP){cP.setupBefore.call(this)}ax.foreach(cM,function(cQ){cQ.call(this)},this)};var cO=this.afterEachFns;this.setupAfter=function(){ax.foreach(cO,function(cQ){cQ.call(this)},this);if(cP){cP.setupAfter.call(this)}}};ax.scenario.Describe.id=0;ax.scenario.Describe.prototype.beforeEach=function(cM){this.beforeEachFns.push(cM)};ax.scenario.Describe.prototype.afterEach=function(cM){this.afterEachFns.push(cM)};ax.scenario.Describe.prototype.describe=function(cN,cM){var cO=new ax.scenario.Describe(cN,this);this.children.push(cO);cM.call(cO)};ax.scenario.Describe.prototype.ddescribe=function(cN,cM){var cO=new ax.scenario.Describe(cN,this);cO.only=true;this.children.push(cO);cM.call(cO)};ax.scenario.Describe.prototype.xdescribe=ax.noop;ax.scenario.Describe.prototype.it=function(cN,cM){this.its.push({definition:this,only:this.only,name:cN,before:this.setupBefore,body:cM,after:this.setupAfter})};ax.scenario.Describe.prototype.iit=function(cN,cM){this.it.apply(this,arguments);this.its[this.its.length-1].only=true};ax.scenario.Describe.prototype.xit=ax.noop;ax.scenario.Describe.prototype.getSpecs=function(){var cN=arguments[0]||[];ax.foreach(this.children,function(cO){cO.getSpecs(cN)});ax.foreach(this.its,function(cO){cN.push(cO)});var cM=[];ax.foreach(cN,function(cO){if(cO.only){cM.push(cO)}});return(cM.length&&cM)||cN};ax.scenario.Runner=function(cM){this.listeners=[];this.$window=cM;this.rootDescribe=new ax.scenario.Describe();this.currentDescribe=this.rootDescribe;this.api={it:this.it,iit:this.iit,xit:ax.noop,describe:this.describe,ddescribe:this.ddescribe,xdescribe:ax.noop,beforeEach:this.beforeEach,afterEach:this.afterEach};ax.foreach(this.api,ax.bind(this,function(cO,cN){this.$window[cN]=ax.bind(this,cO)}))};ax.scenario.Runner.prototype.emit=function(cN){var cM=this;var cO=Array.prototype.slice.call(arguments,1);cN=cN.toLowerCase();if(!this.listeners[cN]){return}ax.foreach(this.listeners[cN],function(cP){cP.apply(cM,cO)})};ax.scenario.Runner.prototype.on=function(cM,cN){cM=cM.toLowerCase();this.listeners[cM]=this.listeners[cM]||[];this.listeners[cM].push(cN)};ax.scenario.Runner.prototype.describe=function(cO,cM){var cN=this;this.currentDescribe.describe(cO,function(){var cP=cN.currentDescribe;cN.currentDescribe=this;try{cM.call(this)}finally{cN.currentDescribe=cP}})};ax.scenario.Runner.prototype.ddescribe=function(cO,cM){var cN=this;this.currentDescribe.ddescribe(cO,function(){var cP=cN.currentDescribe;cN.currentDescribe=this;try{cM.call(this)}finally{cN.currentDescribe=cP}})};ax.scenario.Runner.prototype.it=function(cN,cM){this.currentDescribe.it(cN,cM)};ax.scenario.Runner.prototype.iit=function(cN,cM){this.currentDescribe.iit(cN,cM)};ax.scenario.Runner.prototype.beforeEach=function(cM){this.currentDescribe.beforeEach(cM)};ax.scenario.Runner.prototype.afterEach=function(cM){this.currentDescribe.afterEach(cM)};ax.scenario.Runner.prototype.createSpecRunner_=function(cM){return cM.$new(ax.scenario.SpecRunner)};ax.scenario.Runner.prototype.run=function(cN){var cM=this;var cO=ax.scope(this);cO.application=cN;this.emit("RunnerBegin");X(this.rootDescribe.getSpecs(),function(cP,cS){var cQ={};var cR=cM.createSpecRunner_(cO);ax.foreach(ax.scenario.dsl,function(cU,cT){cQ[cT]=cU.call(cO)});ax.foreach(ax.scenario.dsl,function(cU,cT){cM.$window[cT]=function(){var cV=x(3);var cW=ax.scope(cR);cW.dsl={};ax.foreach(cQ,function(cY,cX){cW.dsl[cX]=function(){return cQ[cX].apply(cW,arguments)}});cW.addFuture=function(){Array.prototype.push.call(arguments,cV);return ax.scenario.SpecRunner.prototype.addFuture.apply(cW,arguments)};cW.addFutureAction=function(){Array.prototype.push.call(arguments,cV);return ax.scenario.SpecRunner.prototype.addFutureAction.apply(cW,arguments)};return cW.dsl[cT].apply(cW,arguments)}});cR.run(cP,cS)},function(cP){if(cP){cM.emit("RunnerError",cP)}cM.emit("RunnerEnd")})};ax.scenario.SpecRunner=function(){this.futures=[];this.afterIndex=0};ax.scenario.SpecRunner.prototype.run=function(cN,cQ){var cM=this;var cO=0;this.spec=cN;this.emit("SpecBegin",cN);try{cN.before.call(this);cN.body.call(this);this.afterIndex=this.futures.length;cN.after.call(this)}catch(cP){this.emit("SpecError",cN,cP);this.emit("SpecEnd",cN);cQ();return}var cR=function(cT,cS){if(cM.error){return cS()}cM.error=true;cS(null,cM.afterIndex)};X(this.futures,function(cS,cT){cM.step=cS;cM.emit("StepBegin",cN,cS);try{cS.execute(function(cV){if(cV){cM.emit("StepFailure",cN,cS,cV);cM.emit("StepEnd",cN,cS);return cR(cV,cT)}cM.emit("StepEnd",cN,cS);if((cO++)%10===0){cM.$window.setTimeout(function(){cT()},0)}else{cT()}})}catch(cU){cM.emit("StepError",cN,cS,cU);cM.emit("StepEnd",cN,cS);cR(cU,cT)}},function(cS){if(cS){cM.emit("SpecError",cN,cS)}cM.emit("SpecEnd",cN);cM.$window.setTimeout(function(){cQ()},0)})};ax.scenario.SpecRunner.prototype.addFuture=function(cO,cP,cN){var cM=new ax.scenario.Future(cO,ax.bind(this,cP),cN);this.futures.push(cM);return cM};ax.scenario.SpecRunner.prototype.addFutureAction=function(cO,cP,cM){var cN=this;return this.addFuture(cO,function(cQ){this.application.executeAction(function(cT,cS){cS.elements=function(cV){var cW=Array.prototype.slice.call(arguments,1);if(cN.selector){cV=cN.selector+" "+(cV||"")}ax.foreach(cW,function(cY,cX){cV=cV.replace("$"+(cX+1),cY)});var cU=cS.find(cV);if(!cU.length){throw {type:"selector",message:"Selector "+cV+" did not match any elements."}}return cU};try{cP.call(cN,cT,cS,cQ)}catch(cR){if(cR.type&&cR.type==="selector"){cQ(cR.message)}else{throw cR}}})},cM)};ax.scenario.dsl("wait",function(){return function(){return this.addFuture("waiting for you to resume",function(cM){this.emit("InteractiveWait",this.spec,this.step);this.$window.resume=function(){cM()}})}});ax.scenario.dsl("pause",function(){return function(cM){return this.addFuture("pause for "+cM+" seconds",function(cN){this.$window.setTimeout(function(){cN(null,cM*1000)},cM*1000)})}});ax.scenario.dsl("expect",function(){var cM=ax.extend({},ax.scenario.matcher);cM.not=function(){this.inverse=true;return cM};return function(cN){this.future=cN;return cM}});ax.scenario.dsl("navigateTo",function(){return function(cN,cO){var cM=this.application;return this.addFuture("navigate to "+cN,function(cP){if(cO){cN=cO.call(this,cN)}cM.navigateTo(cN,function(){cP(null,cN)})})}});ax.scenario.dsl("using",function(){return function(cM){this.selector=(this.selector||"")+" "+cM;return this.dsl}});ax.scenario.dsl("binding",function(){return function(cM){return this.addFutureAction("select binding '"+cM+"'",function(cR,cQ,cN){var cO;try{cO=cQ.elements('[ng\\:bind-template*="{{$1}}"]',cM)}catch(cP){if(cP.type!=="selector"){throw cP}cO=cQ.elements('[ng\\:bind="$1"]',cM)}cN(null,cO.text())})}});ax.scenario.dsl("input",function(){var cM={};cM.enter=function(cN){return this.addFutureAction("input '"+this.name+"' enter '"+cN+"'",function(cR,cQ,cO){var cP=cQ.elements('input[name="$1"]',this.name);cP.val(cN);cP.trigger("change");cO()})};cM.check=function(){return this.addFutureAction("checkbox '"+this.name+"' toggle",function(cQ,cP,cN){var cO=cP.elements('input:checkbox[name="$1"]',this.name);cO.trigger("click");cN()})};cM.select=function(cN){return this.addFutureAction("radio button '"+this.name+"' toggle '"+cN+"'",function(cR,cQ,cO){var cP=cQ.elements('input:radio[name$="@$1"][value="$2"]',this.name,cN);cP.trigger("click");cO()})};return function(cN){this.name=cN;return cM}});ax.scenario.dsl("repeater",function(){var cM={};cM.count=function(){return this.addFutureAction("repeater "+this.selector+" count",function(cQ,cP,cN){try{cN(null,cP.elements().length)}catch(cO){cN(null,0)}})};cM.column=function(cN){return this.addFutureAction("repeater "+this.selector+" column "+cN,function(cR,cQ,cO){var cP=[];cQ.elements().each(function(){bZ(this).find(":visible").each(function(){var cS=bZ(this);if(cS.attr("ng:bind")===cN){cP.push(cS.text())}})});cO(null,cP)})};cM.row=function(cN){return this.addFutureAction("repeater "+this.selector+" row "+cN,function(cS,cR,cO){var cP=[];var cQ=cR.elements().slice(cN,cN+1);if(!cQ.length){return cO("row "+cN+" out of bounds")}bZ(cQ[0]).find(":visible").each(function(){var cT=bZ(this);if(cT.attr("ng:bind")){cP.push(cT.text())}});cO(null,cP)})};return function(cN){this.dsl.using(cN);return cM}});ax.scenario.dsl("select",function(){var cM={};cM.option=function(cN){return this.addFutureAction("select "+this.name+" option "+cN,function(cR,cQ,cP){var cO=cQ.elements('select[name="$1"]',this.name);cO.val(cN);cO.trigger("change");cP()})};cM.options=function(){var cN=arguments;return this.addFutureAction("select "+this.name+" options "+cN,function(cR,cQ,cP){var cO=cQ.elements('select[multiple][name="$1"]',this.name);cO.val(cN);cO.trigger("change");cP()})};return function(cN){this.name=cN;return cM}});ax.scenario.dsl("element",function(){var cM={};cM.count=function(){return this.addFutureAction("element "+this.selector+" count",function(cQ,cP,cN){try{cN(null,cP.elements().length)}catch(cO){cN(null,0)}})};cM.click=function(){return this.addFutureAction("element "+this.selector+" click",function(cR,cQ,cN){var cP=cQ.elements();var cO=cP.attr("href");cP.trigger("click");if(cO&&cP[0].nodeName.toUpperCase()==="A"){this.application.navigateTo(cO,function(){cN()})}else{cN()}})};cM.attr=function(cN,cP){var cO="element "+this.selector+" get attribute "+cN;if(cP){cO="element "+this.selector+" set attribute "+cN+" to "+cP}return this.addFutureAction(cO,function(cS,cR,cQ){cQ(null,cR.elements().attr(cN,cP))})};cM.val=function(cO){var cN="element "+this.selector+" value";if(cO){cN="element "+this.selector+" set value to "+cO}return this.addFutureAction(cN,function(cR,cQ,cP){cP(null,cQ.elements().val(cO))})};cM.query=function(cN){return this.addFutureAction("element "+this.selector+" custom query",function(cQ,cP,cO){cN.call(this,cP.elements(),cO)})};return function(cN){this.dsl.using(cN);return cM}});ax.scenario.matcher("toEqual",function(cM){return ax.equals(this.actual,cM)});ax.scenario.matcher("toBe",function(cM){return this.actual===cM});ax.scenario.matcher("toBeDefined",function(){return ax.isDefined(this.actual)});ax.scenario.matcher("toBeTruthy",function(){return this.actual});ax.scenario.matcher("toBeFalsy",function(){return !this.actual});ax.scenario.matcher("toMatch",function(cM){return new RegExp(cM).test(this.actual)});ax.scenario.matcher("toBeNull",function(){return this.actual===null});ax.scenario.matcher("toContain",function(cM){return u(this.actual,cM)});ax.scenario.matcher("toBeLessThan",function(cM){return this.actual<cM});ax.scenario.matcher("toBeGreaterThan",function(cM){return this.actual>cM});ax.scenario.output("html",function(cP,cR){var cO=new ax.scenario.ObjectModel(cR);cP.append('<div id="header"> <h1><span class="angular">&lt;angular/&gt;</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>');cR.on("InteractiveWait",function(cS,cT){var cU=cO.getSpec(cS.id).getLastStep().ui;cU.find(".test-title").html('waiting for you to <a href="javascript:resume()">resume</a>.')});cR.on("SpecBegin",function(cS){var cT=cQ(cS);cT.find("> .tests").append('<li class="status-pending test-it"></li>');cT=cT.find("> .tests li:last");cT.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>');cT.find("> .test-info .test-name").text(cS.name);cT.find("> .test-info").click(function(){var cV=cT.find("> .scrollpane");var cW=cV.find("> .test-actions");var cU=cP.find("> .test-info .test-name");if(cW.find(":visible").length){cW.hide();cU.removeClass("open").addClass("closed")}else{cW.show();cV.attr("scrollTop",cV.attr("scrollHeight"));cU.removeClass("closed").addClass("open")}});cO.getSpec(cS.id).ui=cT});cR.on("SpecError",function(cS,cT){var cU=cO.getSpec(cS.id).ui;cU.append("<pre></pre>");cU.find("> pre").text(W(cT))});cR.on("SpecEnd",function(cS){cS=cO.getSpec(cS.id);cS.ui.removeClass("status-pending");cS.ui.addClass("status-"+cS.status);cS.ui.find("> .test-info .timer-result").text(cS.duration+"ms");if(cS.status==="success"){cS.ui.find("> .test-info .test-name").addClass("closed");cS.ui.find("> .scrollpane .test-actions").hide()}cN(cS.status)});cR.on("StepBegin",function(cS,cU){cS=cO.getSpec(cS.id);cU=cS.getLastStep();cS.ui.find("> .scrollpane .test-actions").append('<li class="status-pending"></li>');cU.ui=cS.ui.find("> .scrollpane .test-actions li:last");cU.ui.append('<div class="timer-result"></div><div class="test-title"></div>');cU.ui.find("> .test-title").text(cU.name);var cT=cU.ui.parents(".scrollpane");cT.attr("scrollTop",cT.attr("scrollHeight"))});cR.on("StepFailure",function(cS,cU,cT){var cV=cO.getSpec(cS.id).getLastStep().ui;cM(cV,cU.line,cT)});cR.on("StepError",function(cS,cU,cT){var cV=cO.getSpec(cS.id).getLastStep().ui;cM(cV,cU.line,cT)});cR.on("StepEnd",function(cS,cU){cS=cO.getSpec(cS.id);cU=cS.getLastStep();cU.ui.find(".timer-result").text(cU.duration+"ms");cU.ui.removeClass("status-pending");cU.ui.addClass("status-"+cU.status);var cT=cS.ui.find("> .scrollpane");cT.attr("scrollTop",cT.attr("scrollHeight"))});function cQ(cS){var cT=cP.find("#specs");ax.foreach(cO.getDefinitionPath(cS),function(cU){var cV="describe-"+cU.id;if(!cP.find("#"+cV).length){cT.find("> .test-children").append('<div class="test-describe" id="'+cV+'"> <h2></h2> <div class="test-children"></div> <ul class="tests"></ul></div>');cP.find("#"+cV).find("> h2").text("describe: "+cU.name)}cT=cP.find("#"+cV)});return cP.find("#describe-"+cS.definition.id)}function cN(cS){var cT=cP.find("#status-legend .status-"+cS);var cV=cT.text().split(" ");var cU=(cV[0]*1)+1;cT.text(cU+" "+cV[1])}function cM(cU,cS,cT){cU.find(".test-title").append("<pre></pre>");var cV=bZ.trim(cS()+"\n\n"+W(cT));cU.find(".test-title pre:last").text(cV)}});ax.scenario.output("json",function(cN,cO){var cM=new ax.scenario.ObjectModel(cO);cO.on("RunnerEnd",function(){cN.text(ax.toJson(cM.value))})});ax.scenario.output("xml",function(cN,cP){var cM=new ax.scenario.ObjectModel(cP);var cQ=function(cR){return new cN.init(cR)};cP.on("RunnerEnd",function(){var cR=cQ("<scenario></scenario>");cN.append(cR);cO(cR,cM.value)});function cO(cT,cR){ax.foreach(cR.children,function(cV){var cU=cQ("<describe></describe>");cU.attr("id",cV.id);cU.attr("name",cV.name);cT.append(cU);cO(cU,cV)});var cS=cQ("<its></its>");cT.append(cS);ax.foreach(cR.specs,function(cU){var cV=cQ("<it></it>");cV.attr("id",cU.id);cV.attr("name",cU.name);cV.attr("duration",cU.duration);cV.attr("status",cU.status);cS.append(cV);ax.foreach(cU.steps,function(cY){var cX=cQ("<step></step>");cX.attr("name",cY.name);cX.attr("duration",cY.duration);cX.attr("status",cY.status);cV.append(cX);if(cY.error){var cW=cQ("<error></error");cX.append(cW);cW.text(W(cX.error))}})})}});ax.scenario.output("object",function(cM,cN){cN.$window.$result=new ax.scenario.ObjectModel(cN).value});var aj=new ax.scenario.Runner(bL);bL.onload=function(){try{if(a8){a8()}}catch(cM){}i(aj,bw(r))}})(window,document,window.onload);document.write('<style type="text/css">@charset "UTF-8";\n\n.ng-format-negative {\n color: red;\n}\n\n.ng-exception {\n border: 2px solid #FF0000;\n font-family: "Courier New", Courier, monospace;\n font-size: smaller;\n}\n\n.ng-validation-error {\n border: 2px solid #FF0000;\n}\n\n\n/*****************\n * TIP\n *****************/\n#ng-callout {\n margin: 0;\n padding: 0;\n border: 0;\n outline: 0;\n font-size: 13px;\n font-weight: normal;\n font-family: Verdana, Arial, Helvetica, sans-serif;\n vertical-align: baseline;\n background: transparent;\n text-decoration: none;\n}\n\n#ng-callout .ng-arrow-left{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrSLoc/AG8FeUUIN+sGebWAnbKSJodqqlsOxJtqYooU9vvk+vcJIcTkg+QAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n left:-12px;\n height:23px;\n width:10px;\n top:-3px;\n}\n\n#ng-callout .ng-arrow-right{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrCLTcoM29yN6k9socs91e5X3EyJloipYrO4ohTMqA0Fn2XVNswJe+H+SXAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n height:23px;\n width:11px;\n top:-2px;\n}\n\n#ng-callout {\n position: absolute;\n z-index:100;\n border: 2px solid #CCCCCC;\n background-color: #fff;\n}\n\n#ng-callout .ng-content{\n padding:10px 10px 10px 10px;\n color:#333333;\n}\n\n#ng-callout .ng-title{\n background-color: #CCCCCC;\n text-align: left;\n padding-left: 8px;\n padding-bottom: 5px;\n padding-top: 2px;\n font-weight:bold;\n}\n\n\n/*****************\n * indicators\n *****************/\n.ng-input-indicator-wait {\n background-image: url("data:image/png;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1BAYzlyILczULC2UhACH5BAkKAAAALAAAAAAQABAAAAV2ICACAmlAZTmOREEIyUEQjLKKxPHADhEvqxlgcGgkGI1DYSVAIAWMx+lwSKkICJ0QsHi9RgKBwnVTiRQQgwF4I4UFDQQEwi6/3YSGWRRmjhEETAJfIgMFCnAKM0KDV4EEEAQLiF18TAYNXDaSe3x6mjidN1s3IQAh+QQJCgAAACwAAAAAEAAQAAAFeCAgAgLZDGU5jgRECEUiCI+yioSDwDJyLKsXoHFQxBSHAoAAFBhqtMJg8DgQBgfrEsJAEAg4YhZIEiwgKtHiMBgtpg3wbUZXGO7kOb1MUKRFMysCChAoggJCIg0GC2aNe4gqQldfL4l/Ag1AXySJgn5LcoE3QXI3IQAh+QQJCgAAACwAAAAAEAAQAAAFdiAgAgLZNGU5joQhCEjxIssqEo8bC9BRjy9Ag7GILQ4QEoE0gBAEBcOpcBA0DoxSK/e8LRIHn+i1cK0IyKdg0VAoljYIg+GgnRrwVS/8IAkICyosBIQpBAMoKy9dImxPhS+GKkFrkX+TigtLlIyKXUF+NjagNiEAIfkECQoAAAAsAAAAABAAEAAABWwgIAICaRhlOY4EIgjH8R7LKhKHGwsMvb4AAy3WODBIBBKCsYA9TjuhDNDKEVSERezQEL0WrhXucRUQGuik7bFlngzqVW9LMl9XWvLdjFaJtDFqZ1cEZUB0dUgvL3dgP4WJZn4jkomWNpSTIyEAIfkECQoAAAAsAAAAABAAEAAABX4gIAICuSxlOY6CIgiD8RrEKgqGOwxwUrMlAoSwIzAGpJpgoSDAGifDY5kopBYDlEpAQBwevxfBtRIUGi8xwWkDNBCIwmC9Vq0aiQQDQuK+VgQPDXV9hCJjBwcFYU5pLwwHXQcMKSmNLQcIAExlbH8JBwttaX0ABAcNbWVbKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICSRBlOY7CIghN8zbEKsKoIjdFzZaEgUBHKChMJtRwcWpAWoWnifm6ESAMhO8lQK0EEAV3rFopIBCEcGwDKAqPh4HUrY4ICHH1dSoTFgcHUiZjBhAJB2AHDykpKAwHAwdzf19KkASIPl9cDgcnDkdtNwiMJCshACH5BAkKAAAALAAAAAAQABAAAAV3ICACAkkQZTmOAiosiyAoxCq+KPxCNVsSMRgBsiClWrLTSWFoIQZHl6pleBh6suxKMIhlvzbAwkBWfFWrBQTxNLq2RG2yhSUkDs2b63AYDAoJXAcFRwADeAkJDX0AQCsEfAQMDAIPBz0rCgcxky0JRWE1AmwpKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICKZzkqJ4nQZxLqZKv4NqNLKK2/Q4Ek4lFXChsg5ypJjs1II3gEDUSRInEGYAw6B6zM4JhrDAtEosVkLUtHA7RHaHAGJQEjsODcEg0FBAFVgkQJQ1pAwcDDw8KcFtSInwJAowCCA6RIwqZAgkPNgVpWndjdyohACH5BAkKAAAALAAAAAAQABAAAAV5ICACAimc5KieLEuUKvm2xAKLqDCfC2GaO9eL0LABWTiBYmA06W6kHgvCqEJiAIJiu3gcvgUsscHUERm+kaCxyxa+zRPk0SgJEgfIvbAdIAQLCAYlCj4DBw0IBQsMCjIqBAcPAooCBg9pKgsJLwUFOhCZKyQDA3YqIQAh+QQJCgAAACwAAAAAEAAQAAAFdSAgAgIpnOSonmxbqiThCrJKEHFbo8JxDDOZYFFb+A41E4H4OhkOipXwBElYITDAckFEOBgMQ3arkMkUBdxIUGZpEb7kaQBRlASPg0FQQHAbEEMGDSVEAA1QBhAED1E0NgwFAooCDWljaQIQCE5qMHcNhCkjIQAh+QQJCgAAACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA==");\n background-position: right;\n background-repeat: no-repeat;\n}\n</style>');document.write("<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#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>");
examples/src/components/Multiselect.js
glowka/react-select
import React from 'react'; import Select from 'react-select'; const FLAVOURS = [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, { label: 'Caramel', value: 'caramel' }, { label: 'Cookies and Cream', value: 'cookiescream' }, { label: 'Peppermint', value: 'peppermint' }, ]; const WHY_WOULD_YOU = [ { label: 'Chocolate (are you crazy?)', value: 'chocolate', disabled: true }, ].concat(FLAVOURS.slice(1)); var MultiSelectField = React.createClass({ displayName: 'MultiSelectField', propTypes: { label: React.PropTypes.string, }, getInitialState () { return { disabled: false, crazy: false, options: FLAVOURS, value: [], }; }, handleSelectChange (value) { console.log('You\'ve selected:', value); this.setState({ value }); }, toggleDisabled (e) { this.setState({ disabled: e.target.checked }); }, toggleChocolate (e) { let crazy = e.target.checked; this.setState({ crazy: crazy, options: crazy ? WHY_WOULD_YOU : FLAVOURS, }); }, render () { return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select multi simpleValue disabled={this.state.disabled} value={this.state.value} placeholder="Select your favourite(s)" options={this.state.options} onChange={this.handleSelectChange} /> <div className="checkbox-list"> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.disabled} onChange={this.toggleDisabled} /> <span className="checkbox-label">Disable the control</span> </label> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.crazy} onChange={this.toggleChocolate} /> <span className="checkbox-label">I don't like Chocolate (disabled the option)</span> </label> </div> </div> ); } }); module.exports = MultiSelectField;
test/fixtures/webpack-message-formatting/src/AppCss.js
GreenGremlin/create-react-app
import React, { Component } from 'react'; import './AppCss.css'; class App extends Component { render() { return <div className="App" />; } } export default App;
ajax/libs/react-native-web/0.12.3/exports/AppRegistry/AppContainer.js
cdnjs/cdnjs
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import StyleSheet from '../StyleSheet'; import View from '../View'; import { any } from 'prop-types'; import React from 'react'; var AppContainer = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(AppContainer, _React$Component); function AppContainer() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this; _this.state = { mainKey: 1 }; return _this; } var _proto = AppContainer.prototype; _proto.getChildContext = function getChildContext() { return { rootTag: this.props.rootTag }; }; _proto.render = function render() { var _this$props = this.props, children = _this$props.children, WrapperComponent = _this$props.WrapperComponent; var innerView = React.createElement(View, { children: children, key: this.state.mainKey, pointerEvents: "box-none", style: styles.appContainer }); if (WrapperComponent) { innerView = React.createElement(WrapperComponent, null, innerView); } return React.createElement(View, { pointerEvents: "box-none", style: styles.appContainer }, innerView); }; return AppContainer; }(React.Component); AppContainer.childContextTypes = { rootTag: any }; export { AppContainer as default }; var styles = StyleSheet.create({ appContainer: { flex: 1 } });
wp-includes/js/jquery/jquery.js
joachimbl/ajourdk
/*! jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")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(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.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=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.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,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.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,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=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,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},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(e,t){return e.which==null&&(e.which=t.charCode!=null?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,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.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]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.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,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.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)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.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){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(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 lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={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,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.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=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=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):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); jQuery.noConflict();
src/AutoProgressBar.js
peterbe/whatsdeployed
import React from 'react'; import PropTypes from 'prop-types'; import { Progress } from 'reactstrap'; export default class AutoProgressBar extends React.Component { static propTypes = { done: PropTypes.number, total: PropTypes.number, targetTime: PropTypes.number, auto: PropTypes.bool, autoTickRate: PropTypes.number, }; static defaultProps = { targetTime: 5000, auto: true, autoTickRate: 100, }; constructor(props) { super(props); this.state = { autoCounter: 0, }; this.interval = null; } componentDidMount() { this.interval = setInterval(() => this.tick(), this.props.autoTickRate); this.setState({ autoCounter: 0 }); } componentWillUnmount() { clearInterval(this.interval); } tick() { const { autoTickRate, targetTime } = this.props; this.setState((state) => { const next = state.autoCounter + autoTickRate; if (next > targetTime) { clearInterval(this.interval); } return { autoCounter: next }; }); } render() { const { auto, done, total, targetTime } = this.props; const { autoCounter } = this.state; let displayedProgress = 0; if (done && total) { displayedProgress = Math.max(displayedProgress, done / total); } if (auto) { let fakeProgress = autoCounter / targetTime; displayedProgress = Math.max(displayedProgress, fakeProgress); } if (displayedProgress > 1) { displayedProgress = 1; } return ( <Progress animated color="success" striped value={displayedProgress} max={1} > {displayedProgress >= 0.99 && 'This is taking a while...'} </Progress> ); } }
addons/themes/minimaxing/layouts/Blog.js
rendact/rendact
import $ from 'jquery' import React from 'react'; import gql from 'graphql-tag'; import {graphql} from 'react-apollo'; import moment from 'moment'; import {Link} from 'react-router'; import scrollToElement from 'scroll-to-element'; let Blog = React.createClass({ componentDidMount(){ require('../assets/css/main.css') }, handleScrolly(e){ scrollToElement("#inti", { duration: 1500, offset: 0, ease: 'in-sine' }) }, render(){ let { theConfig, latestPosts: data, thePagination, loadDone } = this.props; return ( <div> <div id="page-wrapper"> <div id="header-wrapper"> <div className="container"> <div className="row"> <div className="12u"> <header id="header"> <h1 id="logo"><Link to={"/"}>Home</Link></h1> <nav id="nav"> {this.props.theMenu()} </nav> </header> </div> </div> </div> </div> <div id="banner-wrapper"> <div className="container"> <div id="banner"> <h2>{theConfig?theConfig.name:"Rendact"}</h2> <span>{theConfig?theConfig.tagline:"Hello, you are in Rendact"}</span> </div> </div> </div> <div id="main"> <div className="container"> <div className="row main-row"> <div className="12u 12u(mobile)"> <section> <h2>Just another blog post</h2> <ul className="big-image-list"> {data && data.map((post, index) => ( <li> <Link to={"/post/" + post.id}> <img src={post.imageFeatured ? post.imageFeatured.blobUrl: require('images/logo-128.png') } alt="" className="left" /> </Link> <h3><Link to={"/post/" + post.id}>{post.title && post.title}</Link></h3> <p dangerouslySetInnerHTML={{__html: post.content ? post.content.slice(0, 300):""}} /> <footer className="controls"> <Link className="button" to={"/post/" + post.id}>Continue Reading</Link> </footer> </li> ))} </ul> </section> </div> </div> </div> <div style={{textAlign: "center"}}> {this.props.thePagination} </div> </div> <div id="footer-wrapper"> <div className="container"> <div className="row"> <div className="12u 12u(mobile)"> <section> <div> <div className="row"> {this.props.footerWidgets && this.props.footerWidgets.map((fw, idx) =><div className="4u 12u(mobile)"><ul className="link-list">{fw}</ul></div>)} </div> </div> </section> </div> </div> <div className="row"> <div className="12u"> <div id="copyright"> &copy; Rendact. All rights reserved. | Design: <a href="http://html5up.net">HTML5 UP</a> </div> </div> </div> </div> </div> </div> </div> ) } }); export default Blog;
packages/cxx/src/router.js
wangzuo/cxx
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import NProgress from 'nprogress'; import { createOperationSelector, getOperation } from 'relay-runtime'; import QueryRenderer from './query-renderer'; import normalizeHref from './normalize-href'; import createMatcher from './matcher'; export default class Router extends Component { static childContextTypes = { router: PropTypes.object }; constructor(props) { super(props); const location = normalizeHref({ pathname: props.history.location.pathname, search: props.history.location.search }); this.matcher = createMatcher(props.routes); const match = this.matcher(location); const { page } = match; // todo match.query conflicts if (page.query) { const variables = page.variables ? page.variables(match) : {}; const operation = createOperationSelector( getOperation(page.query), variables ); // todo this.props.environment.retain(operation.root); } this.state = { match }; } getChildContext() { return { router: { history: this.props.history } }; } componentWillMount() { const { routes, environment, history } = this.props; history.listen(location => { const match = this.matcher(normalizeHref(location)); const { page } = match; if (page.query) { const variables = page.variables ? page.variables(match) : {}; const operation = createOperationSelector( getOperation(page.query), variables ); if (environment.check(operation.root)) { this.setState({ match }); } else { // todo: customize NProgress.start(); // todo: retain? environment.retain(operation.root); environment.sendQuery({ operation, onCompleted: () => { setTimeout(() => { this.setState({ match }); NProgress.done(); }, 1000); }, onError: error => console.log(error) }); } } else { this.setState({ match }); } }); } render() { const { environment } = this.props; const { match } = this.state; const { page } = match; const variables = page.variables ? page.variables(match) : {}; return ( <QueryRenderer environment={environment} query={page.query} variables={variables} render={result => React.createElement(page.default, result)} /> ); } }
client/src/components/Home.js
kevinladkins/newsfeed
import React from 'react' import Login from '../containers/Login' import {Link} from 'react-router-dom' const Home = (props) => <div> <h2 > Welcome! Log in below to view your newsfeed, or <Link className="link" to="/signup">click here</Link> to sign up. </h2> <Login history={props.history}/> </div> export default Home
app/main.js
n8e/simple-react
import React from 'react'; import ReactDOM from 'react-dom'; import App from './views/App.jsx'; ReactDOM.render(<App />, document.getElementById('wrapper'));
packages/material-ui-icons/src/BrushSharp.js
allanalexandre/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="M7 14c-1.66 0-3 1.34-3 3 0 1.31-1.16 2-2 2 .92 1.22 2.49 2 4 2 2.21 0 4-1.79 4-4 0-1.66-1.34-3-3-3zm14.41-8.66l-2.75-2.75L9 12.25 11.75 15l9.66-9.66z" /></g></React.Fragment> , 'BrushSharp');
js/react-native/merin_j/src/app.js
petarov/sandbox
// Root Component import React, { Component } from 'react'; import { View, Text } from 'react-native'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxThunk from 'redux-thunk'; import Firebase from 'firebase'; import reducers from './reducers'; import FirebaseCreds from './creds'; import AppWithNavigationState from './AppNavigator'; class App extends Component { componentWillMount() { Firebase.initializeApp(FirebaseCreds); } render() { const store = createStore(reducers, {}, applyMiddleware(ReduxThunk)); return ( <Provider store={store}> <AppWithNavigationState /> </Provider> ) } } export default App;
src/svg-icons/image/photo-size-select-small.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePhotoSizeSelectSmall = (props) => ( <SvgIcon {...props}> <path d="M23 15h-2v2h2v-2zm0-4h-2v2h2v-2zm0 8h-2v2c1 0 2-1 2-2zM15 3h-2v2h2V3zm8 4h-2v2h2V7zm-2-4v2h2c0-1-1-2-2-2zM3 21h8v-6H1v4c0 1.1.9 2 2 2zM3 7H1v2h2V7zm12 12h-2v2h2v-2zm4-16h-2v2h2V3zm0 16h-2v2h2v-2zM3 3C2 3 1 4 1 5h2V3zm0 8H1v2h2v-2zm8-8H9v2h2V3zM7 3H5v2h2V3z"/> </SvgIcon> ); ImagePhotoSizeSelectSmall = pure(ImagePhotoSizeSelectSmall); ImagePhotoSizeSelectSmall.displayName = 'ImagePhotoSizeSelectSmall'; ImagePhotoSizeSelectSmall.muiName = 'SvgIcon'; export default ImagePhotoSizeSelectSmall;
js/jquery.mobile-1.3.2.js
pcphashimoto/WorldClockBox
/*! * jQuery Mobile 1.3.2 * Git HEAD hash: 528cf0e96940644ea644096bfeb913ed920ffaef <> Date: Fri Jul 19 2013 22:17:57 UTC * http://jquerymobile.com * * Copyright 2010, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license. * http://jquery.org/license * */ (function ( root, doc, factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], function ( $ ) { factory( $, root, doc ); return $.mobile; }); } else { // Browser globals factory( root.jQuery, root, doc ); } }( this, document, function ( jQuery, window, document, undefined ) { (function( $ ) { $.mobile = {}; }( jQuery )); (function( $, window, undefined ) { var nsNormalizeDict = {}; // jQuery.mobile configurable options $.mobile = $.extend($.mobile, { // Version of the jQuery Mobile Framework version: "1.3.2", // Namespace used framework-wide for data-attrs. Default is no namespace ns: "", // Define the url parameter used for referencing widget-generated sub-pages. // Translates to to example.html&ui-page=subpageIdentifier // hash segment before &ui-page= is used to make Ajax request subPageUrlKey: "ui-page", // Class assigned to page currently in view, and during transitions activePageClass: "ui-page-active", // Class used for "active" button state, from CSS framework activeBtnClass: "ui-btn-active", // Class used for "focus" form element state, from CSS framework focusClass: "ui-focus", // Automatically handle clicks and form submissions through Ajax, when same-domain ajaxEnabled: true, // Automatically load and show pages based on location.hash hashListeningEnabled: true, // disable to prevent jquery from bothering with links linkBindingEnabled: true, // Set default page transition - 'none' for no transitions defaultPageTransition: "fade", // Set maximum window width for transitions to apply - 'false' for no limit maxTransitionWidth: false, // Minimum scroll distance that will be remembered when returning to a page minScrollBack: 250, // DEPRECATED: the following property is no longer in use, but defined until 2.0 to prevent conflicts touchOverflowEnabled: false, // Set default dialog transition - 'none' for no transitions defaultDialogTransition: "pop", // Error response message - appears when an Ajax page request fails pageLoadErrorMessage: "Error Loading Page", // For error messages, which theme does the box uses? pageLoadErrorMessageTheme: "e", // replace calls to window.history.back with phonegaps navigation helper // where it is provided on the window object phonegapNavigationEnabled: false, //automatically initialize the DOM when it's ready autoInitializePage: true, pushStateEnabled: true, // allows users to opt in to ignoring content by marking a parent element as // data-ignored ignoreContentEnabled: false, // turn of binding to the native orientationchange due to android orientation behavior orientationChangeEnabled: true, buttonMarkup: { hoverDelay: 200 }, // define the window and the document objects window: $( window ), document: $( document ), // TODO might be useful upstream in jquery itself ? keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, // COMMAND COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, // COMMAND_RIGHT NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91 // COMMAND }, // Place to store various widget extensions behaviors: {}, // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value silentScroll: function( ypos ) { if ( $.type( ypos ) !== "number" ) { ypos = $.mobile.defaultHomeScroll; } // prevent scrollstart and scrollstop events $.event.special.scrollstart.enabled = false; setTimeout( function() { window.scrollTo( 0, ypos ); $.mobile.document.trigger( "silentscroll", { x: 0, y: ypos }); }, 20 ); setTimeout( function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, // Expose our cache for testing purposes. nsNormalizeDict: nsNormalizeDict, // Take a data attribute property, prepend the namespace // and then camel case the attribute string. Add the result // to our nsNormalizeDict so we don't have to do this again. nsNormalize: function( prop ) { if ( !prop ) { return; } return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) ); }, // Find the closest parent with a theme class on it. Note that // we are not using $.fn.closest() on purpose here because this // method gets called quite a bit and we need it to be as fast // as possible. getInheritedTheme: function( el, defaultTheme ) { var e = el[ 0 ], ltr = "", re = /ui-(bar|body|overlay)-([a-z])\b/, c, m; while ( e ) { c = e.className || ""; if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) { // We found a parent with a theme class // on it so bail from this loop. break; } e = e.parentNode; } // Return the theme letter we found, if none, return the // specified default. return ltr || defaultTheme || "a"; }, // TODO the following $ and $.fn extensions can/probably should be moved into jquery.mobile.core.helpers // // Find the closest javascript page element to gather settings data jsperf test // http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit // possibly naive, but it shows that the parsing overhead for *just* the page selector vs // the page and dialog selector is negligable. This could probably be speed up by // doing a similar parent node traversal to the one found in the inherited theme code above closestPageData: function( $target ) { return $target .closest( ':jqmData(role="page"), :jqmData(role="dialog")' ) .data( "mobile-page" ); }, enhanceable: function( $set ) { return this.haveParents( $set, "enhance" ); }, hijackable: function( $set ) { return this.haveParents( $set, "ajax" ); }, haveParents: function( $set, attr ) { if ( !$.mobile.ignoreContentEnabled ) { return $set; } var count = $set.length, $newSet = $(), e, $element, excluded; for ( var i = 0; i < count; i++ ) { $element = $set.eq( i ); excluded = false; e = $set[ i ]; while ( e ) { var c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : ""; if ( c === "false" ) { excluded = true; break; } e = e.parentNode; } if ( !excluded ) { $newSet = $newSet.add( $element ); } } return $newSet; }, getScreenHeight: function() { // Native innerHeight returns more accurate value for this across platforms, // jQuery version is here as a normalized fallback for platforms like Symbian return window.innerHeight || $.mobile.window.height(); } }, $.mobile ); // Mobile version of data and removeData and hasData methods // ensures all data is set and retrieved using jQuery Mobile's data namespace $.fn.jqmData = function( prop, value ) { var result; if ( typeof prop !== "undefined" ) { if ( prop ) { prop = $.mobile.nsNormalize( prop ); } // undefined is permitted as an explicit input for the second param // in this case it returns the value and does not set it to undefined if( arguments.length < 2 || value === undefined ){ result = this.data( prop ); } else { result = this.data( prop, value ); } } return result; }; $.jqmData = function( elem, prop, value ) { var result; if ( typeof prop !== "undefined" ) { result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value ); } return result; }; $.fn.jqmRemoveData = function( prop ) { return this.removeData( $.mobile.nsNormalize( prop ) ); }; $.jqmRemoveData = function( elem, prop ) { return $.removeData( elem, $.mobile.nsNormalize( prop ) ); }; $.fn.removeWithDependents = function() { $.removeWithDependents( this ); }; $.removeWithDependents = function( elem ) { var $elem = $( elem ); ( $elem.jqmData( 'dependents' ) || $() ).remove(); $elem.remove(); }; $.fn.addDependents = function( newDependents ) { $.addDependents( $( this ), newDependents ); }; $.addDependents = function( elem, newDependents ) { var dependents = $( elem ).jqmData( 'dependents' ) || $(); $( elem ).jqmData( 'dependents', $.merge( dependents, newDependents ) ); }; // note that this helper doesn't attempt to handle the callback // or setting of an html element's text, its only purpose is // to return the html encoded version of the text in all cases. (thus the name) $.fn.getEncodedText = function() { return $( "<div/>" ).text( $( this ).text() ).html(); }; // fluent helper function for the mobile namespaced equivalent $.fn.jqmEnhanceable = function() { return $.mobile.enhanceable( this ); }; $.fn.jqmHijackable = function() { return $.mobile.hijackable( this ); }; // Monkey-patching Sizzle to filter the :jqmData selector var oldFind = $.find, jqmDataRE = /:jqmData\(([^)]*)\)/g; $.find = function( selector, context, ret, extra ) { selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" ); return oldFind.call( this, selector, context, ret, extra ); }; $.extend( $.find, oldFind ); $.find.matches = function( expr, set ) { return $.find( expr, null, null, set ); }; $.find.matchesSelector = function( node, expr ) { return $.find( expr, null, null, [ node ] ).length > 0; }; })( jQuery, this ); /*! * jQuery UI Widget v1.10.0pre - 2012-11-13 (ff055a0c353c3c8ce6e5bfa07ad7cb03e8885bc5) * http://jqueryui.com * * Copyright 2010, 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( $.isFunction( value ) ) { prototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); } }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name }, prototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) // 1.9 BC for #7810 // TODO remove dual storage .removeData( this.widgetName ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.widget", { // decorate the parent _createWidget to trigger `widgetinit` for users // who wish to do post post `widgetcreate` alterations/additions // // TODO create a pull request for jquery ui to trigger this event // in the original _createWidget _createWidget: function() { $.Widget.prototype._createWidget.apply( this, arguments ); this._trigger( 'init' ); }, _getCreateOptions: function() { var elem = this.element, options = {}; $.each( this.options, function( option ) { var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) { return "-" + c.toLowerCase(); }) ); if ( value !== undefined ) { options[ option ] = value; } }); return options; }, enhanceWithin: function( target, useKeepNative ) { this.enhance( $( this.options.initSelector, $( target )), useKeepNative ); }, enhance: function( targets, useKeepNative ) { var page, keepNative, $widgetElements = $( targets ), self = this; // if ignoreContentEnabled is set to true the framework should // only enhance the selected elements when they do NOT have a // parent with the data-namespace-ignore attribute $widgetElements = $.mobile.enhanceable( $widgetElements ); if ( useKeepNative && $widgetElements.length ) { // TODO remove dependency on the page widget for the keepNative. // Currently the keepNative value is defined on the page prototype so // the method is as well page = $.mobile.closestPageData( $widgetElements ); keepNative = ( page && page.keepNativeSelector()) || ""; $widgetElements = $widgetElements.not( keepNative ); } $widgetElements[ this.widgetName ](); }, raise: function( msg ) { throw "Widget [" + this.widgetName + "]: " + msg; } }); })( jQuery ); (function( $, window ) { // DEPRECATED // NOTE global mobile object settings $.extend( $.mobile, { // DEPRECATED Should the text be visble in the loading message? loadingMessageTextVisible: undefined, // DEPRECATED When the text is visible, what theme does the loading box use? loadingMessageTheme: undefined, // DEPRECATED default message setting loadingMessage: undefined, // DEPRECATED // Turn on/off page loading message. Theme doubles as an object argument // with the following shape: { theme: '', text: '', html: '', textVisible: '' } // NOTE that the $.mobile.loading* settings and params past the first are deprecated showPageLoadingMsg: function( theme, msgText, textonly ) { $.mobile.loading( 'show', theme, msgText, textonly ); }, // DEPRECATED hidePageLoadingMsg: function() { $.mobile.loading( 'hide' ); }, loading: function() { this.loaderWidget.loader.apply( this.loaderWidget, arguments ); } }); // TODO move loader class down into the widget settings var loaderClass = "ui-loader", $html = $( "html" ), $window = $.mobile.window; $.widget( "mobile.loader", { // NOTE if the global config settings are defined they will override these // options options: { // the theme for the loading message theme: "a", // whether the text in the loading message is shown textVisible: false, // custom html for the inner content of the loading message html: "", // the text to be displayed when the popup is shown text: "loading" }, defaultHtml: "<div class='" + loaderClass + "'>" + "<span class='ui-icon ui-icon-loading'></span>" + "<h1></h1>" + "</div>", // For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top fakeFixLoader: function() { var activeBtn = $( "." + $.mobile.activeBtnClass ).first(); this.element .css({ top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 || activeBtn.length && activeBtn.offset().top || 100 }); }, // check position of loader to see if it appears to be "fixed" to center // if not, use abs positioning checkLoaderPosition: function() { var offset = this.element.offset(), scrollTop = $window.scrollTop(), screenHeight = $.mobile.getScreenHeight(); if ( offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight ) { this.element.addClass( "ui-loader-fakefix" ); this.fakeFixLoader(); $window .unbind( "scroll", this.checkLoaderPosition ) .bind( "scroll", $.proxy( this.fakeFixLoader, this ) ); } }, resetHtml: function() { this.element.html( $( this.defaultHtml ).html() ); }, // Turn on/off page loading message. Theme doubles as an object argument // with the following shape: { theme: '', text: '', html: '', textVisible: '' } // NOTE that the $.mobile.loading* settings and params past the first are deprecated // TODO sweet jesus we need to break some of this out show: function( theme, msgText, textonly ) { var textVisible, message, $header, loadSettings; this.resetHtml(); // use the prototype options so that people can set them globally at // mobile init. Consistency, it's what's for dinner if ( $.type(theme) === "object" ) { loadSettings = $.extend( {}, this.options, theme ); // prefer object property from the param then the old theme setting theme = loadSettings.theme || $.mobile.loadingMessageTheme; } else { loadSettings = this.options; // here we prefer the them value passed as a string argument, then // we prefer the global option because we can't use undefined default // prototype options, then the prototype option theme = theme || $.mobile.loadingMessageTheme || loadSettings.theme; } // set the message text, prefer the param, then the settings object // then loading message message = msgText || $.mobile.loadingMessage || loadSettings.text; // prepare the dom $html.addClass( "ui-loading" ); if ( $.mobile.loadingMessage !== false || loadSettings.html ) { // boolean values require a bit more work :P, supports object properties // and old settings if ( $.mobile.loadingMessageTextVisible !== undefined ) { textVisible = $.mobile.loadingMessageTextVisible; } else { textVisible = loadSettings.textVisible; } // add the proper css given the options (theme, text, etc) // Force text visibility if the second argument was supplied, or // if the text was explicitly set in the object args this.element.attr("class", loaderClass + " ui-corner-all ui-body-" + theme + " ui-loader-" + ( textVisible || msgText || theme.text ? "verbose" : "default" ) + ( loadSettings.textonly || textonly ? " ui-loader-textonly" : "" ) ); // TODO verify that jquery.fn.html is ok to use in both cases here // this might be overly defensive in preventing unknowing xss // if the html attribute is defined on the loading settings, use that // otherwise use the fallbacks from above if ( loadSettings.html ) { this.element.html( loadSettings.html ); } else { this.element.find( "h1" ).text( message ); } // attach the loader to the DOM this.element.appendTo( $.mobile.pageContainer ); // check that the loader is visible this.checkLoaderPosition(); // on scroll check the loader position $window.bind( "scroll", $.proxy( this.checkLoaderPosition, this ) ); } }, hide: function() { $html.removeClass( "ui-loading" ); if ( $.mobile.loadingMessage ) { this.element.removeClass( "ui-loader-fakefix" ); } $.mobile.window.unbind( "scroll", this.fakeFixLoader ); $.mobile.window.unbind( "scroll", this.checkLoaderPosition ); } }); $window.bind( 'pagecontainercreate', function() { $.mobile.loaderWidget = $.mobile.loaderWidget || $( $.mobile.loader.prototype.defaultHtml ).loader(); }); })(jQuery, this); // Script: jQuery hashchange event // // *Version: 1.3, Last updated: 7/21/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5, // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and // robust, there are a few unfortunate browser bugs surrounding expected // hashchange event-based behaviors, independent of any JavaScript // window.onhashchange abstraction. See the following examples for more // information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // Also note that should a browser natively support the window.onhashchange // event, but not report that it does, the fallback polling loop will be used. // // About: Release History // // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more // "removable" for mobile-only development. Added IE6/7 document.title // support. Attempted to make Iframe as hidden as possible by using // techniques from http://www.paciellogroup.com/blog/?p=604. Added // support for the "shortcut" format $(window).hashchange( fn ) and // $(window).hashchange() like jQuery provides for built-in events. // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and // lowered its default value to 50. Added <jQuery.fn.hashchange.domain> // and <jQuery.fn.hashchange.src> properties plus document-domain.html // file to address access denied issues when setting document.domain in // IE6/7. // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function( $, window, undefined ) { // Reused string. var str_hashchange = 'hashchange', // Method / object references. doc = document, fake_onhashchange, special = $.event.special, // Does the browser support window.onhashchange? Note that IE8 running in // IE7 compatibility mode reports true for 'onhashchange' in window, even // though the event isn't supported, so also test document.documentMode. doc_mode = doc.documentMode, supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 ); // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || location.href; return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Method: jQuery.fn.hashchange // // Bind a handler to the window.onhashchange event or trigger all bound // window.onhashchange event handlers. This behavior is consistent with // jQuery's built-in event handlers. // // Usage: // // > jQuery(window).hashchange( [ handler ] ); // // Arguments: // // handler - (Function) Optional handler to be bound to the hashchange // event. This is a "shortcut" for the more verbose form: // jQuery(window).bind( 'hashchange', handler ). If handler is omitted, // all bound window.onhashchange event handlers will be triggered. This // is a shortcut for the more verbose // jQuery(window).trigger( 'hashchange' ). These forms are described in // the <hashchange event> section. // // Returns: // // (jQuery) The initial jQuery collection of elements. // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and // $(elem).hashchange() for triggering, like jQuery does for built-in events. $.fn[ str_hashchange ] = function( fn ) { return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange ); }; // Property: jQuery.fn.hashchange.delay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 50. // Property: jQuery.fn.hashchange.domain // // If you're setting document.domain in your JavaScript, and you want hash // history to work in IE6/7, not only must this property be set, but you must // also set document.domain BEFORE jQuery is loaded into the page. This // property is only applicable if you are supporting IE6/7 (or IE8 operating // in "IE7 compatibility" mode). // // In addition, the <jQuery.fn.hashchange.src> property must be set to the // path of the included "document-domain.html" file, which can be renamed or // modified if necessary (note that the document.domain specified must be the // same in both your main JavaScript as well as in this file). // // Usage: // // jQuery.fn.hashchange.domain = document.domain; // Property: jQuery.fn.hashchange.src // // If, for some reason, you need to specify an Iframe src file (for example, // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can // do so using this property. Note that when using this property, history // won't be recorded in IE6/7 until the Iframe src file loads. This property // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7 // compatibility" mode). // // Usage: // // jQuery.fn.hashchange.src = 'path/to/file.html'; $.fn[ str_hashchange ].delay = 50; /* $.fn[ str_hashchange ].domain = null; $.fn[ str_hashchange ].src = null; */ // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // HTML5 window.onhashchange event is used, otherwise a polling loop is // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7 // compatibility" mode), a hidden Iframe is created to allow the back button // and hash-based history to work. // // Usage as described in <jQuery.fn.hashchange>: // // > // Bind an event handler. // > jQuery(window).hashchange( function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).hashchange(); // // A more verbose usage that allows for event namespacing: // // > // Bind an event handler. // > jQuery(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).trigger( 'hashchange' ); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one handler // is actually bound to the 'hashchange' event. // * If you need the bound handler(s) to execute immediately, in cases where // a location.hash exists on page load, via bookmark or page refresh for // example, use jQuery(window).hashchange() or the more verbose // jQuery(window).trigger( 'hashchange' ). // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a DOM ready handler. // Override existing $.event.special.hashchange methods (allowing this plugin // to be defined after jQuery BBQ in BBQ's source code). special[ str_hashchange ] = $.extend( special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function() { var self = {}, timeout_id, // Remember the initial hash so it doesn't get triggered immediately. last_hash = get_fragment(), fn_retval = function( val ) { return val; }, history_set = fn_retval, history_get = fn_retval; // Start the polling loop. self.start = function() { timeout_id || poll(); }; // Stop the polling loop. self.stop = function() { timeout_id && clearTimeout( timeout_id ); timeout_id = undefined; }; // This polling loop checks every $.fn.hashchange.delay milliseconds to see // if location.hash has changed, and triggers the 'hashchange' event on // window when necessary. function poll() { var hash = get_fragment(), history_hash = history_get( last_hash ); if ( hash !== last_hash ) { history_set( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { location.href = location.href.replace( /#.*/, '' ) + history_hash; } timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay ); }; // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv window.attachEvent && !window.addEventListener && !supports_onhashchange && (function() { // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8 // when running in "IE7 compatibility" mode. var iframe, iframe_src; // When the event is bound and polling starts in IE 6/7, create a hidden // Iframe for history handling. self.start = function() { if ( !iframe ) { iframe_src = $.fn[ str_hashchange ].src; iframe_src = iframe_src && iframe_src + get_fragment(); // Create hidden Iframe. Attempt to make Iframe as hidden as possible // by using techniques from http://www.paciellogroup.com/blog/?p=604. iframe = $('<iframe tabindex="-1" title="empty"/>').hide() // When Iframe has completely loaded, initialize the history and // start polling. .one( 'load', function() { iframe_src || history_set( get_fragment() ); poll(); }) // Load Iframe src if specified, otherwise nothing. .attr( 'src', iframe_src || 'javascript:0' ) // Append Iframe after the end of the body to prevent unnecessary // initial page scrolling (yes, this works). .insertAfter( 'body' )[0].contentWindow; // Whenever `document.title` changes, update the Iframe's title to // prettify the back/next history menu entries. Since IE sometimes // errors with "Unspecified error" the very first time this is set // (yes, very useful) wrap this with a try/catch block. doc.onpropertychange = function() { try { if ( event.propertyName === 'title' ) { iframe.document.title = doc.title; } } catch(e) {} }; } }; // Override the "stop" method since an IE6/7 Iframe was created. Even // if there are no longer any bound event handlers, the polling loop // is still necessary for back/next to work at all! self.stop = fn_retval; // Get history by looking at the hidden Iframe's location.hash. history_get = function() { return get_fragment( iframe.location.href ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. If document.domain has // been set, update that as well. history_set = function( hash, history_hash ) { var iframe_doc = iframe.document, domain = $.fn[ str_hashchange ].domain; if ( hash !== history_hash ) { // Update Iframe with any initial `document.title` that might be set. iframe_doc.title = doc.title; // Opening the Iframe's document after it has been closed is what // actually adds a history entry. iframe_doc.open(); // Set document.domain for the Iframe document as well, if necessary. domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' ); iframe_doc.close(); // Update the Iframe's hash, for great justice. iframe.location.hash = hash; } }; })(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return self; })(); })(jQuery,this); (function( $, undefined ) { /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ window.matchMedia = window.matchMedia || (function( doc, undefined ) { var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement( "body" ), div = doc.createElement( "div" ); div.id = "mq-test-1"; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function(q){ div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; docElem.insertBefore( fakeBody, refNode ); bool = div.offsetWidth === 42; docElem.removeChild( fakeBody ); return { matches: bool, media: q }; }; }( document )); // $.mobile.media uses matchMedia to return a boolean. $.mobile.media = function( q ) { return window.matchMedia( q ).matches; }; })(jQuery); (function( $, undefined ) { var support = { touch: "ontouchend" in document }; $.mobile.support = $.mobile.support || {}; $.extend( $.support, support ); $.extend( $.mobile.support, support ); }( jQuery )); (function( $, undefined ) { $.extend( $.support, { orientation: "orientation" in window && "onorientationchange" in window }); }( jQuery )); (function( $, undefined ) { // thx Modernizr function propExists( prop ) { var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ), props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " ); for ( var v in props ) { if ( fbCSS[ props[ v ] ] !== undefined ) { return true; } } } var fakeBody = $( "<body>" ).prependTo( "html" ), fbCSS = fakeBody[ 0 ].style, vendors = [ "Webkit", "Moz", "O" ], webos = "palmGetResource" in window, //only used to rule out scrollTop opera = window.opera, operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]", bb = window.blackberry && !propExists( "-webkit-transform" ); //only used to rule out box shadow, as it's filled opaque on BB 5 and lower function validStyle( prop, value, check_vend ) { var div = document.createElement( 'div' ), uc = function( txt ) { return txt.charAt( 0 ).toUpperCase() + txt.substr( 1 ); }, vend_pref = function( vend ) { if( vend === "" ) { return ""; } else { return "-" + vend.charAt( 0 ).toLowerCase() + vend.substr( 1 ) + "-"; } }, check_style = function( vend ) { var vend_prop = vend_pref( vend ) + prop + ": " + value + ";", uc_vend = uc( vend ), propStyle = uc_vend + ( uc_vend === "" ? prop : uc( prop ) ); div.setAttribute( "style", vend_prop ); if ( !!div.style[ propStyle ] ) { ret = true; } }, check_vends = check_vend ? check_vend : vendors, ret; for( var i = 0; i < check_vends.length; i++ ) { check_style( check_vends[i] ); } return !!ret; } function transform3dTest() { var mqProp = "transform-3d", // Because the `translate3d` test below throws false positives in Android: ret = $.mobile.media( "(-" + vendors.join( "-" + mqProp + "),(-" ) + "-" + mqProp + "),(" + mqProp + ")" ); if( ret ) { return !!ret; } var el = document.createElement( "div" ), transforms = { // We’re omitting Opera for the time being; MS uses unprefixed. 'MozTransform':'-moz-transform', 'transform':'transform' }; fakeBody.append( el ); for ( var t in transforms ) { if( el.style[ t ] !== undefined ){ el.style[ t ] = 'translate3d( 100px, 1px, 1px )'; ret = window.getComputedStyle( el ).getPropertyValue( transforms[ t ] ); } } return ( !!ret && ret !== "none" ); } // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting ) function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/", base = $( "head base" ), fauxEle = null, href = "", link, rebase; if ( !base.length ) { base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" ); } else { href = base.attr( "href" ); } link = $( "<a href='testurl' />" ).prependTo( fakeBody ); rebase = link[ 0 ].href; base[ 0 ].href = href || location.pathname; if ( fauxEle ) { fauxEle.remove(); } return rebase.indexOf( fauxBase ) === 0; } // Thanks Modernizr function cssPointerEventsTest() { var element = document.createElement( 'x' ), documentElement = document.documentElement, getComputedStyle = window.getComputedStyle, supports; if ( !( 'pointerEvents' in element.style ) ) { return false; } element.style.pointerEvents = 'auto'; element.style.pointerEvents = 'x'; documentElement.appendChild( element ); supports = getComputedStyle && getComputedStyle( element, '' ).pointerEvents === 'auto'; documentElement.removeChild( element ); return !!supports; } function boundingRect() { var div = document.createElement( "div" ); return typeof div.getBoundingClientRect !== "undefined"; } // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683 // allows for inclusion of IE 6+, including Windows Mobile 7 $.extend( $.mobile, { browser: {} } ); $.mobile.browser.oldIE = (function() { var v = 3, div = document.createElement( "div" ), a = div.all || []; do { div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->"; } while( a[0] ); return v > 4 ? v : !v; })(); function fixedPosition() { var w = window, ua = navigator.userAgent, platform = navigator.platform, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], ffmatch = ua.match( /Fennec\/([0-9]+)/ ), ffversion = !!ffmatch && ffmatch[ 1 ], operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ), omversion = !!operammobilematch && operammobilematch[ 1 ]; if( // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5) ( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 ) || // Opera Mini ( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" ) || ( operammobilematch && omversion < 7458 ) || //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2) ( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 ) || // Firefox Mobile before 6.0 - ( ffversion && ffversion < 6 ) || // WebOS less than 3 ( "palmGetResource" in window && wkversion && wkversion < 534 ) || // MeeGo ( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 ) ) { return false; } return true; } $.extend( $.support, { cssTransitions: "WebKitTransitionEvent" in window || validStyle( 'transition', 'height 100ms linear', [ "Webkit", "Moz", "" ] ) && !$.mobile.browser.oldIE && !opera, // Note, Chrome for iOS has an extremely quirky implementation of popstate. // We've chosen to take the shortest path to a bug fix here for issue #5426 // See the following link for information about the regex chosen // https://developers.google.com/chrome/mobile/docs/user-agent#chrome_for_ios_user-agent pushState: "pushState" in history && "replaceState" in history && // When running inside a FF iframe, calling replaceState causes an error !( window.navigator.userAgent.indexOf( "Firefox" ) >= 0 && window.top !== window ) && ( window.navigator.userAgent.search(/CriOS/) === -1 ), mediaquery: $.mobile.media( "only all" ), cssPseudoElement: !!propExists( "content" ), touchOverflow: !!propExists( "overflowScrolling" ), cssTransform3d: transform3dTest(), boxShadow: !!propExists( "boxShadow" ) && !bb, fixedPosition: fixedPosition(), scrollTop: ("pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ]) && !webos && !operamini, dynamicBaseTag: baseTagTest(), cssPointerEvents: cssPointerEventsTest(), boundingRect: boundingRect() }); fakeBody.remove(); // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian) // or that generally work better browsing in regular http for full page refreshes (Opera Mini) // Note: This detection below is used as a last resort. // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible var nokiaLTE7_3 = (function() { var ua = window.navigator.userAgent; //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older return ua.indexOf( "Nokia" ) > -1 && ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) && ua.indexOf( "AppleWebKit" ) > -1 && ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ ); })(); // Support conditions that must be met in order to proceed // default enhanced qualifications are media query support OR IE 7+ $.mobile.gradeA = function() { return ( $.support.mediaquery || $.mobile.browser.oldIE && $.mobile.browser.oldIE >= 7 ) && ( $.support.boundingRect || $.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/) !== null ); }; $.mobile.ajaxBlacklist = // BlackBerry browsers, pre-webkit window.blackberry && !window.WebKitPoint || // Opera Mini operamini || // Symbian webkits pre 7.3 nokiaLTE7_3; // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices // to render the stylesheets when they're referenced before this script, as we'd recommend doing. // This simply reappends the CSS in place, which for some reason makes it apply if ( nokiaLTE7_3 ) { $(function() { $( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" ); }); } // For ruling out shadows via css if ( !$.support.boxShadow ) { $( "html" ).addClass( "ui-mobile-nosupport-boxshadow" ); } })( jQuery ); (function( $, undefined ) { var $win = $.mobile.window, self, history; $.event.special.navigate = self = { bound: false, pushStateEnabled: true, originalEventName: undefined, // If pushstate support is present and push state support is defined to // be true on the mobile namespace. isPushStateEnabled: function() { return $.support.pushState && $.mobile.pushStateEnabled === true && this.isHashChangeEnabled(); }, // !! assumes mobile namespace is present isHashChangeEnabled: function() { return $.mobile.hashListeningEnabled === true; }, // TODO a lot of duplication between popstate and hashchange popstate: function( event ) { var newEvent = new $.Event( "navigate" ), beforeNavigate = new $.Event( "beforenavigate" ), state = event.originalEvent.state || {}, href = location.href; $win.trigger( beforeNavigate ); if( beforeNavigate.isDefaultPrevented() ){ return; } if( event.historyState ){ $.extend(state, event.historyState); } // Make sure the original event is tracked for the end // user to inspect incase they want to do something special newEvent.originalEvent = event; // NOTE we let the current stack unwind because any assignment to // location.hash will stop the world and run this event handler. By // doing this we create a similar behavior to hashchange on hash // assignment setTimeout(function() { $win.trigger( newEvent, { state: state }); }, 0); }, hashchange: function( event, data ) { var newEvent = new $.Event( "navigate" ), beforeNavigate = new $.Event( "beforenavigate" ); $win.trigger( beforeNavigate ); if( beforeNavigate.isDefaultPrevented() ){ return; } // Make sure the original event is tracked for the end // user to inspect incase they want to do something special newEvent.originalEvent = event; // Trigger the hashchange with state provided by the user // that altered the hash $win.trigger( newEvent, { // Users that want to fully normalize the two events // will need to do history management down the stack and // add the state to the event before this binding is fired // TODO consider allowing for the explicit addition of callbacks // to be fired before this value is set to avoid event timing issues state: event.hashchangeState || {} }); }, // TODO We really only want to set this up once // but I'm not clear if there's a beter way to achieve // this with the jQuery special event structure setup: function( data, namespaces ) { if( self.bound ) { return; } self.bound = true; if( self.isPushStateEnabled() ) { self.originalEventName = "popstate"; $win.bind( "popstate.navigate", self.popstate ); } else if ( self.isHashChangeEnabled() ){ self.originalEventName = "hashchange"; $win.bind( "hashchange.navigate", self.hashchange ); } } }; })( jQuery ); (function( $, undefined ) { var path, documentBase, $base, dialogHashKey = "&ui-state=dialog"; $.mobile.path = path = { uiStateKey: "&ui-state", // This scary looking regular expression parses an absolute URL or its relative // variants (protocol, site, document, query, and hash), into the various // components (protocol, host, path, query, fragment, etc that make up the // URL as well as some other commonly used sub-parts. When used with RegExp.exec() // or String.match, it parses the URL into a results array that looks like this: // // [0]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread#msg-content // [1]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread // [2]: http://jblas:[email protected]:8080/mail/inbox // [3]: http://jblas:[email protected]:8080 // [4]: http: // [5]: // // [6]: jblas:[email protected]:8080 // [7]: jblas:password // [8]: jblas // [9]: password // [10]: mycompany.com:8080 // [11]: mycompany.com // [12]: 8080 // [13]: /mail/inbox // [14]: /mail/ // [15]: inbox // [16]: ?msg=1234&type=unread // [17]: #msg-content // urlParseRE: /^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/, // Abstraction to address xss (Issue #4787) by removing the authority in // browsers that auto decode it. All references to location.href should be // replaced with a call to this method so that it can be dealt with properly here getLocation: function( url ) { var uri = url ? this.parseUrl( url ) : location, hash = this.parseUrl( url || location.href ).hash; // mimic the browser with an empty string when the hash is empty hash = hash === "#" ? "" : hash; // Make sure to parse the url or the location object for the hash because using location.hash // is autodecoded in firefox, the rest of the url should be from the object (location unless // we're testing) to avoid the inclusion of the authority return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash; }, parseLocation: function() { return this.parseUrl( this.getLocation() ); }, //Parse a URL into a structure that allows easy access to //all of the URL components by name. parseUrl: function( url ) { // If we're passed an object, we'll assume that it is // a parsed url object and just return it back to the caller. if ( $.type( url ) === "object" ) { return url; } var matches = path.urlParseRE.exec( url || "" ) || []; // Create an object that allows the caller to access the sub-matches // by name. Note that IE returns an empty string instead of undefined, // like all other browsers do, so we normalize everything so its consistent // no matter what browser we're running on. return { href: matches[ 0 ] || "", hrefNoHash: matches[ 1 ] || "", hrefNoSearch: matches[ 2 ] || "", domain: matches[ 3 ] || "", protocol: matches[ 4 ] || "", doubleSlash: matches[ 5 ] || "", authority: matches[ 6 ] || "", username: matches[ 8 ] || "", password: matches[ 9 ] || "", host: matches[ 10 ] || "", hostname: matches[ 11 ] || "", port: matches[ 12 ] || "", pathname: matches[ 13 ] || "", directory: matches[ 14 ] || "", filename: matches[ 15 ] || "", search: matches[ 16 ] || "", hash: matches[ 17 ] || "" }; }, //Turn relPath into an asbolute path. absPath is //an optional absolute path which describes what //relPath is relative to. makePathAbsolute: function( relPath, absPath ) { if ( relPath && relPath.charAt( 0 ) === "/" ) { return relPath; } relPath = relPath || ""; absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : ""; var absStack = absPath ? absPath.split( "/" ) : [], relStack = relPath.split( "/" ); for ( var i = 0; i < relStack.length; i++ ) { var d = relStack[ i ]; switch ( d ) { case ".": break; case "..": if ( absStack.length ) { absStack.pop(); } break; default: absStack.push( d ); break; } } return "/" + absStack.join( "/" ); }, //Returns true if both urls have the same domain. isSameDomain: function( absUrl1, absUrl2 ) { return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain; }, //Returns true for any relative variant. isRelativeUrl: function( url ) { // All relative Url variants have one thing in common, no protocol. return path.parseUrl( url ).protocol === ""; }, //Returns true for an absolute url. isAbsoluteUrl: function( url ) { return path.parseUrl( url ).protocol !== ""; }, //Turn the specified realtive URL into an absolute one. This function //can handle all relative variants (protocol, site, document, query, fragment). makeUrlAbsolute: function( relUrl, absUrl ) { if ( !path.isRelativeUrl( relUrl ) ) { return relUrl; } if ( absUrl === undefined ) { absUrl = this.documentBase; } var relObj = path.parseUrl( relUrl ), absObj = path.parseUrl( absUrl ), protocol = relObj.protocol || absObj.protocol, doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ), authority = relObj.authority || absObj.authority, hasPath = relObj.pathname !== "", pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ), search = relObj.search || ( !hasPath && absObj.search ) || "", hash = relObj.hash; return protocol + doubleSlash + authority + pathname + search + hash; }, //Add search (aka query) params to the specified url. addSearchParams: function( url, params ) { var u = path.parseUrl( url ), p = ( typeof params === "object" ) ? $.param( params ) : params, s = u.search || "?"; return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" ); }, convertUrlToDataUrl: function( absUrl ) { var u = path.parseUrl( absUrl ); if ( path.isEmbeddedPage( u ) ) { // For embedded pages, remove the dialog hash key as in getFilePath(), // and remove otherwise the Data Url won't match the id of the embedded Page. return u.hash .split( dialogHashKey )[0] .replace( /^#/, "" ) .replace( /\?.*$/, "" ); } else if ( path.isSameDomain( u, this.documentBase ) ) { return u.hrefNoHash.replace( this.documentBase.domain, "" ).split( dialogHashKey )[0]; } return window.decodeURIComponent(absUrl); }, //get path from current hash, or from a file path get: function( newPath ) { if ( newPath === undefined ) { newPath = path.parseLocation().hash; } return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' ); }, //set location hash to path set: function( path ) { location.hash = path; }, //test if a given url (string) is a path //NOTE might be exceptionally naive isPath: function( url ) { return ( /\// ).test( url ); }, //return a url path with the window's location protocol/hostname/pathname removed clean: function( url ) { return url.replace( this.documentBase.domain, "" ); }, //just return the url without an initial # stripHash: function( url ) { return url.replace( /^#/, "" ); }, stripQueryParams: function( url ) { return url.replace( /\?.*$/, "" ); }, //remove the preceding hash, any query params, and dialog notations cleanHash: function( hash ) { return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) ); }, isHashValid: function( hash ) { return ( /^#[^#]+$/ ).test( hash ); }, //check whether a url is referencing the same domain, or an external domain or different protocol //could be mailto, etc isExternal: function( url ) { var u = path.parseUrl( url ); return u.protocol && u.domain !== this.documentUrl.domain ? true : false; }, hasProtocol: function( url ) { return ( /^(:?\w+:)/ ).test( url ); }, isEmbeddedPage: function( url ) { var u = path.parseUrl( url ); //if the path is absolute, then we need to compare the url against //both the this.documentUrl and the documentBase. The main reason for this //is that links embedded within external documents will refer to the //application document, whereas links embedded within the application //document will be resolved against the document base. if ( u.protocol !== "" ) { return ( !this.isPath(u.hash) && u.hash && ( u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ) ) ); } return ( /^#/ ).test( u.href ); }, squash: function( url, resolutionUrl ) { var state, href, cleanedUrl, search, stateIndex, isPath = this.isPath( url ), uri = this.parseUrl( url ), preservedHash = uri.hash, uiState = ""; // produce a url against which we can resole the provided path resolutionUrl = resolutionUrl || (path.isPath(url) ? path.getLocation() : path.getDocumentUrl()); // If the url is anything but a simple string, remove any preceding hash // eg #foo/bar -> foo/bar // #foo -> #foo cleanedUrl = isPath ? path.stripHash( url ) : url; // If the url is a full url with a hash check if the parsed hash is a path // if it is, strip the #, and use it otherwise continue without change cleanedUrl = path.isPath( uri.hash ) ? path.stripHash( uri.hash ) : cleanedUrl; // Split the UI State keys off the href stateIndex = cleanedUrl.indexOf( this.uiStateKey ); // store the ui state keys for use if( stateIndex > -1 ){ uiState = cleanedUrl.slice( stateIndex ); cleanedUrl = cleanedUrl.slice( 0, stateIndex ); } // make the cleanedUrl absolute relative to the resolution url href = path.makeUrlAbsolute( cleanedUrl, resolutionUrl ); // grab the search from the resolved url since parsing from // the passed url may not yield the correct result search = this.parseUrl( href ).search; // TODO all this crap is terrible, clean it up if ( isPath ) { // reject the hash if it's a path or it's just a dialog key if( path.isPath( preservedHash ) || preservedHash.replace("#", "").indexOf( this.uiStateKey ) === 0) { preservedHash = ""; } // Append the UI State keys where it exists and it's been removed // from the url if( uiState && preservedHash.indexOf( this.uiStateKey ) === -1){ preservedHash += uiState; } // make sure that pound is on the front of the hash if( preservedHash.indexOf( "#" ) === -1 && preservedHash !== "" ){ preservedHash = "#" + preservedHash; } // reconstruct each of the pieces with the new search string and hash href = path.parseUrl( href ); href = href.protocol + "//" + href.host + href.pathname + search + preservedHash; } else { href += href.indexOf( "#" ) > -1 ? uiState : "#" + uiState; } return href; }, isPreservableHash: function( hash ) { return hash.replace( "#", "" ).indexOf( this.uiStateKey ) === 0; } }; path.documentUrl = path.parseLocation(); $base = $( "head" ).find( "base" ); path.documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), path.documentUrl.href ) ) : path.documentUrl; path.documentBaseDiffers = (path.documentUrl.hrefNoHash !== path.documentBase.hrefNoHash); //return the original document url path.getDocumentUrl = function( asParsedObject ) { return asParsedObject ? $.extend( {}, path.documentUrl ) : path.documentUrl.href; }; //return the original document base url path.getDocumentBase = function( asParsedObject ) { return asParsedObject ? $.extend( {}, path.documentBase ) : path.documentBase.href; }; })( jQuery ); (function( $, undefined ) { var path = $.mobile.path; $.mobile.History = function( stack, index ) { this.stack = stack || []; this.activeIndex = index || 0; }; $.extend($.mobile.History.prototype, { getActive: function() { return this.stack[ this.activeIndex ]; }, getLast: function() { return this.stack[ this.previousIndex ]; }, getNext: function() { return this.stack[ this.activeIndex + 1 ]; }, getPrev: function() { return this.stack[ this.activeIndex - 1 ]; }, // addNew is used whenever a new page is added add: function( url, data ){ data = data || {}; //if there's forward history, wipe it if ( this.getNext() ) { this.clearForward(); } // if the hash is included in the data make sure the shape // is consistent for comparison if( data.hash && data.hash.indexOf( "#" ) === -1) { data.hash = "#" + data.hash; } data.url = url; this.stack.push( data ); this.activeIndex = this.stack.length - 1; }, //wipe urls ahead of active index clearForward: function() { this.stack = this.stack.slice( 0, this.activeIndex + 1 ); }, find: function( url, stack, earlyReturn ) { stack = stack || this.stack; var entry, i, length = stack.length, index; for ( i = 0; i < length; i++ ) { entry = stack[i]; if ( decodeURIComponent(url) === decodeURIComponent(entry.url) || decodeURIComponent(url) === decodeURIComponent(entry.hash) ) { index = i; if( earlyReturn ) { return index; } } } return index; }, closest: function( url ) { var closest, a = this.activeIndex; // First, take the slice of the history stack before the current index and search // for a url match. If one is found, we'll avoid avoid looking through forward history // NOTE the preference for backward history movement is driven by the fact that // most mobile browsers only have a dedicated back button, and users rarely use // the forward button in desktop browser anyhow closest = this.find( url, this.stack.slice(0, a) ); // If nothing was found in backward history check forward. The `true` // value passed as the third parameter causes the find method to break // on the first match in the forward history slice. The starting index // of the slice must then be added to the result to get the element index // in the original history stack :( :( // // TODO this is hyper confusing and should be cleaned up (ugh so bad) if( closest === undefined ) { closest = this.find( url, this.stack.slice(a), true ); closest = closest === undefined ? closest : closest + a; } return closest; }, direct: function( opts ) { var newActiveIndex = this.closest( opts.url ), a = this.activeIndex; // save new page index, null check to prevent falsey 0 result // record the previous index for reference if( newActiveIndex !== undefined ) { this.activeIndex = newActiveIndex; this.previousIndex = a; } // invoke callbacks where appropriate // // TODO this is also convoluted and confusing if ( newActiveIndex < a ) { ( opts.present || opts.back || $.noop )( this.getActive(), 'back' ); } else if ( newActiveIndex > a ) { ( opts.present || opts.forward || $.noop )( this.getActive(), 'forward' ); } else if ( newActiveIndex === undefined && opts.missing ){ opts.missing( this.getActive() ); } } }); })( jQuery ); (function( $, undefined ) { var path = $.mobile.path, initialHref = location.href; $.mobile.Navigator = function( history ) { this.history = history; this.ignoreInitialHashChange = true; $.mobile.window.bind({ "popstate.history": $.proxy( this.popstate, this ), "hashchange.history": $.proxy( this.hashchange, this ) }); }; $.extend($.mobile.Navigator.prototype, { squash: function( url, data ) { var state, href, hash = path.isPath(url) ? path.stripHash(url) : url; href = path.squash( url ); // make sure to provide this information when it isn't explicitly set in the // data object that was passed to the squash method state = $.extend({ hash: hash, url: href }, data); // replace the current url with the new href and store the state // Note that in some cases we might be replacing an url with the // same url. We do this anyways because we need to make sure that // all of our history entries have a state object associated with // them. This allows us to work around the case where $.mobile.back() // is called to transition from an external page to an embedded page. // In that particular case, a hashchange event is *NOT* generated by the browser. // Ensuring each history entry has a state object means that onPopState() // will always trigger our hashchange callback even when a hashchange event // is not fired. window.history.replaceState( state, state.title || document.title, href ); return state; }, hash: function( url, href ) { var parsed, loc, hash; // Grab the hash for recording. If the passed url is a path // we used the parsed version of the squashed url to reconstruct, // otherwise we assume it's a hash and store it directly parsed = path.parseUrl( url ); loc = path.parseLocation(); if( loc.pathname + loc.search === parsed.pathname + parsed.search ) { // If the pathname and search of the passed url is identical to the current loc // then we must use the hash. Otherwise there will be no event // eg, url = "/foo/bar?baz#bang", location.href = "http://example.com/foo/bar?baz" hash = parsed.hash ? parsed.hash : parsed.pathname + parsed.search; } else if ( path.isPath(url) ) { var resolved = path.parseUrl( href ); // If the passed url is a path, make it domain relative and remove any trailing hash hash = resolved.pathname + resolved.search + (path.isPreservableHash( resolved.hash )? resolved.hash.replace( "#", "" ) : ""); } else { hash = url; } return hash; }, // TODO reconsider name go: function( url, data, noEvents ) { var state, href, hash, popstateEvent, isPopStateEvent = $.event.special.navigate.isPushStateEnabled(); // Get the url as it would look squashed on to the current resolution url href = path.squash( url ); // sort out what the hash sould be from the url hash = this.hash( url, href ); // Here we prevent the next hash change or popstate event from doing any // history management. In the case of hashchange we don't swallow it // if there will be no hashchange fired (since that won't reset the value) // and will swallow the following hashchange if( noEvents && hash !== path.stripHash(path.parseLocation().hash) ) { this.preventNextHashChange = noEvents; } // IMPORTANT in the case where popstate is supported the event will be triggered // directly, stopping further execution - ie, interupting the flow of this // method call to fire bindings at this expression. Below the navigate method // there is a binding to catch this event and stop its propagation. // // We then trigger a new popstate event on the window with a null state // so that the navigate events can conclude their work properly // // if the url is a path we want to preserve the query params that are available on // the current url. this.preventHashAssignPopState = true; window.location.hash = hash; // If popstate is enabled and the browser triggers `popstate` events when the hash // is set (this often happens immediately in browsers like Chrome), then the // this flag will be set to false already. If it's a browser that does not trigger // a `popstate` on hash assignement or `replaceState` then we need avoid the branch // that swallows the event created by the popstate generated by the hash assignment // At the time of this writing this happens with Opera 12 and some version of IE this.preventHashAssignPopState = false; state = $.extend({ url: href, hash: hash, title: document.title }, data); if( isPopStateEvent ) { popstateEvent = new $.Event( "popstate" ); popstateEvent.originalEvent = { type: "popstate", state: null }; this.squash( url, state ); // Trigger a new faux popstate event to replace the one that we // caught that was triggered by the hash setting above. if( !noEvents ) { this.ignorePopState = true; $.mobile.window.trigger( popstateEvent ); } } // record the history entry so that the information can be included // in hashchange event driven navigate events in a similar fashion to // the state that's provided by popstate this.history.add( state.url, state ); }, // This binding is intended to catch the popstate events that are fired // when execution of the `$.navigate` method stops at window.location.hash = url; // and completely prevent them from propagating. The popstate event will then be // retriggered after execution resumes // // TODO grab the original event here and use it for the synthetic event in the // second half of the navigate execution that will follow this binding popstate: function( event ) { var active, hash, state, closestIndex; // Partly to support our test suite which manually alters the support // value to test hashchange. Partly to prevent all around weirdness if( !$.event.special.navigate.isPushStateEnabled() ){ return; } // If this is the popstate triggered by the actual alteration of the hash // prevent it completely. History is tracked manually if( this.preventHashAssignPopState ) { this.preventHashAssignPopState = false; event.stopImmediatePropagation(); return; } // if this is the popstate triggered after the `replaceState` call in the go // method, then simply ignore it. The history entry has already been captured if( this.ignorePopState ) { this.ignorePopState = false; return; } // If there is no state, and the history stack length is one were // probably getting the page load popstate fired by browsers like chrome // avoid it and set the one time flag to false. // TODO: Do we really need all these conditions? Comparing location hrefs // should be sufficient. if( !event.originalEvent.state && this.history.stack.length === 1 && this.ignoreInitialHashChange ) { this.ignoreInitialHashChange = false; if ( location.href === initialHref ) { event.preventDefault(); return; } } // account for direct manipulation of the hash. That is, we will receive a popstate // when the hash is changed by assignment, and it won't have a state associated. We // then need to squash the hash. See below for handling of hash assignment that // matches an existing history entry // TODO it might be better to only add to the history stack // when the hash is adjacent to the active history entry hash = path.parseLocation().hash; if( !event.originalEvent.state && hash ) { // squash the hash that's been assigned on the URL with replaceState // also grab the resulting state object for storage state = this.squash( hash ); // record the new hash as an additional history entry // to match the browser's treatment of hash assignment this.history.add( state.url, state ); // pass the newly created state information // along with the event event.historyState = state; // do not alter history, we've added a new history entry // so we know where we are return; } // If all else fails this is a popstate that comes from the back or forward buttons // make sure to set the state of our history stack properly, and record the directionality this.history.direct({ url: (event.originalEvent.state || {}).url || hash, // When the url is either forward or backward in history include the entry // as data on the event object for merging as data in the navigate event present: function( historyEntry, direction ) { // make sure to create a new object to pass down as the navigate event data event.historyState = $.extend({}, historyEntry); event.historyState.direction = direction; } }); }, // NOTE must bind before `navigate` special event hashchange binding otherwise the // navigation data won't be attached to the hashchange event in time for those // bindings to attach it to the `navigate` special event // TODO add a check here that `hashchange.navigate` is bound already otherwise it's // broken (exception?) hashchange: function( event ) { var history, hash; // If hashchange listening is explicitly disabled or pushstate is supported // avoid making use of the hashchange handler. if(!$.event.special.navigate.isHashChangeEnabled() || $.event.special.navigate.isPushStateEnabled() ) { return; } // On occasion explicitly want to prevent the next hash from propogating because we only // with to alter the url to represent the new state do so here if( this.preventNextHashChange ){ this.preventNextHashChange = false; event.stopImmediatePropagation(); return; } history = this.history; hash = path.parseLocation().hash; // If this is a hashchange caused by the back or forward button // make sure to set the state of our history stack properly this.history.direct({ url: hash, // When the url is either forward or backward in history include the entry // as data on the event object for merging as data in the navigate event present: function( historyEntry, direction ) { // make sure to create a new object to pass down as the navigate event data event.hashchangeState = $.extend({}, historyEntry); event.hashchangeState.direction = direction; }, // When we don't find a hash in our history clearly we're aiming to go there // record the entry as new for future traversal // // NOTE it's not entirely clear that this is the right thing to do given that we // can't know the users intention. It might be better to explicitly _not_ // support location.hash assignment in preference to $.navigate calls // TODO first arg to add should be the href, but it causes issues in identifying // embeded pages missing: function() { history.add( hash, { hash: hash, title: document.title }); } }); } }); })( jQuery ); (function( $, undefined ) { // TODO consider queueing navigation activity until previous activities have completed // so that end users don't have to think about it. Punting for now // TODO !! move the event bindings into callbacks on the navigate event $.mobile.navigate = function( url, data, noEvents ) { $.mobile.navigate.navigator.go( url, data, noEvents ); }; // expose the history on the navigate method in anticipation of full integration with // existing navigation functionalty that is tightly coupled to the history information $.mobile.navigate.history = new $.mobile.History(); // instantiate an instance of the navigator for use within the $.navigate method $.mobile.navigate.navigator = new $.mobile.Navigator( $.mobile.navigate.history ); var loc = $.mobile.path.parseLocation(); $.mobile.navigate.history.add( loc.href, {hash: loc.hash} ); })( jQuery ); // This plugin is an experiment for abstracting away the touch and mouse // events so that developers don't have to worry about which method of input // the device their document is loaded on supports. // // The idea here is to allow the developer to register listeners for the // basic mouse events, such as mousedown, mousemove, mouseup, and click, // and the plugin will take care of registering the correct listeners // behind the scenes to invoke the listener at the fastest possible time // for that device, while still retaining the order of event firing in // the traditional mouse environment, should multiple handlers be registered // on the same element for different events. // // The current version exposes the following virtual events to jQuery bind methods: // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel" (function( $, window, document, undefined ) { var dataPropertyName = "virtualMouseBindings", touchTargetPropertyName = "virtualTouchID", virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ), touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ), mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [], mouseEventProps = $.event.props.concat( mouseHookProps ), activeDocHandlers = {}, resetTimerID = 0, startX = 0, startY = 0, didScroll = false, clickBlockList = [], blockMouseTriggers = false, blockTouchTriggers = false, eventCaptureSupported = "addEventListener" in document, $document = $( document ), nextTouchID = 1, lastTouchID = 0, threshold; $.vmouse = { moveDistanceThreshold: 10, clickDistanceThreshold: 10, resetTimerDuration: 1500 }; function getNativeEvent( event ) { while ( event && typeof event.originalEvent !== "undefined" ) { event = event.originalEvent; } return event; } function createVirtualEvent( event, eventType ) { var t = event.type, oe, props, ne, prop, ct, touch, i, j, len; event = $.Event( event ); event.type = eventType; oe = event.originalEvent; props = $.event.props; // addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280 // https://github.com/jquery/jquery-mobile/issues/3280 if ( t.search( /^(mouse|click)/ ) > -1 ) { props = mouseEventProps; } // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( oe ) { for ( i = props.length, prop; i; ) { prop = props[ --i ]; event[ prop ] = oe[ prop ]; } } // make sure that if the mouse and click virtual events are generated // without a .which one is defined if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ) { event.which = 1; } if ( t.search(/^touch/) !== -1 ) { ne = getNativeEvent( oe ); t = ne.touches; ct = ne.changedTouches; touch = ( t && t.length ) ? t[0] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined ); if ( touch ) { for ( j = 0, len = touchEventProps.length; j < len; j++) { prop = touchEventProps[ j ]; event[ prop ] = touch[ prop ]; } } } return event; } function getVirtualBindingFlags( element ) { var flags = {}, b, k; while ( element ) { b = $.data( element, dataPropertyName ); for ( k in b ) { if ( b[ k ] ) { flags[ k ] = flags.hasVirtualBinding = true; } } element = element.parentNode; } return flags; } function getClosestElementWithVirtualBinding( element, eventType ) { var b; while ( element ) { b = $.data( element, dataPropertyName ); if ( b && ( !eventType || b[ eventType ] ) ) { return element; } element = element.parentNode; } return null; } function enableTouchBindings() { blockTouchTriggers = false; } function disableTouchBindings() { blockTouchTriggers = true; } function enableMouseBindings() { lastTouchID = 0; clickBlockList.length = 0; blockMouseTriggers = false; // When mouse bindings are enabled, our // touch bindings are disabled. disableTouchBindings(); } function disableMouseBindings() { // When mouse bindings are disabled, our // touch bindings are enabled. enableTouchBindings(); } function startResetTimer() { clearResetTimer(); resetTimerID = setTimeout( function() { resetTimerID = 0; enableMouseBindings(); }, $.vmouse.resetTimerDuration ); } function clearResetTimer() { if ( resetTimerID ) { clearTimeout( resetTimerID ); resetTimerID = 0; } } function triggerVirtualEvent( eventType, event, flags ) { var ve; if ( ( flags && flags[ eventType ] ) || ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) { ve = createVirtualEvent( event, eventType ); $( event.target).trigger( ve ); } return ve; } function mouseEventCallback( event ) { var touchID = $.data( event.target, touchTargetPropertyName ); if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ) { var ve = triggerVirtualEvent( "v" + event.type, event ); if ( ve ) { if ( ve.isDefaultPrevented() ) { event.preventDefault(); } if ( ve.isPropagationStopped() ) { event.stopPropagation(); } if ( ve.isImmediatePropagationStopped() ) { event.stopImmediatePropagation(); } } } } function handleTouchStart( event ) { var touches = getNativeEvent( event ).touches, target, flags; if ( touches && touches.length === 1 ) { target = event.target; flags = getVirtualBindingFlags( target ); if ( flags.hasVirtualBinding ) { lastTouchID = nextTouchID++; $.data( target, touchTargetPropertyName, lastTouchID ); clearResetTimer(); disableMouseBindings(); didScroll = false; var t = getNativeEvent( event ).touches[ 0 ]; startX = t.pageX; startY = t.pageY; triggerVirtualEvent( "vmouseover", event, flags ); triggerVirtualEvent( "vmousedown", event, flags ); } } } function handleScroll( event ) { if ( blockTouchTriggers ) { return; } if ( !didScroll ) { triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) ); } didScroll = true; startResetTimer(); } function handleTouchMove( event ) { if ( blockTouchTriggers ) { return; } var t = getNativeEvent( event ).touches[ 0 ], didCancel = didScroll, moveThreshold = $.vmouse.moveDistanceThreshold, flags = getVirtualBindingFlags( event.target ); didScroll = didScroll || ( Math.abs( t.pageX - startX ) > moveThreshold || Math.abs( t.pageY - startY ) > moveThreshold ); if ( didScroll && !didCancel ) { triggerVirtualEvent( "vmousecancel", event, flags ); } triggerVirtualEvent( "vmousemove", event, flags ); startResetTimer(); } function handleTouchEnd( event ) { if ( blockTouchTriggers ) { return; } disableTouchBindings(); var flags = getVirtualBindingFlags( event.target ), t; triggerVirtualEvent( "vmouseup", event, flags ); if ( !didScroll ) { var ve = triggerVirtualEvent( "vclick", event, flags ); if ( ve && ve.isDefaultPrevented() ) { // The target of the mouse events that follow the touchend // event don't necessarily match the target used during the // touch. This means we need to rely on coordinates for blocking // any click that is generated. t = getNativeEvent( event ).changedTouches[ 0 ]; clickBlockList.push({ touchID: lastTouchID, x: t.clientX, y: t.clientY }); // Prevent any mouse events that follow from triggering // virtual event notifications. blockMouseTriggers = true; } } triggerVirtualEvent( "vmouseout", event, flags); didScroll = false; startResetTimer(); } function hasVirtualBindings( ele ) { var bindings = $.data( ele, dataPropertyName ), k; if ( bindings ) { for ( k in bindings ) { if ( bindings[ k ] ) { return true; } } } return false; } function dummyMouseHandler() {} function getSpecialEventObject( eventType ) { var realType = eventType.substr( 1 ); return { setup: function( data, namespace ) { // If this is the first virtual mouse binding for this element, // add a bindings object to its data. if ( !hasVirtualBindings( this ) ) { $.data( this, dataPropertyName, {} ); } // If setup is called, we know it is the first binding for this // eventType, so initialize the count for the eventType to zero. var bindings = $.data( this, dataPropertyName ); bindings[ eventType ] = true; // If this is the first virtual mouse event for this type, // register a global handler on the document. activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1; if ( activeDocHandlers[ eventType ] === 1 ) { $document.bind( realType, mouseEventCallback ); } // Some browsers, like Opera Mini, won't dispatch mouse/click events // for elements unless they actually have handlers registered on them. // To get around this, we register dummy handlers on the elements. $( this ).bind( realType, dummyMouseHandler ); // For now, if event capture is not supported, we rely on mouse handlers. if ( eventCaptureSupported ) { // If this is the first virtual mouse binding for the document, // register our touchstart handler on the document. activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1; if ( activeDocHandlers[ "touchstart" ] === 1 ) { $document.bind( "touchstart", handleTouchStart ) .bind( "touchend", handleTouchEnd ) // On touch platforms, touching the screen and then dragging your finger // causes the window content to scroll after some distance threshold is // exceeded. On these platforms, a scroll prevents a click event from being // dispatched, and on some platforms, even the touchend is suppressed. To // mimic the suppression of the click event, we need to watch for a scroll // event. Unfortunately, some platforms like iOS don't dispatch scroll // events until *AFTER* the user lifts their finger (touchend). This means // we need to watch both scroll and touchmove events to figure out whether // or not a scroll happenens before the touchend event is fired. .bind( "touchmove", handleTouchMove ) .bind( "scroll", handleScroll ); } } }, teardown: function( data, namespace ) { // If this is the last virtual binding for this eventType, // remove its global handler from the document. --activeDocHandlers[ eventType ]; if ( !activeDocHandlers[ eventType ] ) { $document.unbind( realType, mouseEventCallback ); } if ( eventCaptureSupported ) { // If this is the last virtual mouse binding in existence, // remove our document touchstart listener. --activeDocHandlers[ "touchstart" ]; if ( !activeDocHandlers[ "touchstart" ] ) { $document.unbind( "touchstart", handleTouchStart ) .unbind( "touchmove", handleTouchMove ) .unbind( "touchend", handleTouchEnd ) .unbind( "scroll", handleScroll ); } } var $this = $( this ), bindings = $.data( this, dataPropertyName ); // teardown may be called when an element was // removed from the DOM. If this is the case, // jQuery core may have already stripped the element // of any data bindings so we need to check it before // using it. if ( bindings ) { bindings[ eventType ] = false; } // Unregister the dummy event handler. $this.unbind( realType, dummyMouseHandler ); // If this is the last virtual mouse binding on the // element, remove the binding data from the element. if ( !hasVirtualBindings( this ) ) { $this.removeData( dataPropertyName ); } } }; } // Expose our custom events to the jQuery bind/unbind mechanism. for ( var i = 0; i < virtualEventNames.length; i++ ) { $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] ); } // Add a capture click handler to block clicks. // Note that we require event capture support for this so if the device // doesn't support it, we punt for now and rely solely on mouse events. if ( eventCaptureSupported ) { document.addEventListener( "click", function( e ) { var cnt = clickBlockList.length, target = e.target, x, y, ele, i, o, touchID; if ( cnt ) { x = e.clientX; y = e.clientY; threshold = $.vmouse.clickDistanceThreshold; // The idea here is to run through the clickBlockList to see if // the current click event is in the proximity of one of our // vclick events that had preventDefault() called on it. If we find // one, then we block the click. // // Why do we have to rely on proximity? // // Because the target of the touch event that triggered the vclick // can be different from the target of the click event synthesized // by the browser. The target of a mouse/click event that is syntehsized // from a touch event seems to be implementation specific. For example, // some browsers will fire mouse/click events for a link that is near // a touch event, even though the target of the touchstart/touchend event // says the user touched outside the link. Also, it seems that with most // browsers, the target of the mouse/click event is not calculated until the // time it is dispatched, so if you replace an element that you touched // with another element, the target of the mouse/click will be the new // element underneath that point. // // Aside from proximity, we also check to see if the target and any // of its ancestors were the ones that blocked a click. This is necessary // because of the strange mouse/click target calculation done in the // Android 2.1 browser, where if you click on an element, and there is a // mouse/click handler on one of its ancestors, the target will be the // innermost child of the touched element, even if that child is no where // near the point of touch. ele = target; while ( ele ) { for ( i = 0; i < cnt; i++ ) { o = clickBlockList[ i ]; touchID = 0; if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) || $.data( ele, touchTargetPropertyName ) === o.touchID ) { // XXX: We may want to consider removing matches from the block list // instead of waiting for the reset timer to fire. e.preventDefault(); e.stopPropagation(); return; } } ele = ele.parentNode; } } }, true); } })( jQuery, window, document ); (function( $, window, undefined ) { var $document = $( document ); // add new event shortcuts $.each( ( "touchstart touchmove touchend " + "tap taphold " + "swipe swipeleft swiperight " + "scrollstart scrollstop" ).split( " " ), function( i, name ) { $.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; // jQuery < 1.8 if ( $.attrFn ) { $.attrFn[ name ] = true; } }); var supportTouch = $.mobile.support.touch, scrollEvent = "touchmove scroll", touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove"; function triggerCustomEvent( obj, eventType, event ) { var originalType = event.type; event.type = eventType; $.event.dispatch.call( obj, event ); event.type = originalType; } // also handles scrollstop $.event.special.scrollstart = { enabled: true, setup: function() { var thisObject = this, $this = $( thisObject ), scrolling, timer; function trigger( event, state ) { scrolling = state; triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event ); } // iPhone triggers scroll after a small delay; use touchmove instead $this.bind( scrollEvent, function( event ) { if ( !$.event.special.scrollstart.enabled ) { return; } if ( !scrolling ) { trigger( event, true ); } clearTimeout( timer ); timer = setTimeout( function() { trigger( event, false ); }, 50 ); }); } }; // also handles taphold $.event.special.tap = { tapholdThreshold: 750, setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( "vmousedown", function( event ) { if ( event.which && event.which !== 1 ) { return false; } var origTarget = event.target, origEvent = event.originalEvent, timer; function clearTapTimer() { clearTimeout( timer ); } function clearTapHandlers() { clearTapTimer(); $this.unbind( "vclick", clickHandler ) .unbind( "vmouseup", clearTapTimer ); $document.unbind( "vmousecancel", clearTapHandlers ); } function clickHandler( event ) { clearTapHandlers(); // ONLY trigger a 'tap' event if the start target is // the same as the stop target. if ( origTarget === event.target ) { triggerCustomEvent( thisObject, "tap", event ); } } $this.bind( "vmouseup", clearTapTimer ) .bind( "vclick", clickHandler ); $document.bind( "vmousecancel", clearTapHandlers ); timer = setTimeout( function() { triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) ); }, $.event.special.tap.tapholdThreshold ); }); } }; // also handles swipeleft, swiperight $.event.special.swipe = { scrollSupressionThreshold: 30, // More than this horizontal displacement, and we will suppress scrolling. durationThreshold: 1000, // More time than this, and it isn't a swipe. horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this. verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this. start: function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event; return { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ], origin: $( event.target ) }; }, stop: function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event; return { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ] }; }, handleSwipe: function( start, stop ) { if ( stop.time - start.time < $.event.special.swipe.durationThreshold && Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold && Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) { start.origin.trigger( "swipe" ) .trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" ); } }, setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( touchStartEvent, function( event ) { var start = $.event.special.swipe.start( event ), stop; function moveHandler( event ) { if ( !start ) { return; } stop = $.event.special.swipe.stop( event ); // prevent scrolling if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) { event.preventDefault(); } } $this.bind( touchMoveEvent, moveHandler ) .one( touchStopEvent, function() { $this.unbind( touchMoveEvent, moveHandler ); if ( start && stop ) { $.event.special.swipe.handleSwipe( start, stop ); } start = stop = undefined; }); }); } }; $.each({ scrollstop: "scrollstart", taphold: "tap", swipeleft: "swipe", swiperight: "swipe" }, function( event, sourceEvent ) { $.event.special[ event ] = { setup: function() { $( this ).bind( sourceEvent, $.noop ); } }; }); })( jQuery, this ); // throttled resize event (function( $ ) { $.event.special.throttledresize = { setup: function() { $( this ).bind( "resize", handler ); }, teardown: function() { $( this ).unbind( "resize", handler ); } }; var throttle = 250, handler = function() { curr = ( new Date() ).getTime(); diff = curr - lastCall; if ( diff >= throttle ) { lastCall = curr; $( this ).trigger( "throttledresize" ); } else { if ( heldCall ) { clearTimeout( heldCall ); } // Promise a held call will still execute heldCall = setTimeout( handler, throttle - diff ); } }, lastCall = 0, heldCall, curr, diff; })( jQuery ); (function( $, window ) { var win = $( window ), event_name = "orientationchange", special_event, get_orientation, last_orientation, initial_orientation_is_landscape, initial_orientation_is_default, portrait_map = { "0": true, "180": true }; // It seems that some device/browser vendors use window.orientation values 0 and 180 to // denote the "default" orientation. For iOS devices, and most other smart-phones tested, // the default orientation is always "portrait", but in some Android and RIM based tablets, // the default orientation is "landscape". The following code attempts to use the window // dimensions to figure out what the current orientation is, and then makes adjustments // to the to the portrait_map if necessary, so that we can properly decode the // window.orientation value whenever get_orientation() is called. // // Note that we used to use a media query to figure out what the orientation the browser // thinks it is in: // // initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)"); // // but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1, // where the browser *ALWAYS* applied the landscape media query. This bug does not // happen on iPad. if ( $.support.orientation ) { // Check the window width and height to figure out what the current orientation // of the device is at this moment. Note that we've initialized the portrait map // values to 0 and 180, *AND* we purposely check for landscape so that if we guess // wrong, , we default to the assumption that portrait is the default orientation. // We use a threshold check below because on some platforms like iOS, the iPhone // form-factor can report a larger width than height if the user turns on the // developer console. The actual threshold value is somewhat arbitrary, we just // need to make sure it is large enough to exclude the developer console case. var ww = window.innerWidth || win.width(), wh = window.innerHeight || win.height(), landscape_threshold = 50; initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold; // Now check to see if the current window.orientation is 0 or 180. initial_orientation_is_default = portrait_map[ window.orientation ]; // If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR* // if the initial orientation is portrait, but window.orientation reports 90 or -90, we // need to flip our portrait_map values because landscape is the default orientation for // this device/browser. if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) { portrait_map = { "-90": true, "90": true }; } } $.event.special.orientationchange = $.extend( {}, $.event.special.orientationchange, { setup: function() { // If the event is supported natively, return false so that jQuery // will bind to the event using DOM methods. if ( $.support.orientation && !$.event.special.orientationchange.disabled ) { return false; } // Get the current orientation to avoid initial double-triggering. last_orientation = get_orientation(); // Because the orientationchange event doesn't exist, simulate the // event by testing window dimensions on resize. win.bind( "throttledresize", handler ); }, teardown: function() { // If the event is not supported natively, return false so that // jQuery will unbind the event using DOM methods. if ( $.support.orientation && !$.event.special.orientationchange.disabled ) { return false; } // Because the orientationchange event doesn't exist, unbind the // resize event handler. win.unbind( "throttledresize", handler ); }, add: function( handleObj ) { // Save a reference to the bound event handler. var old_handler = handleObj.handler; handleObj.handler = function( event ) { // Modify event object, adding the .orientation property. event.orientation = get_orientation(); // Call the originally-bound event handler and return its result. return old_handler.apply( this, arguments ); }; } }); // If the event is not supported natively, this handler will be bound to // the window resize event to simulate the orientationchange event. function handler() { // Get the current orientation. var orientation = get_orientation(); if ( orientation !== last_orientation ) { // The orientation has changed, so trigger the orientationchange event. last_orientation = orientation; win.trigger( event_name ); } } // Get the current page orientation. This method is exposed publicly, should it // be needed, as jQuery.event.special.orientationchange.orientation() $.event.special.orientationchange.orientation = get_orientation = function() { var isPortrait = true, elem = document.documentElement; // prefer window orientation to the calculation based on screensize as // the actual screen resize takes place before or after the orientation change event // has been fired depending on implementation (eg android 2.3 is before, iphone after). // More testing is required to determine if a more reliable method of determining the new screensize // is possible when orientationchange is fired. (eg, use media queries + element + opacity) if ( $.support.orientation ) { // if the window orientation registers as 0 or 180 degrees report // portrait, otherwise landscape isPortrait = portrait_map[ window.orientation ]; } else { isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1; } return isPortrait ? "portrait" : "landscape"; }; $.fn[ event_name ] = function( fn ) { return fn ? this.bind( event_name, fn ) : this.trigger( event_name ); }; // jQuery < 1.8 if ( $.attrFn ) { $.attrFn[ event_name ] = true; } }( jQuery, this )); (function( $, undefined ) { $.widget( "mobile.page", $.mobile.widget, { options: { theme: "c", domCache: false, keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')" }, _create: function() { // if false is returned by the callbacks do not create the page if ( this._trigger( "beforecreate" ) === false ) { return false; } this.element .attr( "tabindex", "0" ) .addClass( "ui-page ui-body-" + this.options.theme ); this._on( this.element, { pagebeforehide: "removeContainerBackground", pagebeforeshow: "_handlePageBeforeShow" }); }, _handlePageBeforeShow: function( e ) { this.setContainerBackground(); }, removeContainerBackground: function() { $.mobile.pageContainer.removeClass( "ui-overlay-" + $.mobile.getInheritedTheme( this.element.parent() ) ); }, // set the page container background to the page theme setContainerBackground: function( theme ) { if ( this.options.theme ) { $.mobile.pageContainer.addClass( "ui-overlay-" + ( theme || this.options.theme ) ); } }, keepNativeSelector: function() { var options = this.options, keepNativeDefined = options.keepNative && $.trim( options.keepNative ); if ( keepNativeDefined && options.keepNative !== options.keepNativeDefault ) { return [options.keepNative, options.keepNativeDefault].join( ", " ); } return options.keepNativeDefault; } }); })( jQuery ); (function( $, window, undefined ) { var createHandler = function( sequential ) { // Default to sequential if ( sequential === undefined ) { sequential = true; } return function( name, reverse, $to, $from ) { var deferred = new $.Deferred(), reverseClass = reverse ? " reverse" : "", active = $.mobile.urlHistory.getActive(), toScroll = active.lastScroll || $.mobile.defaultHomeScroll, screenHeight = $.mobile.getScreenHeight(), maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth, none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $.mobile.window.scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(), toPreClass = " ui-page-pre-in", toggleViewportClass = function() { $.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name ); }, scrollPage = function() { // By using scrollTo instead of silentScroll, we can keep things better in order // Just to be precautios, disable scrollstart listening like silentScroll would $.event.special.scrollstart.enabled = false; window.scrollTo( 0, toScroll ); // reenable scrollstart listening like silentScroll would setTimeout( function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, cleanFrom = function() { $from .removeClass( $.mobile.activePageClass + " out in reverse " + name ) .height( "" ); }, startOut = function() { // if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously if ( !sequential ) { doneOut(); } else { $from.animationComplete( doneOut ); } // Set the from page's height and start it transitioning out // Note: setting an explicit height helps eliminate tiling in the transitions $from .height( screenHeight + $.mobile.window.scrollTop() ) .addClass( name + " out" + reverseClass ); }, doneOut = function() { if ( $from && sequential ) { cleanFrom(); } startIn(); }, startIn = function() { // Prevent flickering in phonegap container: see comments at #4024 regarding iOS $to.css( "z-index", -10 ); $to.addClass( $.mobile.activePageClass + toPreClass ); // Send focus to page as it is now display: block $.mobile.focusPage( $to ); // Set to page height $to.height( screenHeight + toScroll ); scrollPage(); // Restores visibility of the new page: added together with $to.css( "z-index", -10 ); $to.css( "z-index", "" ); if ( !none ) { $to.animationComplete( doneIn ); } $to .removeClass( toPreClass ) .addClass( name + " in" + reverseClass ); if ( none ) { doneIn(); } }, doneIn = function() { if ( !sequential ) { if ( $from ) { cleanFrom(); } } $to .removeClass( "out in reverse " + name ) .height( "" ); toggleViewportClass(); // In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition // This ensures we jump to that spot after the fact, if we aren't there already. if ( $.mobile.window.scrollTop() !== toScroll ) { scrollPage(); } deferred.resolve( name, reverse, $to, $from, true ); }; toggleViewportClass(); if ( $from && !none ) { startOut(); } else { doneOut(); } return deferred.promise(); }; }; // generate the handlers from the above var sequentialHandler = createHandler(), simultaneousHandler = createHandler( false ), defaultGetMaxScrollForTransition = function() { return $.mobile.getScreenHeight() * 3; }; // Make our transition handler the public default. $.mobile.defaultTransitionHandler = sequentialHandler; //transition handler dictionary for 3rd party transitions $.mobile.transitionHandlers = { "default": $.mobile.defaultTransitionHandler, "sequential": sequentialHandler, "simultaneous": simultaneousHandler }; $.mobile.transitionFallbacks = {}; // If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified $.mobile._maybeDegradeTransition = function( transition ) { if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) { transition = $.mobile.transitionFallbacks[ transition ]; } return transition; }; // Set the getMaxScrollForTransition to default if no implementation was set by user $.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition; })( jQuery, this ); (function( $, undefined ) { //define vars for interal use var $window = $.mobile.window, $html = $( 'html' ), $head = $( 'head' ), // NOTE: path extensions dependent on core attributes. Moved here to remove deps from // $.mobile.path definition path = $.extend($.mobile.path, { //return the substring of a filepath before the sub-page key, for making a server request getFilePath: function( path ) { var splitkey = '&' + $.mobile.subPageUrlKey; return path && path.split( splitkey )[0].split( dialogHashKey )[0]; }, //check if the specified url refers to the first page in the main application document. isFirstPageUrl: function( url ) { // We only deal with absolute paths. var u = path.parseUrl( path.makeUrlAbsolute( url, this.documentBase ) ), // Does the url have the same path as the document? samePath = u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ), // Get the first page element. fp = $.mobile.firstPage, // Get the id of the first page element if it has one. fpId = fp && fp[0] ? fp[0].id : undefined; // The url refers to the first page if the path matches the document and // it either has no hash value, or the hash is exactly equal to the id of the // first page element. return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) ); }, // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR // requests if the document doing the request was loaded via the file:// protocol. // This is usually to allow the application to "phone home" and fetch app specific // data. We normally let the browser handle external/cross-domain urls, but if the // allowCrossDomainPages option is true, we will allow cross-domain http/https // requests to go through our page loading logic. isPermittedCrossDomainRequest: function( docUrl, reqUrl ) { return $.mobile.allowCrossDomainPages && docUrl.protocol === "file:" && reqUrl.search( /^https?:/ ) !== -1; } }), // used to track last vclicked element to make sure its value is added to form data $lastVClicked = null, //will be defined when a link is clicked and given an active class $activeClickedLink = null, // resolved on domready domreadyDeferred = $.Deferred(), //urlHistory is purely here to make guesses at whether the back or forward button was clicked //and provide an appropriate transition urlHistory = $.mobile.navigate.history, //define first selector to receive focus when a page is shown focusable = "[tabindex],a,button:visible,select:visible,input", //queue to hold simultanious page transitions pageTransitionQueue = [], //indicates whether or not page is in process of transitioning isPageTransitioning = false, //nonsense hash change key for dialogs, so they create a history entry dialogHashKey = "&ui-state=dialog", //existing base tag? $base = $head.children( "base" ), //tuck away the original document URL minus any fragment. documentUrl = path.documentUrl, //if the document has an embedded base tag, documentBase is set to its //initial value. If a base tag does not exist, then we default to the documentUrl. documentBase = path.documentBase, //cache the comparison once. documentBaseDiffers = path.documentBaseDiffers, getScreenHeight = $.mobile.getScreenHeight; //base element management, defined depending on dynamic base tag support var base = $.support.dynamicBaseTag ? { //define base element, for use in routing asset urls that are referenced in Ajax-requested markup element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ), //set the generated BASE element's href attribute to a new page's base path set: function( href ) { href = path.parseUrl(href).hrefNoHash; base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) ); }, //set the generated BASE element's href attribute to a new page's base path reset: function() { base.element.attr( "href", documentBase.hrefNoSearch ); } } : undefined; //return the original document url $.mobile.getDocumentUrl = path.getDocumentUrl; //return the original document base url $.mobile.getDocumentBase = path.getDocumentBase; /* internal utility functions */ // NOTE Issue #4950 Android phonegap doesn't navigate back properly // when a full page refresh has taken place. It appears that hashchange // and replacestate history alterations work fine but we need to support // both forms of history traversal in our code that uses backward history // movement $.mobile.back = function() { var nav = window.navigator; // if the setting is on and the navigator object is // available use the phonegap navigation capability if( this.phonegapNavigationEnabled && nav && nav.app && nav.app.backHistory ){ nav.app.backHistory(); } else { window.history.back(); } }; //direct focus to the page title, or otherwise first focusable element $.mobile.focusPage = function ( page ) { var autofocus = page.find( "[autofocus]" ), pageTitle = page.find( ".ui-title:eq(0)" ); if ( autofocus.length ) { autofocus.focus(); return; } if ( pageTitle.length ) { pageTitle.focus(); } else{ page.focus(); } }; //remove active classes after page transition or error function removeActiveLinkClass( forceRemoval ) { if ( !!$activeClickedLink && ( !$activeClickedLink.closest( "." + $.mobile.activePageClass ).length || forceRemoval ) ) { $activeClickedLink.removeClass( $.mobile.activeBtnClass ); } $activeClickedLink = null; } function releasePageTransitionLock() { isPageTransitioning = false; if ( pageTransitionQueue.length > 0 ) { $.mobile.changePage.apply( null, pageTransitionQueue.pop() ); } } // Save the last scroll distance per page, before it is hidden var setLastScrollEnabled = true, setLastScroll, delayedSetLastScroll; setLastScroll = function() { // this barrier prevents setting the scroll value based on the browser // scrolling the window based on a hashchange if ( !setLastScrollEnabled ) { return; } var active = $.mobile.urlHistory.getActive(); if ( active ) { var lastScroll = $window.scrollTop(); // Set active page's lastScroll prop. // If the location we're scrolling to is less than minScrollBack, let it go. active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll; } }; // bind to scrollstop to gather scroll position. The delay allows for the hashchange // event to fire and disable scroll recording in the case where the browser scrolls // to the hash targets location (sometimes the top of the page). once pagechange fires // getLastScroll is again permitted to operate delayedSetLastScroll = function() { setTimeout( setLastScroll, 100 ); }; // disable an scroll setting when a hashchange has been fired, this only works // because the recording of the scroll position is delayed for 100ms after // the browser might have changed the position because of the hashchange $window.bind( $.support.pushState ? "popstate" : "hashchange", function() { setLastScrollEnabled = false; }); // handle initial hashchange from chrome :( $window.one( $.support.pushState ? "popstate" : "hashchange", function() { setLastScrollEnabled = true; }); // wait until the mobile page container has been determined to bind to pagechange $window.one( "pagecontainercreate", function() { // once the page has changed, re-enable the scroll recording $.mobile.pageContainer.bind( "pagechange", function() { setLastScrollEnabled = true; // remove any binding that previously existed on the get scroll // which may or may not be different than the scroll element determined for // this page previously $window.unbind( "scrollstop", delayedSetLastScroll ); // determine and bind to the current scoll element which may be the window // or in the case of touch overflow the element with touch overflow $window.bind( "scrollstop", delayedSetLastScroll ); }); }); // bind to scrollstop for the first page as "pagechange" won't be fired in that case $window.bind( "scrollstop", delayedSetLastScroll ); // No-op implementation of transition degradation $.mobile._maybeDegradeTransition = $.mobile._maybeDegradeTransition || function( transition ) { return transition; }; //function for transitioning between two existing pages function transitionPages( toPage, fromPage, transition, reverse ) { if ( fromPage ) { //trigger before show/hide events fromPage.data( "mobile-page" )._trigger( "beforehide", null, { nextPage: toPage } ); } toPage.data( "mobile-page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } ); //clear page loader $.mobile.hidePageLoadingMsg(); transition = $.mobile._maybeDegradeTransition( transition ); //find the transition handler for the specified transition. If there //isn't one in our transitionHandlers dictionary, use the default one. //call the handler immediately to kick-off the transition. var th = $.mobile.transitionHandlers[ transition || "default" ] || $.mobile.defaultTransitionHandler, promise = th( transition, reverse, toPage, fromPage ); promise.done(function() { //trigger show/hide events if ( fromPage ) { fromPage.data( "mobile-page" )._trigger( "hide", null, { nextPage: toPage } ); } //trigger pageshow, define prevPage as either fromPage or empty jQuery obj toPage.data( "mobile-page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } ); }); return promise; } //simply set the active page's minimum height to screen height, depending on orientation $.mobile.resetActivePageHeight = function resetActivePageHeight( height ) { var aPage = $( "." + $.mobile.activePageClass ), aPagePadT = parseFloat( aPage.css( "padding-top" ) ), aPagePadB = parseFloat( aPage.css( "padding-bottom" ) ), aPageBorderT = parseFloat( aPage.css( "border-top-width" ) ), aPageBorderB = parseFloat( aPage.css( "border-bottom-width" ) ); height = ( typeof height === "number" )? height : getScreenHeight(); aPage.css( "min-height", height - aPagePadT - aPagePadB - aPageBorderT - aPageBorderB ); }; //shared page enhancements function enhancePage( $page, role ) { // If a role was specified, make sure the data-role attribute // on the page element is in sync. if ( role ) { $page.attr( "data-" + $.mobile.ns + "role", role ); } //run page plugin $page.page(); } // determine the current base url function findBaseWithDefault() { var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) ); return closestBase || documentBase.hrefNoHash; } /* exposed $.mobile methods */ //animation complete callback $.fn.animationComplete = function( callback ) { if ( $.support.cssTransitions ) { return $( this ).one( 'webkitAnimationEnd animationend', callback ); } else{ // defer execution for consistency between webkit/non webkit setTimeout( callback, 0 ); return $( this ); } }; //expose path object on $.mobile $.mobile.path = path; //expose base object on $.mobile $.mobile.base = base; //history stack $.mobile.urlHistory = urlHistory; $.mobile.dialogHashKey = dialogHashKey; //enable cross-domain page support $.mobile.allowCrossDomainPages = false; $.mobile._bindPageRemove = function() { var page = $( this ); // when dom caching is not enabled or the page is embedded bind to remove the page on hide if ( !page.data( "mobile-page" ).options.domCache && page.is( ":jqmData(external-page='true')" ) ) { page.bind( 'pagehide.remove', function( e ) { var $this = $( this ), prEvent = new $.Event( "pageremove" ); $this.trigger( prEvent ); if ( !prEvent.isDefaultPrevented() ) { $this.removeWithDependents(); } }); } }; // Load a page into the DOM. $.mobile.loadPage = function( url, options ) { // This function uses deferred notifications to let callers // know when the page is done loading, or if an error has occurred. var deferred = $.Deferred(), // The default loadPage options with overrides specified by // the caller. settings = $.extend( {}, $.mobile.loadPage.defaults, options ), // The DOM element for the page after it has been loaded. page = null, // If the reloadPage option is true, and the page is already // in the DOM, dupCachedPage will be set to the page element // so that it can be removed after the new version of the // page is loaded off the network. dupCachedPage = null, // The absolute version of the URL passed into the function. This // version of the URL may contain dialog/subpage params in it. absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() ); // If the caller provided data, and we're using "get" request, // append the data to the URL. if ( settings.data && settings.type === "get" ) { absUrl = path.addSearchParams( absUrl, settings.data ); settings.data = undefined; } // If the caller is using a "post" request, reloadPage must be true if ( settings.data && settings.type === "post" ) { settings.reloadPage = true; } // The absolute version of the URL minus any dialog/subpage params. // In otherwords the real URL of the page to be loaded. var fileUrl = path.getFilePath( absUrl ), // The version of the Url actually stored in the data-url attribute of // the page. For embedded pages, it is just the id of the page. For pages // within the same domain as the document base, it is the site relative // path. For cross-domain pages (Phone Gap only) the entire absolute Url // used to load the page. dataUrl = path.convertUrlToDataUrl( absUrl ); // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // Check to see if the page already exists in the DOM. // NOTE do _not_ use the :jqmData psuedo selector because parenthesis // are a valid url char and it breaks on the first occurence page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" ); // If we failed to find the page, check to see if the url is a // reference to an embedded page. If so, it may have been dynamically // injected by a developer, in which case it would be lacking a data-url // attribute and in need of enhancement. if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) { page = settings.pageContainer.children( "#" + dataUrl ) .attr( "data-" + $.mobile.ns + "url", dataUrl ) .jqmData( "url", dataUrl ); } // If we failed to find a page in the DOM, check the URL to see if it // refers to the first page in the application. If it isn't a reference // to the first page and refers to non-existent embedded page, error out. if ( page.length === 0 ) { if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) { // Check to make sure our cached-first-page is actually // in the DOM. Some user deployed apps are pruning the first // page from the DOM for various reasons, we check for this // case here because we don't want a first-page with an id // falling through to the non-existent embedded page error // case. If the first-page is not in the DOM, then we let // things fall through to the ajax loading code below so // that it gets reloaded. if ( $.mobile.firstPage.parent().length ) { page = $( $.mobile.firstPage ); } } else if ( path.isEmbeddedPage( fileUrl ) ) { deferred.reject( absUrl, options ); return deferred.promise(); } } // If the page we are interested in is already in the DOM, // and the caller did not indicate that we should force a // reload of the file, we are done. Otherwise, track the // existing page as a duplicated. if ( page.length ) { if ( !settings.reloadPage ) { enhancePage( page, settings.role ); deferred.resolve( absUrl, options, page ); //if we are reloading the page make sure we update the base if its not a prefetch if( base && !options.prefetch ){ base.set(url); } return deferred.promise(); } dupCachedPage = page; } var mpc = settings.pageContainer, pblEvent = new $.Event( "pagebeforeload" ), triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings }; // Let listeners know we're about to load a page. mpc.trigger( pblEvent, triggerData ); // If the default behavior is prevented, stop here! if ( pblEvent.isDefaultPrevented() ) { return deferred.promise(); } if ( settings.showLoadMsg ) { // This configurable timeout allows cached pages a brief delay to load without showing a message var loadMsgDelay = setTimeout(function() { $.mobile.showPageLoadingMsg(); }, settings.loadMsgDelay ), // Shared logic for clearing timeout and removing message. hideMsg = function() { // Stop message show timer clearTimeout( loadMsgDelay ); // Hide loading message $.mobile.hidePageLoadingMsg(); }; } // Reset base to the default document base. // only reset if we are not prefetching if ( base && ( typeof options === "undefined" || typeof options.prefetch === "undefined" ) ) { base.reset(); } if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) { deferred.reject( absUrl, options ); } else { // Load the new page. $.ajax({ url: fileUrl, type: settings.type, data: settings.data, contentType: settings.contentType, dataType: "html", success: function( html, textStatus, xhr ) { //pre-parse html to check for a data-url, //use it as the new fileUrl, base path, etc var all = $( "<div></div>" ), //page title regexp newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1, // TODO handle dialogs again pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ), dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" ); // data-url must be provided for the base tag so resource requests can be directed to the // correct url. loading into a temprorary element makes these requests immediately if ( pageElemRegex.test( html ) && RegExp.$1 && dataUrlRegex.test( RegExp.$1 ) && RegExp.$1 ) { url = fileUrl = path.getFilePath( $( "<div>" + RegExp.$1 + "</div>" ).text() ); } //dont update the base tag if we are prefetching if ( base && ( typeof options === "undefined" || typeof options.prefetch === "undefined" )) { base.set( fileUrl ); } //workaround to allow scripts to execute when included in page divs all.get( 0 ).innerHTML = html; page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first(); //if page elem couldn't be found, create one and insert the body element's contents if ( !page.length ) { page = $( "<div data-" + $.mobile.ns + "role='page'>" + ( html.split( /<\/?body[^>]*>/gmi )[1] || "" ) + "</div>" ); } if ( newPageTitle && !page.jqmData( "title" ) ) { if ( ~newPageTitle.indexOf( "&" ) ) { newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text(); } page.jqmData( "title", newPageTitle ); } //rewrite src and href attrs to use a base url if ( !$.support.dynamicBaseTag ) { var newPath = path.get( fileUrl ); page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() { var thisAttr = $( this ).is( '[href]' ) ? 'href' : $( this ).is( '[src]' ) ? 'src' : 'action', thisUrl = $( this ).attr( thisAttr ); // XXX_jblas: We need to fix this so that it removes the document // base URL, and then prepends with the new page URL. //if full path exists and is same, chop it - helps IE out thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' ); if ( !/^(\w+:|#|\/)/.test( thisUrl ) ) { $( this ).attr( thisAttr, newPath + thisUrl ); } }); } //append to page and enhance // TODO taging a page with external to make sure that embedded pages aren't removed // by the various page handling code is bad. Having page handling code in many // places is bad. Solutions post 1.0 page .attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) ) .attr( "data-" + $.mobile.ns + "external-page", true ) .appendTo( settings.pageContainer ); // wait for page creation to leverage options defined on widget page.one( 'pagecreate', $.mobile._bindPageRemove ); enhancePage( page, settings.role ); // Enhancing the page may result in new dialogs/sub pages being inserted // into the DOM. If the original absUrl refers to a sub-page, that is the // real page we are interested in. if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) { page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" ); } // Remove loading message. if ( settings.showLoadMsg ) { hideMsg(); } // Add the page reference and xhr to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; triggerData.page = page; // Let listeners know the page loaded successfully. settings.pageContainer.trigger( "pageload", triggerData ); deferred.resolve( absUrl, options, page, dupCachedPage ); }, error: function( xhr, textStatus, errorThrown ) { //set base back to current path if ( base ) { base.set( path.get() ); } // Add error info to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; triggerData.errorThrown = errorThrown; var plfEvent = new $.Event( "pageloadfailed" ); // Let listeners know the page load failed. settings.pageContainer.trigger( plfEvent, triggerData ); // If the default behavior is prevented, stop here! // Note that it is the responsibility of the listener/handler // that called preventDefault(), to resolve/reject the // deferred object within the triggerData. if ( plfEvent.isDefaultPrevented() ) { return; } // Remove loading message. if ( settings.showLoadMsg ) { // Remove loading message. hideMsg(); // show error message $.mobile.showPageLoadingMsg( $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true ); // hide after delay setTimeout( $.mobile.hidePageLoadingMsg, 1500 ); } deferred.reject( absUrl, options ); } }); } return deferred.promise(); }; $.mobile.loadPage.defaults = { type: "get", data: undefined, reloadPage: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. showLoadMsg: false, pageContainer: undefined, loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message. }; // Show a specific page in the page container. $.mobile.changePage = function( toPage, options ) { // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition to // service the request. if ( isPageTransitioning ) { pageTransitionQueue.unshift( arguments ); return; } var settings = $.extend( {}, $.mobile.changePage.defaults, options ), isToPageString; // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // Make sure we have a fromPage. settings.fromPage = settings.fromPage || $.mobile.activePage; isToPageString = (typeof toPage === "string"); var mpc = settings.pageContainer, pbcEvent = new $.Event( "pagebeforechange" ), triggerData = { toPage: toPage, options: settings }; // NOTE: preserve the original target as the dataUrl value will be simplified // eg, removing ui-state, and removing query params from the hash // this is so that users who want to use query params have access to them // in the event bindings for the page life cycle See issue #5085 if ( isToPageString ) { // if the toPage is a string simply convert it triggerData.absUrl = path.makeUrlAbsolute( toPage, findBaseWithDefault() ); } else { // if the toPage is a jQuery object grab the absolute url stored // in the loadPage callback where it exists triggerData.absUrl = toPage.data( 'absUrl' ); } // Let listeners know we're about to change the current page. mpc.trigger( pbcEvent, triggerData ); // If the default behavior is prevented, stop here! if ( pbcEvent.isDefaultPrevented() ) { return; } // We allow "pagebeforechange" observers to modify the toPage in the trigger // data to allow for redirects. Make sure our toPage is updated. // // We also need to re-evaluate whether it is a string, because an object can // also be replaced by a string toPage = triggerData.toPage; isToPageString = (typeof toPage === "string"); // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; // If the caller passed us a url, call loadPage() // to make sure it is loaded into the DOM. We'll listen // to the promise object it returns so we know when // it is done loading or if an error ocurred. if ( isToPageString ) { // preserve the original target as the dataUrl value will be simplified // eg, removing ui-state, and removing query params from the hash // this is so that users who want to use query params have access to them // in the event bindings for the page life cycle See issue #5085 settings.target = toPage; $.mobile.loadPage( toPage, settings ) .done(function( url, options, newPage, dupCachedPage ) { isPageTransitioning = false; options.duplicateCachedPage = dupCachedPage; // store the original absolute url so that it can be provided // to events in the triggerData of the subsequent changePage call newPage.data( 'absUrl', triggerData.absUrl ); $.mobile.changePage( newPage, options ); }) .fail(function( url, options ) { //clear out the active button state removeActiveLinkClass( true ); //release transition lock so navigation is free again releasePageTransitionLock(); settings.pageContainer.trigger( "pagechangefailed", triggerData ); }); return; } // If we are going to the first-page of the application, we need to make // sure settings.dataUrl is set to the application document url. This allows // us to avoid generating a document url with an id hash in the case where the // first-page of the document has an id attribute specified. if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) { settings.dataUrl = documentUrl.hrefNoHash; } // The caller passed us a real page DOM element. Update our // internal state and then trigger a transition to the page. var fromPage = settings.fromPage, url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ), // The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path pageUrl = url, fileUrl = path.getFilePath( url ), active = urlHistory.getActive(), activeIsInitialPage = urlHistory.activeIndex === 0, historyDir = 0, pageTitle = document.title, isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog"; // By default, we prevent changePage requests when the fromPage and toPage // are the same element, but folks that generate content manually/dynamically // and reuse pages want to be able to transition to the same page. To allow // this, they will need to change the default value of allowSamePageTransition // to true, *OR*, pass it in as an option when they manually call changePage(). // It should be noted that our default transition animations assume that the // formPage and toPage are different elements, so they may behave unexpectedly. // It is up to the developer that turns on the allowSamePageTransitiona option // to either turn off transition animations, or make sure that an appropriate // animation transition is used. if ( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) { isPageTransitioning = false; mpc.trigger( "pagechange", triggerData ); // Even if there is no page change to be done, we should keep the urlHistory in sync with the hash changes if ( settings.fromHashChange ) { urlHistory.direct({ url: url }); } return; } // We need to make sure the page we are given has already been enhanced. enhancePage( toPage, settings.role ); // If the changePage request was sent from a hashChange event, check to see if the // page is already within the urlHistory stack. If so, we'll assume the user hit // the forward/back button and will try to match the transition accordingly. if ( settings.fromHashChange ) { historyDir = options.direction === "back" ? -1 : 1; } // Kill the keyboard. // XXX_jblas: We need to stop crawling the entire document to kill focus. Instead, // we should be tracking focus with a delegate() handler so we already have // the element in hand at this point. // Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement // is undefined when we are in an IFrame. try { if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== 'body' ) { $( document.activeElement ).blur(); } else { $( "input:focus, textarea:focus, select:focus" ).blur(); } } catch( e ) {} // Record whether we are at a place in history where a dialog used to be - if so, do not add a new history entry and do not change the hash either var alreadyThere = false; // If we're displaying the page as a dialog, we don't want the url // for the dialog content to be used in the hash. Instead, we want // to append the dialogHashKey to the url of the current page. if ( isDialog && active ) { // on the initial page load active.url is undefined and in that case should // be an empty string. Moving the undefined -> empty string back into // urlHistory.addNew seemed imprudent given undefined better represents // the url state // If we are at a place in history that once belonged to a dialog, reuse // this state without adding to urlHistory and without modifying the hash. // However, if a dialog is already displayed at this point, and we're // about to display another dialog, then we must add another hash and // history entry on top so that one may navigate back to the original dialog if ( active.url && active.url.indexOf( dialogHashKey ) > -1 && $.mobile.activePage && !$.mobile.activePage.is( ".ui-dialog" ) && urlHistory.activeIndex > 0 ) { settings.changeHash = false; alreadyThere = true; } // Normally, we tack on a dialog hash key, but if this is the location of a stale dialog, // we reuse the URL from the entry url = ( active.url || "" ); // account for absolute urls instead of just relative urls use as hashes if( !alreadyThere && url.indexOf("#") > -1 ) { url += dialogHashKey; } else { url += "#" + dialogHashKey; } // tack on another dialogHashKey if this is the same as the initial hash // this makes sure that a history entry is created for this dialog if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) { url += dialogHashKey; } } // if title element wasn't found, try the page div data attr too // If this is a deep-link or a reload ( active === undefined ) then just use pageTitle var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children( ":jqmData(role='header')" ).find( ".ui-title" ).text(); if ( !!newPageTitle && pageTitle === document.title ) { pageTitle = newPageTitle; } if ( !toPage.jqmData( "title" ) ) { toPage.jqmData( "title", pageTitle ); } // Make sure we have a transition defined. settings.transition = settings.transition || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition ); //add page to history stack if it's not back or forward if ( !historyDir && alreadyThere ) { urlHistory.getActive().pageUrl = pageUrl; } // Set the location hash. if ( url && !settings.fromHashChange ) { var params; // rebuilding the hash here since we loose it earlier on // TODO preserve the originally passed in path if( !path.isPath( url ) && url.indexOf( "#" ) < 0 ) { url = "#" + url; } // TODO the property names here are just silly params = { transition: settings.transition, title: pageTitle, pageUrl: pageUrl, role: settings.role }; if ( settings.changeHash !== false && $.mobile.hashListeningEnabled ) { $.mobile.navigate( url, params, true); } else if ( toPage[ 0 ] !== $.mobile.firstPage[ 0 ] ) { $.mobile.navigate.history.add( url, params ); } } //set page title document.title = pageTitle; //set "toPage" as activePage $.mobile.activePage = toPage; // If we're navigating back in the URL history, set reverse accordingly. settings.reverse = settings.reverse || historyDir < 0; transitionPages( toPage, fromPage, settings.transition, settings.reverse ) .done(function( name, reverse, $to, $from, alreadyFocused ) { removeActiveLinkClass(); //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden if ( settings.duplicateCachedPage ) { settings.duplicateCachedPage.remove(); } // Send focus to the newly shown page. Moved from promise .done binding in transitionPages // itself to avoid ie bug that reports offsetWidth as > 0 (core check for visibility) // despite visibility: hidden addresses issue #2965 // https://github.com/jquery/jquery-mobile/issues/2965 if ( !alreadyFocused ) { $.mobile.focusPage( toPage ); } releasePageTransitionLock(); mpc.trigger( "pagechange", triggerData ); }); }; $.mobile.changePage.defaults = { transition: undefined, reverse: false, changeHash: true, fromHashChange: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. duplicateCachedPage: undefined, pageContainer: undefined, showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage dataUrl: undefined, fromPage: undefined, allowSamePageTransition: false }; /* Event Bindings - hashchange, submit, and click */ function findClosestLink( ele ) { while ( ele ) { // Look for the closest element with a nodeName of "a". // Note that we are checking if we have a valid nodeName // before attempting to access it. This is because the // node we get called with could have originated from within // an embedded SVG document where some symbol instance elements // don't have nodeName defined on them, or strings are of type // SVGAnimatedString. if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() === "a" ) { break; } ele = ele.parentNode; } return ele; } // The base URL for any given element depends on the page it resides in. function getClosestBaseUrl( ele ) { // Find the closest page and extract out its url. var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ), base = documentBase.hrefNoHash; if ( !url || !path.isPath( url ) ) { url = base; } return path.makeUrlAbsolute( url, base); } //The following event bindings should be bound after mobileinit has been triggered //the following deferred is resolved in the init file $.mobile.navreadyDeferred = $.Deferred(); $.mobile._registerInternalEvents = function() { var getAjaxFormData = function( $form, calculateOnly ) { var url, ret = true, formData, vclickedName, method; if ( !$.mobile.ajaxEnabled || // test that the form is, itself, ajax false $form.is( ":jqmData(ajax='false')" ) || // test that $.mobile.ignoreContentEnabled is set and // the form or one of it's parents is ajax=false !$form.jqmHijackable().length || $form.attr( "target" ) ) { return false; } url = $form.attr( "action" ); method = ( $form.attr( "method" ) || "get" ).toLowerCase(); // If no action is specified, browsers default to using the // URL of the document containing the form. Since we dynamically // pull in pages from external documents, the form should submit // to the URL for the source document of the page containing // the form. if ( !url ) { // Get the @data-url for the page containing the form. url = getClosestBaseUrl( $form ); // NOTE: If the method is "get", we need to strip off the query string // because it will get replaced with the new form data. See issue #5710. if ( method === "get" ) { url = path.parseUrl( url ).hrefNoSearch; } if ( url === documentBase.hrefNoHash ) { // The url we got back matches the document base, // which means the page must be an internal/embedded page, // so default to using the actual document url as a browser // would. url = documentUrl.hrefNoSearch; } } url = path.makeUrlAbsolute( url, getClosestBaseUrl( $form ) ); if ( ( path.isExternal( url ) && !path.isPermittedCrossDomainRequest( documentUrl, url ) ) ) { return false; } if ( !calculateOnly ) { formData = $form.serializeArray(); if ( $lastVClicked && $lastVClicked[ 0 ].form === $form[ 0 ] ) { vclickedName = $lastVClicked.attr( "name" ); if ( vclickedName ) { // Make sure the last clicked element is included in the form $.each( formData, function( key, value ) { if ( value.name === vclickedName ) { // Unset vclickedName - we've found it in the serialized data already vclickedName = ""; return false; } }); if ( vclickedName ) { formData.push( { name: vclickedName, value: $lastVClicked.attr( "value" ) } ); } } } ret = { url: url, options: { type: method, data: $.param( formData ), transition: $form.jqmData( "transition" ), reverse: $form.jqmData( "direction" ) === "reverse", reloadPage: true } }; } return ret; }; //bind to form submit events, handle with Ajax $.mobile.document.delegate( "form", "submit", function( event ) { var formData = getAjaxFormData( $( this ) ); if ( formData ) { $.mobile.changePage( formData.url, formData.options ); event.preventDefault(); } }); //add active state on vclick $.mobile.document.bind( "vclick", function( event ) { var $btn, btnEls, target = event.target, needClosest = false; // if this isn't a left click we don't care. Its important to note // that when the virtual event is generated it will create the which attr if ( event.which > 1 || !$.mobile.linkBindingEnabled ) { return; } // Record that this element was clicked, in case we need it for correct // form submission during the "submit" handler above $lastVClicked = $( target ); // Try to find a target element to which the active class will be applied if ( $.data( target, "mobile-button" ) ) { // If the form will not be submitted via AJAX, do not add active class if ( !getAjaxFormData( $( target ).closest( "form" ), true ) ) { return; } // We will apply the active state to this button widget - the parent // of the input that was clicked will have the associated data if ( target.parentNode ) { target = target.parentNode; } } else { target = findClosestLink( target ); if ( !( target && path.parseUrl( target.getAttribute( "href" ) || "#" ).hash !== "#" ) ) { return; } // TODO teach $.mobile.hijackable to operate on raw dom elements so the // link wrapping can be avoided if ( !$( target ).jqmHijackable().length ) { return; } } // Avoid calling .closest by using the data set during .buttonMarkup() // List items have the button data in the parent of the element clicked if ( !!~target.className.indexOf( "ui-link-inherit" ) ) { if ( target.parentNode ) { btnEls = $.data( target.parentNode, "buttonElements" ); } // Otherwise, look for the data on the target itself } else { btnEls = $.data( target, "buttonElements" ); } // If found, grab the button's outer element if ( btnEls ) { target = btnEls.outer; } else { needClosest = true; } $btn = $( target ); // If the outer element wasn't found by the our heuristics, use .closest() if ( needClosest ) { $btn = $btn.closest( ".ui-btn" ); } if ( $btn.length > 0 && !$btn.hasClass( "ui-disabled" ) ) { removeActiveLinkClass( true ); $activeClickedLink = $btn; $activeClickedLink.addClass( $.mobile.activeBtnClass ); } }); // click routing - direct to HTTP or Ajax, accordingly $.mobile.document.bind( "click", function( event ) { if ( !$.mobile.linkBindingEnabled || event.isDefaultPrevented() ) { return; } var link = findClosestLink( event.target ), $link = $( link ), httpCleanup; // If there is no link associated with the click or its not a left // click we want to ignore the click // TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping // can be avoided if ( !link || event.which > 1 || !$link.jqmHijackable().length ) { return; } //remove active link class if external (then it won't be there if you come back) httpCleanup = function() { window.setTimeout(function() { removeActiveLinkClass( true ); }, 200 ); }; //if there's a data-rel=back attr, go back in history if ( $link.is( ":jqmData(rel='back')" ) ) { $.mobile.back(); return false; } var baseUrl = getClosestBaseUrl( $link ), //get href, if defined, otherwise default to empty hash href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl ); //if ajax is disabled, exit early if ( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ) { httpCleanup(); //use default click handling return; } // XXX_jblas: Ideally links to application pages should be specified as // an url to the application document with a hash that is either // the site relative path or id to the page. But some of the // internal code that dynamically generates sub-pages for nested // lists and select dialogs, just write a hash in the link they // create. This means the actual URL path is based on whatever // the current value of the base tag is at the time this code // is called. For now we are just assuming that any url with a // hash in it is an application page reference. if ( href.search( "#" ) !== -1 ) { href = href.replace( /[^#]*#/, "" ); if ( !href ) { //link was an empty hash meant purely //for interaction, so we ignore it. event.preventDefault(); return; } else if ( path.isPath( href ) ) { //we have apath so make it the href we want to load. href = path.makeUrlAbsolute( href, baseUrl ); } else { //we have a simple id so use the documentUrl as its base. href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash ); } } // Should we handle this link, or let the browser deal with it? var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ), // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR // requests if the document doing the request was loaded via the file:// protocol. // This is usually to allow the application to "phone home" and fetch app specific // data. We normally let the browser handle external/cross-domain urls, but if the // allowCrossDomainPages option is true, we will allow cross-domain http/https // requests to go through our page loading logic. //check for protocol or rel and its not an embedded page //TODO overlap in logic from isExternal, rel=external check should be // moved into more comprehensive isExternalLink isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !path.isPermittedCrossDomainRequest( documentUrl, href ) ); if ( isExternal ) { httpCleanup(); //use default click handling return; } //use ajax var transition = $link.jqmData( "transition" ), reverse = $link.jqmData( "direction" ) === "reverse" || // deprecated - remove by 1.0 $link.jqmData( "back" ), //this may need to be more specific as we use data-rel more role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined; $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role, link: $link } ); event.preventDefault(); }); //prefetch pages when anchors with data-prefetch are encountered $.mobile.document.delegate( ".ui-page", "pageshow.prefetch", function() { var urls = []; $( this ).find( "a:jqmData(prefetch)" ).each(function() { var $link = $( this ), url = $link.attr( "href" ); if ( url && $.inArray( url, urls ) === -1 ) { urls.push( url ); $.mobile.loadPage( url, { role: $link.attr( "data-" + $.mobile.ns + "rel" ),prefetch: true } ); } }); }); $.mobile._handleHashChange = function( url, data ) { //find first page via hash var to = path.stripHash(url), //transition is false if it's the first page, undefined otherwise (and may be overridden by default) transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined, // default options for the changPage calls made after examining the current state // of the page and the hash, NOTE that the transition is derived from the previous // history entry changePageOptions = { changeHash: false, fromHashChange: true, reverse: data.direction === "back" }; $.extend( changePageOptions, data, { transition: (urlHistory.getLast() || {}).transition || transition }); // special case for dialogs if ( urlHistory.activeIndex > 0 && to.indexOf( dialogHashKey ) > -1 && urlHistory.initialDst !== to ) { // If current active page is not a dialog skip the dialog and continue // in the same direction if ( $.mobile.activePage && !$.mobile.activePage.is( ".ui-dialog" ) ) { //determine if we're heading forward or backward and continue accordingly past //the current dialog if( data.direction === "back" ) { $.mobile.back(); } else { window.history.forward(); } // prevent changePage call return; } else { // if the current active page is a dialog and we're navigating // to a dialog use the dialog objected saved in the stack to = data.pageUrl; var active = $.mobile.urlHistory.getActive(); // make sure to set the role, transition and reversal // as most of this is lost by the domCache cleaning $.extend( changePageOptions, { role: active.role, transition: active.transition, reverse: data.direction === "back" }); } } //if to is defined, load it if ( to ) { // At this point, 'to' can be one of 3 things, a cached page element from // a history stack entry, an id, or site-relative/absolute URL. If 'to' is // an id, we need to resolve it against the documentBase, not the location.href, // since the hashchange could've been the result of a forward/backward navigation // that crosses from an external page/dialog to an internal page/dialog. to = !path.isPath( to ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to; // If we're about to go to an initial URL that contains a reference to a non-existent // internal page, go to the first page instead. We know that the initial hash refers to a // non-existent page, because the initial hash did not end up in the initial urlHistory entry if ( to === path.makeUrlAbsolute( '#' + urlHistory.initialDst, documentBase ) && urlHistory.stack.length && urlHistory.stack[0].url !== urlHistory.initialDst.replace( dialogHashKey, "" ) ) { to = $.mobile.firstPage; } $.mobile.changePage( to, changePageOptions ); } else { //there's no hash, go to the first page in the dom $.mobile.changePage( $.mobile.firstPage, changePageOptions ); } }; // TODO roll the logic here into the handleHashChange method $window.bind( "navigate", function( e, data ) { var url; if ( e.originalEvent && e.originalEvent.isDefaultPrevented() ) { return; } url = $.event.special.navigate.originalEventName.indexOf( "hashchange" ) > -1 ? data.state.hash : data.state.url; if( !url ) { url = $.mobile.path.parseLocation().hash; } if( !url || url === "#" || url.indexOf( "#" + $.mobile.path.uiStateKey ) === 0 ){ url = location.href; } $.mobile._handleHashChange( url, data.state ); }); //set page min-heights to be device specific $.mobile.document.bind( "pageshow", $.mobile.resetActivePageHeight ); $.mobile.window.bind( "throttledresize", $.mobile.resetActivePageHeight ); };//navreadyDeferred done callback $( function() { domreadyDeferred.resolve(); } ); $.when( domreadyDeferred, $.mobile.navreadyDeferred ).done( function() { $.mobile._registerInternalEvents(); } ); })( jQuery ); /* * fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.flip = "fade"; })( jQuery, this ); /* * fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.flow = "fade"; })( jQuery, this ); /* * fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.pop = "fade"; })( jQuery, this ); /* * fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { // Use the simultaneous transitions handler for slide transitions $.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous; // Set the slide transitions's fallback to "fade" $.mobile.transitionFallbacks.slide = "fade"; })( jQuery, this ); /* * fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.slidedown = "fade"; })( jQuery, this ); /* * fallback transition for slidefade in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { // Set the slide transitions's fallback to "fade" $.mobile.transitionFallbacks.slidefade = "fade"; })( jQuery, this ); /* * fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.slideup = "fade"; })( jQuery, this ); /* * fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.turn = "fade"; })( jQuery, this ); (function( $, undefined ) { $.mobile.page.prototype.options.degradeInputs = { color: false, date: false, datetime: false, "datetime-local": false, email: false, month: false, number: false, range: "number", search: "text", tel: false, time: false, url: false, week: false }; //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { var page = $.mobile.closestPageData( $( e.target ) ), options; if ( !page ) { return; } options = page.options; // degrade inputs to avoid poorly implemented native functionality $( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() { var $this = $( this ), type = this.getAttribute( "type" ), optType = options.degradeInputs[ type ] || "text"; if ( options.degradeInputs[ type ] ) { var html = $( "<div>" ).html( $this.clone() ).html(), // In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead hasType = html.indexOf( " type=" ) > -1, findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/, repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" ); $this.replaceWith( html.replace( findstr, repstr ) ); } }); }); })( jQuery ); (function( $, window, undefined ) { $.widget( "mobile.dialog", $.mobile.widget, { options: { closeBtn: "left", closeBtnText: "Close", overlayTheme: "a", corners: true, initSelector: ":jqmData(role='dialog')" }, // Override the theme set by the page plugin on pageshow _handlePageBeforeShow: function() { this._isCloseable = true; if ( this.options.overlayTheme ) { this.element .page( "removeContainerBackground" ) .page( "setContainerBackground", this.options.overlayTheme ); } }, _handlePageBeforeHide: function() { this._isCloseable = false; }, _create: function() { var self = this, $el = this.element, cornerClass = !!this.options.corners ? " ui-corner-all" : "", dialogWrap = $( "<div/>", { "role" : "dialog", "class" : "ui-dialog-contain ui-overlay-shadow" + cornerClass }); $el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme ); // Class the markup for dialog styling // Set aria role $el.wrapInner( dialogWrap ); /* bind events - clicks and submits should use the closing transition that the dialog opened with unless a data-transition is specified on the link/form - if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally */ $el.bind( "vclick submit", function( event ) { var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ), active; if ( $target.length && !$target.jqmData( "transition" ) ) { active = $.mobile.urlHistory.getActive() || {}; $target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) ) .attr( "data-" + $.mobile.ns + "direction", "reverse" ); } }); this._on( $el, { pagebeforeshow: "_handlePageBeforeShow", pagebeforehide: "_handlePageBeforeHide" }); $.extend( this, { _createComplete: false }); this._setCloseBtn( this.options.closeBtn ); }, _setCloseBtn: function( value ) { var self = this, btn, location; if ( this._headerCloseButton ) { this._headerCloseButton.remove(); this._headerCloseButton = null; } if ( value !== "none" ) { // Sanitize value location = ( value === "left" ? "left" : "right" ); btn = $( "<a href='#' class='ui-btn-" + location + "' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" ); this.element.children().find( ":jqmData(role='header')" ).first().prepend( btn ); if ( this._createComplete && $.fn.buttonMarkup ) { btn.buttonMarkup(); } this._createComplete = true; // this must be an anonymous function so that select menu dialogs can replace // the close method. This is a change from previously just defining data-rel=back // on the button and letting nav handle it // // Use click rather than vclick in order to prevent the possibility of unintentionally // reopening the dialog if the dialog opening item was directly under the close button. btn.bind( "click", function() { self.close(); }); this._headerCloseButton = btn; } }, _setOption: function( key, value ) { if ( key === "closeBtn" ) { this._setCloseBtn( value ); } this._super( key, value ); }, // Close method goes back in history close: function() { var idx, dst, hist = $.mobile.navigate.history; if ( this._isCloseable ) { this._isCloseable = false; // If the hash listening is enabled and there is at least one preceding history // entry it's ok to go back. Initial pages with the dialog hash state are an example // where the stack check is necessary if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) { $.mobile.back(); } else { idx = Math.max( 0, hist.activeIndex - 1 ); dst = hist.stack[ idx ].pageUrl || hist.stack[ idx ].url; hist.previousIndex = hist.activeIndex; hist.activeIndex = idx; if ( !$.mobile.path.isPath( dst ) ) { dst = $.mobile.path.makeUrlAbsolute( "#" + dst ); } $.mobile.changePage( dst, { direction: "back", changeHash: false, fromHashChange: true } ); } } } }); //auto self-init widgets $.mobile.document.delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function() { $.mobile.dialog.prototype.enhance( this ); }); })( jQuery, this ); (function( $, undefined ) { $.mobile.page.prototype.options.backBtnText = "Back"; $.mobile.page.prototype.options.addBackBtn = false; $.mobile.page.prototype.options.backBtnTheme = null; $.mobile.page.prototype.options.headerTheme = "a"; $.mobile.page.prototype.options.footerTheme = "a"; $.mobile.page.prototype.options.contentTheme = null; // NOTE bind used to force this binding to run before the buttonMarkup binding // which expects .ui-footer top be applied in its gigantic selector // TODO remove the buttonMarkup giant selector and move it to the various modules // on which it depends $.mobile.document.bind( "pagecreate", function( e ) { var $page = $( e.target ), o = $page.data( "mobile-page" ).options, pageRole = $page.jqmData( "role" ), pageTheme = o.theme; $( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", $page ) .jqmEnhanceable() .each(function() { var $this = $( this ), role = $this.jqmData( "role" ), theme = $this.jqmData( "theme" ), contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ), $headeranchors, leftbtn, rightbtn, backBtn; $this.addClass( "ui-" + role ); //apply theming and markup modifications to page,header,content,footer if ( role === "header" || role === "footer" ) { var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme; $this //add theme class .addClass( "ui-bar-" + thisTheme ) // Add ARIA role .attr( "role", role === "header" ? "banner" : "contentinfo" ); if ( role === "header") { // Right,left buttons $headeranchors = $this.children( "a, button" ); leftbtn = $headeranchors.hasClass( "ui-btn-left" ); rightbtn = $headeranchors.hasClass( "ui-btn-right" ); leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length; rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length; } // Auto-add back btn on pages beyond first view if ( o.addBackBtn && role === "header" && $( ".ui-page" ).length > 1 && $page.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) && !leftbtn ) { backBtn = $( "<a href='javascript:void(0);' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" ) // If theme is provided, override default inheritance .attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme ) .prependTo( $this ); } // Page title $this.children( "h1, h2, h3, h4, h5, h6" ) .addClass( "ui-title" ) // Regardless of h element number in src, it becomes h1 for the enhanced page .attr({ "role": "heading", "aria-level": "1" }); } else if ( role === "content" ) { if ( contentTheme ) { $this.addClass( "ui-body-" + ( contentTheme ) ); } // Add ARIA role $this.attr( "role", "main" ); } }); }); })( jQuery ); (function( $, undefined ) { // This function calls getAttribute, which should be safe for data-* attributes var getAttrFixed = function( e, key ) { var value = e.getAttribute( key ); return value === "true" ? true : value === "false" ? false : value === null ? undefined : value; }; $.fn.buttonMarkup = function( options ) { var $workingSet = this, nsKey = "data-" + $.mobile.ns, key; // Enforce options to be of type string options = ( options && ( $.type( options ) === "object" ) )? options : {}; for ( var i = 0; i < $workingSet.length; i++ ) { var el = $workingSet.eq( i ), e = el[ 0 ], o = $.extend( {}, $.fn.buttonMarkup.defaults, { icon: options.icon !== undefined ? options.icon : getAttrFixed( e, nsKey + "icon" ), iconpos: options.iconpos !== undefined ? options.iconpos : getAttrFixed( e, nsKey + "iconpos" ), theme: options.theme !== undefined ? options.theme : getAttrFixed( e, nsKey + "theme" ) || $.mobile.getInheritedTheme( el, "c" ), inline: options.inline !== undefined ? options.inline : getAttrFixed( e, nsKey + "inline" ), shadow: options.shadow !== undefined ? options.shadow : getAttrFixed( e, nsKey + "shadow" ), corners: options.corners !== undefined ? options.corners : getAttrFixed( e, nsKey + "corners" ), iconshadow: options.iconshadow !== undefined ? options.iconshadow : getAttrFixed( e, nsKey + "iconshadow" ), mini: options.mini !== undefined ? options.mini : getAttrFixed( e, nsKey + "mini" ) }, options ), // Classes Defined innerClass = "ui-btn-inner", textClass = "ui-btn-text", buttonClass, iconClass, hover = false, state = "up", // Button inner markup buttonInner, buttonText, buttonIcon, buttonElements; for ( key in o ) { if ( o[ key ] === undefined || o[ key ] === null ) { el.removeAttr( nsKey + key ); } else { e.setAttribute( nsKey + key, o[ key ] ); } } // Check if this element is already enhanced buttonElements = $.data( ( ( e.tagName === "INPUT" || e.tagName === "BUTTON" ) ? e.parentNode : e ), "buttonElements" ); if ( buttonElements ) { e = buttonElements.outer; el = $( e ); buttonInner = buttonElements.inner; buttonText = buttonElements.text; // We will recreate this icon below $( buttonElements.icon ).remove(); buttonElements.icon = null; hover = buttonElements.hover; state = buttonElements.state; } else { buttonInner = document.createElement( o.wrapperEls ); buttonText = document.createElement( o.wrapperEls ); } buttonIcon = o.icon ? document.createElement( "span" ) : null; if ( attachEvents && !buttonElements ) { attachEvents(); } // if not, try to find closest theme container if ( !o.theme ) { o.theme = $.mobile.getInheritedTheme( el, "c" ); } buttonClass = "ui-btn "; buttonClass += ( hover ? "ui-btn-hover-" + o.theme : "" ); buttonClass += ( state ? " ui-btn-" + state + "-" + o.theme : "" ); buttonClass += o.shadow ? " ui-shadow" : ""; buttonClass += o.corners ? " ui-btn-corner-all" : ""; if ( o.mini !== undefined ) { // Used to control styling in headers/footers, where buttons default to `mini` style. buttonClass += o.mini === true ? " ui-mini" : " ui-fullsize"; } if ( o.inline !== undefined ) { // Used to control styling in headers/footers, where buttons default to `inline` style. buttonClass += o.inline === true ? " ui-btn-inline" : " ui-btn-block"; } if ( o.icon ) { o.icon = "ui-icon-" + o.icon; o.iconpos = o.iconpos || "left"; iconClass = "ui-icon " + o.icon; if ( o.iconshadow ) { iconClass += " ui-icon-shadow"; } } if ( o.iconpos ) { buttonClass += " ui-btn-icon-" + o.iconpos; if ( o.iconpos === "notext" && !el.attr( "title" ) ) { el.attr( "title", el.getEncodedText() ); } } if ( buttonElements ) { el.removeClass( buttonElements.bcls || "" ); } el.removeClass( "ui-link" ).addClass( buttonClass ); buttonInner.className = innerClass; buttonText.className = textClass; if ( !buttonElements ) { buttonInner.appendChild( buttonText ); } if ( buttonIcon ) { buttonIcon.className = iconClass; if ( !( buttonElements && buttonElements.icon ) ) { buttonIcon.innerHTML = "&#160;"; buttonInner.appendChild( buttonIcon ); } } while ( e.firstChild && !buttonElements ) { buttonText.appendChild( e.firstChild ); } if ( !buttonElements ) { e.appendChild( buttonInner ); } // Assign a structure containing the elements of this button to the elements of this button. This // will allow us to recognize this as an already-enhanced button in future calls to buttonMarkup(). buttonElements = { hover : hover, state : state, bcls : buttonClass, outer : e, inner : buttonInner, text : buttonText, icon : buttonIcon }; $.data( e, 'buttonElements', buttonElements ); $.data( buttonInner, 'buttonElements', buttonElements ); $.data( buttonText, 'buttonElements', buttonElements ); if ( buttonIcon ) { $.data( buttonIcon, 'buttonElements', buttonElements ); } } return this; }; $.fn.buttonMarkup.defaults = { corners: true, shadow: true, iconshadow: true, wrapperEls: "span" }; function closestEnabledButton( element ) { var cname; while ( element ) { // Note that we check for typeof className below because the element we // handed could be in an SVG DOM where className on SVG elements is defined to // be of a different type (SVGAnimatedString). We only operate on HTML DOM // elements, so we look for plain "string". cname = ( typeof element.className === 'string' ) && ( element.className + ' ' ); if ( cname && cname.indexOf( "ui-btn " ) > -1 && cname.indexOf( "ui-disabled " ) < 0 ) { break; } element = element.parentNode; } return element; } function updateButtonClass( $btn, classToRemove, classToAdd, hover, state ) { var buttonElements = $.data( $btn[ 0 ], "buttonElements" ); $btn.removeClass( classToRemove ).addClass( classToAdd ); if ( buttonElements ) { buttonElements.bcls = $( document.createElement( "div" ) ) .addClass( buttonElements.bcls + " " + classToAdd ) .removeClass( classToRemove ) .attr( "class" ); if ( hover !== undefined ) { buttonElements.hover = hover; } buttonElements.state = state; } } var attachEvents = function() { var hoverDelay = $.mobile.buttonMarkup.hoverDelay, hov, foc; $.mobile.document.bind( { "vmousedown vmousecancel vmouseup vmouseover vmouseout focus blur scrollstart": function( event ) { var theme, $btn = $( closestEnabledButton( event.target ) ), isTouchEvent = event.originalEvent && /^touch/.test( event.originalEvent.type ), evt = event.type; if ( $btn.length ) { theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); if ( evt === "vmousedown" ) { if ( isTouchEvent ) { // Use a short delay to determine if the user is scrolling before highlighting hov = setTimeout( function() { updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" ); }, hoverDelay ); } else { updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" ); } } else if ( evt === "vmousecancel" || evt === "vmouseup" ) { updateButtonClass( $btn, "ui-btn-down-" + theme, "ui-btn-up-" + theme, undefined, "up" ); } else if ( evt === "vmouseover" || evt === "focus" ) { if ( isTouchEvent ) { // Use a short delay to determine if the user is scrolling before highlighting foc = setTimeout( function() { updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" ); }, hoverDelay ); } else { updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" ); } } else if ( evt === "vmouseout" || evt === "blur" || evt === "scrollstart" ) { updateButtonClass( $btn, "ui-btn-hover-" + theme + " ui-btn-down-" + theme, "ui-btn-up-" + theme, false, "up" ); if ( hov ) { clearTimeout( hov ); } if ( foc ) { clearTimeout( foc ); } } } }, "focusin focus": function( event ) { $( closestEnabledButton( event.target ) ).addClass( $.mobile.focusClass ); }, "focusout blur": function( event ) { $( closestEnabledButton( event.target ) ).removeClass( $.mobile.focusClass ); } }); attachEvents = null; }; //links in bars, or those with data-role become buttons //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target ) .jqmEnhanceable() .not( "button, input, .ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" ) .buttonMarkup(); }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.collapsible", $.mobile.widget, { options: { expandCueText: " click to expand contents", collapseCueText: " click to collapse contents", collapsed: true, heading: "h1,h2,h3,h4,h5,h6,legend", collapsedIcon: "plus", expandedIcon: "minus", iconpos: "left", theme: null, contentTheme: null, inset: true, corners: true, mini: false, initSelector: ":jqmData(role='collapsible')" }, _create: function() { var $el = this.element, o = this.options, collapsible = $el.addClass( "ui-collapsible" ), collapsibleHeading = $el.children( o.heading ).first(), collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).children( ".ui-collapsible-content" ), collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ), collapsibleClasses = ""; // Replace collapsibleHeading if it's a legend if ( collapsibleHeading.is( "legend" ) ) { collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading ); collapsibleHeading.next().remove(); } // If we are in a collapsible set if ( collapsibleSet.length ) { // Inherit the theme from collapsible-set if ( !o.theme ) { o.theme = collapsibleSet.jqmData( "theme" ) || $.mobile.getInheritedTheme( collapsibleSet, "c" ); } // Inherit the content-theme from collapsible-set if ( !o.contentTheme ) { o.contentTheme = collapsibleSet.jqmData( "content-theme" ); } // Get the preference for collapsed icon in the set, but override with data- attribute on the individual collapsible o.collapsedIcon = $el.jqmData( "collapsed-icon" ) || collapsibleSet.jqmData( "collapsed-icon" ) || o.collapsedIcon; // Get the preference for expanded icon in the set, but override with data- attribute on the individual collapsible o.expandedIcon = $el.jqmData( "expanded-icon" ) || collapsibleSet.jqmData( "expanded-icon" ) || o.expandedIcon; // Gets the preference icon position in the set, but override with data- attribute on the individual collapsible o.iconpos = $el.jqmData( "iconpos" ) || collapsibleSet.jqmData( "iconpos" ) || o.iconpos; // Inherit the preference for inset from collapsible-set or set the default value to ensure equalty within a set if ( collapsibleSet.jqmData( "inset" ) !== undefined ) { o.inset = collapsibleSet.jqmData( "inset" ); } else { o.inset = true; } // Set corners for individual collapsibles to false when in a collapsible-set o.corners = false; // Gets the preference for mini in the set if ( !o.mini ) { o.mini = collapsibleSet.jqmData( "mini" ); } } else { // get inherited theme if not a set and no theme has been set if ( !o.theme ) { o.theme = $.mobile.getInheritedTheme( $el, "c" ); } } if ( !!o.inset ) { collapsibleClasses += " ui-collapsible-inset"; if ( !!o.corners ) { collapsibleClasses += " ui-corner-all" ; } } if ( o.contentTheme ) { collapsibleClasses += " ui-collapsible-themed-content"; collapsibleContent.addClass( "ui-body-" + o.contentTheme ); } if ( collapsibleClasses !== "" ) { collapsible.addClass( collapsibleClasses ); } collapsibleHeading //drop heading in before content .insertBefore( collapsibleContent ) //modify markup & attributes .addClass( "ui-collapsible-heading" ) .append( "<span class='ui-collapsible-heading-status'></span>" ) .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" ) .find( "a" ) .first() .buttonMarkup({ shadow: false, corners: false, iconpos: o.iconpos, icon: o.collapsedIcon, mini: o.mini, theme: o.theme }); //events collapsible .bind( "expand collapse", function( event ) { if ( !event.isDefaultPrevented() ) { var $this = $( this ), isCollapse = ( event.type === "collapse" ); event.preventDefault(); collapsibleHeading .toggleClass( "ui-collapsible-heading-collapsed", isCollapse ) .find( ".ui-collapsible-heading-status" ) .text( isCollapse ? o.expandCueText : o.collapseCueText ) .end() .find( ".ui-icon" ) .toggleClass( "ui-icon-" + o.expandedIcon, !isCollapse ) // logic or cause same icon for expanded/collapsed state would remove the ui-icon-class .toggleClass( "ui-icon-" + o.collapsedIcon, ( isCollapse || o.expandedIcon === o.collapsedIcon ) ) .end() .find( "a" ).first().removeClass( $.mobile.activeBtnClass ); $this.toggleClass( "ui-collapsible-collapsed", isCollapse ); collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse ); collapsibleContent.trigger( "updatelayout" ); } }) .trigger( o.collapsed ? "collapse" : "expand" ); collapsibleHeading .bind( "tap", function( event ) { collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass ); }) .bind( "click", function( event ) { var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ? "expand" : "collapse"; collapsible.trigger( type ); event.preventDefault(); event.stopPropagation(); }); } }); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.collapsible.prototype.enhanceWithin( e.target ); }); })( jQuery ); (function( $, undefined ) { $.mobile.behaviors.addFirstLastClasses = { _getVisibles: function( $els, create ) { var visibles; if ( create ) { visibles = $els.not( ".ui-screen-hidden" ); } else { visibles = $els.filter( ":visible" ); if ( visibles.length === 0 ) { visibles = $els.not( ".ui-screen-hidden" ); } } return visibles; }, _addFirstLastClasses: function( $els, $visibles, create ) { $els.removeClass( "ui-first-child ui-last-child" ); $visibles.eq( 0 ).addClass( "ui-first-child" ).end().last().addClass( "ui-last-child" ); if ( !create ) { this.element.trigger( "updatelayout" ); } } }; })( jQuery ); (function( $, undefined ) { $.widget( "mobile.collapsibleset", $.mobile.widget, $.extend( { options: { initSelector: ":jqmData(role='collapsible-set')" }, _create: function() { var $el = this.element.addClass( "ui-collapsible-set" ), o = this.options; // Inherit the theme from collapsible-set if ( !o.theme ) { o.theme = $.mobile.getInheritedTheme( $el, "c" ); } // Inherit the content-theme from collapsible-set if ( !o.contentTheme ) { o.contentTheme = $el.jqmData( "content-theme" ); } // Inherit the corner styling from collapsible-set if ( !o.corners ) { o.corners = $el.jqmData( "corners" ); } if ( $el.jqmData( "inset" ) !== undefined ) { o.inset = $el.jqmData( "inset" ); } o.inset = o.inset !== undefined ? o.inset : true; o.corners = o.corners !== undefined ? o.corners : true; if ( !!o.corners && !!o.inset ) { $el.addClass( "ui-corner-all" ); } // Initialize the collapsible set if it's not already initialized if ( !$el.jqmData( "collapsiblebound" ) ) { $el .jqmData( "collapsiblebound", true ) .bind( "expand", function( event ) { var closestCollapsible = $( event.target ) .closest( ".ui-collapsible" ); if ( closestCollapsible.parent().is( ":jqmData(role='collapsible-set')" ) ) { closestCollapsible .siblings( ".ui-collapsible" ) .trigger( "collapse" ); } }); } }, _init: function() { var $el = this.element, collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" ), expanded = collapsiblesInSet.filter( ":jqmData(collapsed='false')" ); this._refresh( "true" ); // Because the corners are handled by the collapsible itself and the default state is collapsed // That was causing https://github.com/jquery/jquery-mobile/issues/4116 expanded.trigger( "expand" ); }, _refresh: function( create ) { var collapsiblesInSet = this.element.children( ":jqmData(role='collapsible')" ); $.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) ); this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create ); }, refresh: function() { this._refresh( false ); } }, $.mobile.behaviors.addFirstLastClasses ) ); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.collapsibleset.prototype.enhanceWithin( e.target ); }); })( jQuery ); (function( $, undefined ) { // filter function removes whitespace between label and form element so we can use inline-block (nodeType 3 = text) $.fn.fieldcontain = function( options ) { return this .addClass( "ui-field-contain ui-body ui-br" ) .contents().filter( function() { return ( this.nodeType === 3 && !/\S/.test( this.nodeValue ) ); }).remove(); }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ) { $( ":jqmData(role='fieldcontain')", e.target ).jqmEnhanceable().fieldcontain(); }); })( jQuery ); (function( $, undefined ) { $.fn.grid = function( options ) { return this.each(function() { var $this = $( this ), o = $.extend({ grid: null }, options ), $kids = $this.children(), gridCols = { solo:1, a:2, b:3, c:4, d:5 }, grid = o.grid, iterator; if ( !grid ) { if ( $kids.length <= 5 ) { for ( var letter in gridCols ) { if ( gridCols[ letter ] === $kids.length ) { grid = letter; } } } else { grid = "a"; $this.addClass( "ui-grid-duo" ); } } iterator = gridCols[grid]; $this.addClass( "ui-grid-" + grid ); $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" ); if ( iterator > 1 ) { $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" ); } if ( iterator > 2 ) { $kids.filter( ":nth-child(" + iterator + "n+3)" ).addClass( "ui-block-c" ); } if ( iterator > 3 ) { $kids.filter( ":nth-child(" + iterator + "n+4)" ).addClass( "ui-block-d" ); } if ( iterator > 4 ) { $kids.filter( ":nth-child(" + iterator + "n+5)" ).addClass( "ui-block-e" ); } }); }; })( jQuery ); (function( $, undefined ) { $.widget( "mobile.navbar", $.mobile.widget, { options: { iconpos: "top", grid: null, initSelector: ":jqmData(role='navbar')" }, _create: function() { var $navbar = this.element, $navbtns = $navbar.find( "a" ), iconpos = $navbtns.filter( ":jqmData(icon)" ).length ? this.options.iconpos : undefined; $navbar.addClass( "ui-navbar ui-mini" ) .attr( "role", "navigation" ) .find( "ul" ) .jqmEnhanceable() .grid({ grid: this.options.grid }); $navbtns.buttonMarkup({ corners: false, shadow: false, inline: true, iconpos: iconpos }); $navbar.delegate( "a", "vclick", function( event ) { // ui-btn-inner is returned as target var target = $( event.target ).is( "a" ) ? $( this ) : $( this ).parent( "a" ); if ( !target.is( ".ui-disabled, .ui-btn-active" ) ) { $navbtns.removeClass( $.mobile.activeBtnClass ); $( this ).addClass( $.mobile.activeBtnClass ); // The code below is a workaround to fix #1181 var activeBtn = $( this ); $( document ).one( "pagehide", function() { activeBtn.removeClass( $.mobile.activeBtnClass ); }); } }); // Buttons in the navbar with ui-state-persist class should regain their active state before page show $navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() { $navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass ); }); } }); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.navbar.prototype.enhanceWithin( e.target ); }); })( jQuery ); (function( $, undefined ) { //Keeps track of the number of lists per page UID //This allows support for multiple nested list in the same page //https://github.com/jquery/jquery-mobile/issues/1617 var listCountPerPage = {}; $.widget( "mobile.listview", $.mobile.widget, $.extend( { options: { theme: null, countTheme: "c", headerTheme: "b", dividerTheme: "b", icon: "arrow-r", splitIcon: "arrow-r", splitTheme: "b", corners: true, shadow: true, inset: false, initSelector: ":jqmData(role='listview')" }, _create: function() { var t = this, listviewClasses = ""; listviewClasses += t.options.inset ? " ui-listview-inset" : ""; if ( !!t.options.inset ) { listviewClasses += t.options.corners ? " ui-corner-all" : ""; listviewClasses += t.options.shadow ? " ui-shadow" : ""; } // create listview markup t.element.addClass(function( i, orig ) { return orig + " ui-listview" + listviewClasses; }); t.refresh( true ); }, // This is a generic utility method for finding the first // node with a given nodeName. It uses basic DOM traversal // to be fast and is meant to be a substitute for simple // $.fn.closest() and $.fn.children() calls on a single // element. Note that callers must pass both the lowerCase // and upperCase version of the nodeName they are looking for. // The main reason for this is that this function will be // called many times and we want to avoid having to lowercase // the nodeName from the element every time to ensure we have // a match. Note that this function lives here for now, but may // be moved into $.mobile if other components need a similar method. _findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) { var dict = {}; dict[ lcName ] = dict[ ucName ] = true; while ( ele ) { if ( dict[ ele.nodeName ] ) { return ele; } ele = ele[ nextProp ]; } return null; }, _getChildrenByTagName: function( ele, lcName, ucName ) { var results = [], dict = {}; dict[ lcName ] = dict[ ucName ] = true; ele = ele.firstChild; while ( ele ) { if ( dict[ ele.nodeName ] ) { results.push( ele ); } ele = ele.nextSibling; } return $( results ); }, _addThumbClasses: function( containers ) { var i, img, len = containers.length; for ( i = 0; i < len; i++ ) { img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) ); if ( img.length ) { img.addClass( "ui-li-thumb" ); $( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" ); } } }, refresh: function( create ) { this.parentPage = this.element.closest( ".ui-page" ); this._createSubPages(); var o = this.options, $list = this.element, self = this, dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme, listsplittheme = $list.jqmData( "splittheme" ), listspliticon = $list.jqmData( "spliticon" ), listicon = $list.jqmData( "icon" ), li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ), ol = !!$.nodeName( $list[ 0 ], "ol" ), jsCount = !$.support.cssPseudoElement, start = $list.attr( "start" ), itemClassDict = {}, item, itemClass, itemTheme, a, last, splittheme, counter, startCount, newStartCount, countParent, icon, imgParents, img, linkIcon; if ( ol && jsCount ) { $list.find( ".ui-li-dec" ).remove(); } if ( ol ) { // Check if a start attribute has been set while taking a value of 0 into account if ( start || start === 0 ) { if ( !jsCount ) { startCount = parseInt( start , 10 ) - 1; $list.css( "counter-reset", "listnumbering " + startCount ); } else { counter = parseInt( start , 10 ); } } else if ( jsCount ) { counter = 1; } } if ( !o.theme ) { o.theme = $.mobile.getInheritedTheme( this.element, "c" ); } for ( var pos = 0, numli = li.length; pos < numli; pos++ ) { item = li.eq( pos ); itemClass = "ui-li"; // If we're creating the element, we update it regardless if ( create || !item.hasClass( "ui-li" ) ) { itemTheme = item.jqmData( "theme" ) || o.theme; a = this._getChildrenByTagName( item[ 0 ], "a", "A" ); var isDivider = ( item.jqmData( "role" ) === "list-divider" ); if ( a.length && !isDivider ) { icon = item.jqmData( "icon" ); item.buttonMarkup({ wrapperEls: "div", shadow: false, corners: false, iconpos: "right", icon: a.length > 1 || icon === false ? false : icon || listicon || o.icon, theme: itemTheme }); if ( ( icon !== false ) && ( a.length === 1 ) ) { item.addClass( "ui-li-has-arrow" ); } a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" ); if ( a.length > 1 ) { itemClass += " ui-li-has-alt"; last = a.last(); splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme; linkIcon = last.jqmData( "icon" ); last.appendTo( item ) .attr( "title", $.trim(last.getEncodedText()) ) .addClass( "ui-li-link-alt" ) .empty() .buttonMarkup({ shadow: false, corners: false, theme: itemTheme, icon: false, iconpos: "notext" }) .find( ".ui-btn-inner" ) .append( $( document.createElement( "span" ) ).buttonMarkup({ shadow: true, corners: true, theme: splittheme, iconpos: "notext", // link icon overrides list item icon overrides ul element overrides options icon: linkIcon || icon || listspliticon || o.splitIcon }) ); } } else if ( isDivider ) { itemClass += " ui-li-divider ui-bar-" + ( item.jqmData( "theme" ) || dividertheme ); item.attr( "role", "heading" ); if ( ol ) { //reset counter when a divider heading is encountered if ( start || start === 0 ) { if ( !jsCount ) { newStartCount = parseInt( start , 10 ) - 1; item.css( "counter-reset", "listnumbering " + newStartCount ); } else { counter = parseInt( start , 10 ); } } else if ( jsCount ) { counter = 1; } } } else { itemClass += " ui-li-static ui-btn-up-" + itemTheme; } } if ( ol && jsCount && itemClass.indexOf( "ui-li-divider" ) < 0 ) { countParent = itemClass.indexOf( "ui-li-static" ) > 0 ? item : item.find( ".ui-link-inherit" ); countParent.addClass( "ui-li-jsnumbering" ) .prepend( "<span class='ui-li-dec'>" + ( counter++ ) + ". </span>" ); } // Instead of setting item class directly on the list item and its // btn-inner at this point in time, push the item into a dictionary // that tells us what class to set on it so we can do this after this // processing loop is finished. if ( !itemClassDict[ itemClass ] ) { itemClassDict[ itemClass ] = []; } itemClassDict[ itemClass ].push( item[ 0 ] ); } // Set the appropriate listview item classes on each list item // and their btn-inner elements. The main reason we didn't do this // in the for-loop above is because we can eliminate per-item function overhead // by calling addClass() and children() once or twice afterwards. This // can give us a significant boost on platforms like WP7.5. for ( itemClass in itemClassDict ) { $( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass ); } $list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" ) .end() .find( "p, dl" ).addClass( "ui-li-desc" ) .end() .find( ".ui-li-aside" ).each(function() { var $this = $( this ); $this.prependTo( $this.parent() ); //shift aside to front for css float }) .end() .find( ".ui-li-count" ).each(function() { $( this ).closest( "li" ).addClass( "ui-li-has-count" ); }).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" ); // The idea here is to look at the first image in the list item // itself, and any .ui-link-inherit element it may contain, so we // can place the appropriate classes on the image and list item. // Note that we used to use something like: // // li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... ); // // But executing a find() like that on Windows Phone 7.5 took a // really long time. Walking things manually with the code below // allows the 400 listview item page to load in about 3 seconds as // opposed to 30 seconds. this._addThumbClasses( li ); this._addThumbClasses( $list.find( ".ui-link-inherit" ) ); this._addFirstLastClasses( li, this._getVisibles( li, create ), create ); // autodividers binds to this to redraw dividers after the listview refresh this._trigger( "afterrefresh" ); }, //create a string for ID/subpage url creation _idStringEscape: function( str ) { return str.replace(/[^a-zA-Z0-9]/g, '-'); }, _createSubPages: function() { var parentList = this.element, parentPage = parentList.closest( ".ui-page" ), parentUrl = parentPage.jqmData( "url" ), parentId = parentUrl || parentPage[ 0 ][ $.expando ], parentListId = parentList.attr( "id" ), o = this.options, dns = "data-" + $.mobile.ns, self = this, persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ), hasSubPages; if ( typeof listCountPerPage[ parentId ] === "undefined" ) { listCountPerPage[ parentId ] = -1; } parentListId = parentListId || ++listCountPerPage[ parentId ]; $( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) { var self = this, list = $( this ), listId = list.attr( "id" ) || parentListId + "-" + i, parent = list.parent(), nodeElsFull = $( list.prevAll().toArray().reverse() ), nodeEls = nodeElsFull.length ? nodeElsFull : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ), title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId, theme = list.jqmData( "theme" ) || o.theme, countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme, newPage, anchor; //define hasSubPages for use in later removal hasSubPages = true; newPage = list.detach() .wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" ) .parent() .before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" ) .after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>" ) : "" ) .parent() .appendTo( $.mobile.pageContainer ); newPage.page(); anchor = parent.find( 'a:first' ); if ( !anchor.length ) { anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() ); } anchor.attr( "href", "#" + id ); }).listview(); // on pagehide, remove any nested pages along with the parent page, as long as they aren't active // and aren't embedded if ( hasSubPages && parentPage.is( ":jqmData(external-page='true')" ) && parentPage.data( "mobile-page" ).options.domCache === false ) { var newRemove = function( e, ui ) { var nextPage = ui.nextPage, npURL, prEvent = new $.Event( "pageremove" ); if ( ui.nextPage ) { npURL = nextPage.jqmData( "url" ); if ( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ) { self.childPages().remove(); parentPage.trigger( prEvent ); if ( !prEvent.isDefaultPrevented() ) { parentPage.removeWithDependents(); } } } }; // unbind the original page remove and replace with our specialized version parentPage .unbind( "pagehide.remove" ) .bind( "pagehide.remove", newRemove); } }, // TODO sort out a better way to track sub pages of the listview this is brittle childPages: function() { var parentUrl = this.parentPage.jqmData( "url" ); return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey + "')" ); } }, $.mobile.behaviors.addFirstLastClasses ) ); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.listview.prototype.enhanceWithin( e.target ); }); })( jQuery ); (function( $ ) { var meta = $( "meta[name=viewport]" ), initialContent = meta.attr( "content" ), disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no", enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes", disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent ); $.mobile.zoom = $.extend( {}, { enabled: !disabledInitially, locked: false, disable: function( lock ) { if ( !disabledInitially && !$.mobile.zoom.locked ) { meta.attr( "content", disabledZoom ); $.mobile.zoom.enabled = false; $.mobile.zoom.locked = lock || false; } }, enable: function( unlock ) { if ( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ) { meta.attr( "content", enabledZoom ); $.mobile.zoom.enabled = true; $.mobile.zoom.locked = false; } }, restore: function() { if ( !disabledInitially ) { meta.attr( "content", initialContent ); $.mobile.zoom.enabled = true; } } }); }( jQuery )); (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.widget, { options: { theme: null, mini: false, // This option defaults to true on iOS devices. preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1, initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type]), input[type='file']", clearBtn: false, clearSearchButtonText: null, //deprecating for 1.3... clearBtnText: "clear text", disabled: false }, _create: function() { var self = this, input = this.element, o = this.options, theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ), themeclass = " ui-body-" + theme, miniclass = o.mini ? " ui-mini" : "", isSearch = input.is( "[type='search'], :jqmData(type='search')" ), focusedEl, clearbtn, clearBtnText = o.clearSearchButtonText || o.clearBtnText, clearBtnBlacklist = input.is( "textarea, :jqmData(type='range')" ), inputNeedsClearBtn = !!o.clearBtn && !clearBtnBlacklist, inputNeedsWrap = input.is( "input" ) && !input.is( ":jqmData(type='range')" ); function toggleClear() { setTimeout( function() { clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() ); }, 0 ); } $( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" ); focusedEl = input.addClass( "ui-input-text ui-body-"+ theme ); // XXX: Temporary workaround for issue 785 (Apple bug 8910589). // Turn off autocorrect and autocomplete on non-iOS 5 devices // since the popup they use can't be dismissed by the user. Note // that we test for the presence of the feature by looking for // the autocorrect property on the input element. We currently // have no test for iOS 5 or newer so we're temporarily using // the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) { // Set the attribute instead of the property just in case there // is code that attempts to make modifications via HTML. input[0].setAttribute( "autocorrect", "off" ); input[0].setAttribute( "autocomplete", "off" ); } //"search" and "text" input widgets if ( isSearch ) { focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + miniclass + "'></div>" ).parent(); } else if ( inputNeedsWrap ) { focusedEl = input.wrap( "<div class='ui-input-text ui-shadow-inset ui-corner-all ui-btn-shadow" + themeclass + miniclass + "'></div>" ).parent(); } if( inputNeedsClearBtn || isSearch ) { clearbtn = $( "<a href='#' class='ui-input-clear' title='" + clearBtnText + "'>" + clearBtnText + "</a>" ) .bind( "click", function( event ) { input .val( "" ) .focus() .trigger( "change" ); clearbtn.addClass( "ui-input-clear-hidden" ); event.preventDefault(); }) .appendTo( focusedEl ) .buttonMarkup({ icon: "delete", iconpos: "notext", corners: true, shadow: true, mini: o.mini }); if ( !isSearch ) { focusedEl.addClass( "ui-input-has-clear" ); } toggleClear(); input.bind( "paste cut keyup input focus change blur", toggleClear ); } else if ( !inputNeedsWrap && !isSearch ) { input.addClass( "ui-corner-all ui-shadow-inset" + themeclass + miniclass ); } input.focus(function() { // In many situations, iOS will zoom into the input upon tap, this prevents that from happening if ( o.preventFocusZoom ) { $.mobile.zoom.disable( true ); } focusedEl.addClass( $.mobile.focusClass ); }) .blur(function() { focusedEl.removeClass( $.mobile.focusClass ); if ( o.preventFocusZoom ) { $.mobile.zoom.enable( true ); } }); // Autogrow if ( input.is( "textarea" ) ) { var extraLineHeight = 15, keyupTimeoutBuffer = 100, keyupTimeout; this._keyup = function() { var scrollHeight = input[ 0 ].scrollHeight, clientHeight = input[ 0 ].clientHeight; if ( clientHeight < scrollHeight ) { var paddingTop = parseFloat( input.css( "padding-top" ) ), paddingBottom = parseFloat( input.css( "padding-bottom" ) ), paddingHeight = paddingTop + paddingBottom; input.height( scrollHeight - paddingHeight + extraLineHeight ); } }; input.on( "keyup change input paste", function() { clearTimeout( keyupTimeout ); keyupTimeout = setTimeout( self._keyup, keyupTimeoutBuffer ); }); // binding to pagechange here ensures that for pages loaded via // ajax the height is recalculated without user input this._on( true, $.mobile.document, { "pagechange": "_keyup" }); // Issue 509: the browser is not providing scrollHeight properly until the styles load if ( $.trim( input.val() ) ) { // bind to the window load to make sure the height is calculated based on BOTH // the DOM and CSS this._on( true, $.mobile.window, {"load": "_keyup"}); } } if ( input.attr( "disabled" ) ) { this.disable(); } }, disable: function() { var $el, isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ), inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ), parentNeedsDisabled = this.element.attr( "disabled", true ) && ( inputNeedsWrap || isSearch ); if ( parentNeedsDisabled ) { $el = this.element.parent(); } else { $el = this.element; } $el.addClass( "ui-disabled" ); return this._setOption( "disabled", true ); }, enable: function() { var $el, isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ), inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ), parentNeedsEnabled = this.element.attr( "disabled", false ) && ( inputNeedsWrap || isSearch ); if ( parentNeedsEnabled ) { $el = this.element.parent(); } else { $el = this.element; } $el.removeClass( "ui-disabled" ); return this._setOption( "disabled", false ); } }); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.textinput.prototype.enhanceWithin( e.target, true ); }); })( jQuery ); (function( $, undefined ) { $.mobile.listview.prototype.options.filter = false; $.mobile.listview.prototype.options.filterPlaceholder = "Filter items..."; $.mobile.listview.prototype.options.filterTheme = "c"; $.mobile.listview.prototype.options.filterReveal = false; // TODO rename callback/deprecate and default to the item itself as the first argument var defaultFilterCallback = function( text, searchValue, item ) { return text.toString().toLowerCase().indexOf( searchValue ) === -1; }; $.mobile.listview.prototype.options.filterCallback = defaultFilterCallback; $.mobile.document.delegate( "ul, ol", "listviewcreate", function() { var list = $( this ), listview = list.data( "mobile-listview" ); if ( !listview || !listview.options.filter ) { return; } if ( listview.options.filterReveal ) { list.children().addClass( "ui-screen-hidden" ); } var wrapper = $( "<form>", { "class": "ui-listview-filter ui-bar-" + listview.options.filterTheme, "role": "search" }).submit( function( e ) { e.preventDefault(); search.blur(); }), onKeyUp = function( e ) { var $this = $( this ), val = this.value.toLowerCase(), listItems = null, li = list.children(), lastval = $this.jqmData( "lastval" ) + "", childItems = false, itemtext = "", item, // Check if a custom filter callback applies isCustomFilterCallback = listview.options.filterCallback !== defaultFilterCallback; if ( lastval && lastval === val ) { // Execute the handler only once per value change return; } listview._trigger( "beforefilter", "beforefilter", { input: this } ); // Change val as lastval for next execution $this.jqmData( "lastval" , val ); if ( isCustomFilterCallback || val.length < lastval.length || val.indexOf( lastval ) !== 0 ) { // Custom filter callback applies or removed chars or pasted something totally different, check all items listItems = list.children(); } else { // Only chars added, not removed, only use visible subset listItems = list.children( ":not(.ui-screen-hidden)" ); if ( !listItems.length && listview.options.filterReveal ) { listItems = list.children( ".ui-screen-hidden" ); } } if ( val ) { // This handles hiding regular rows without the text we search for // and any list dividers without regular rows shown under it for ( var i = listItems.length - 1; i >= 0; i-- ) { item = $( listItems[ i ] ); itemtext = item.jqmData( "filtertext" ) || item.text(); if ( item.is( "li:jqmData(role=list-divider)" ) ) { item.toggleClass( "ui-filter-hidequeue" , !childItems ); // New bucket! childItems = false; } else if ( listview.options.filterCallback( itemtext, val, item ) ) { //mark to be hidden item.toggleClass( "ui-filter-hidequeue" , true ); } else { // There's a shown item in the bucket childItems = true; } } // Show items, not marked to be hidden listItems .filter( ":not(.ui-filter-hidequeue)" ) .toggleClass( "ui-screen-hidden", false ); // Hide items, marked to be hidden listItems .filter( ".ui-filter-hidequeue" ) .toggleClass( "ui-screen-hidden", true ) .toggleClass( "ui-filter-hidequeue", false ); } else { //filtervalue is empty => show all listItems.toggleClass( "ui-screen-hidden", !!listview.options.filterReveal ); } listview._addFirstLastClasses( li, listview._getVisibles( li, false ), false ); }, search = $( "<input>", { placeholder: listview.options.filterPlaceholder }) .attr( "data-" + $.mobile.ns + "type", "search" ) .jqmData( "lastval", "" ) .bind( "keyup change input", onKeyUp ) .appendTo( wrapper ) .textinput(); if ( listview.options.inset ) { wrapper.addClass( "ui-listview-filter-inset" ); } wrapper.bind( "submit", function() { return false; }) .insertBefore( list ); }); })( jQuery ); (function( $, undefined ) { $.mobile.listview.prototype.options.autodividers = false; $.mobile.listview.prototype.options.autodividersSelector = function( elt ) { // look for the text in the given element var text = $.trim( elt.text() ) || null; if ( !text ) { return null; } // create the text for the divider (first uppercased letter) text = text.slice( 0, 1 ).toUpperCase(); return text; }; $.mobile.document.delegate( "ul,ol", "listviewcreate", function() { var list = $( this ), listview = list.data( "mobile-listview" ); if ( !listview || !listview.options.autodividers ) { return; } var replaceDividers = function () { list.find( "li:jqmData(role='list-divider')" ).remove(); var lis = list.find( 'li' ), lastDividerText = null, li, dividerText; for ( var i = 0; i < lis.length ; i++ ) { li = lis[i]; dividerText = listview.options.autodividersSelector( $( li ) ); if ( dividerText && lastDividerText !== dividerText ) { var divider = document.createElement( 'li' ); divider.appendChild( document.createTextNode( dividerText ) ); divider.setAttribute( 'data-' + $.mobile.ns + 'role', 'list-divider' ); li.parentNode.insertBefore( divider, li ); } lastDividerText = dividerText; } }; var afterListviewRefresh = function () { list.unbind( 'listviewafterrefresh', afterListviewRefresh ); replaceDividers(); listview.refresh(); list.bind( 'listviewafterrefresh', afterListviewRefresh ); }; afterListviewRefresh(); }); })( jQuery ); (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ) { $( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" ); }); })( jQuery ); (function( $, undefined ) { $.mobile.behaviors.formReset = { _handleFormReset: function() { this._on( this.element.closest( "form" ), { reset: function() { this._delay( "_reset" ); } }); } }; })( jQuery ); /* * "checkboxradio" plugin */ (function( $, undefined ) { $.widget( "mobile.checkboxradio", $.mobile.widget, $.extend( { options: { theme: null, mini: false, initSelector: "input[type='checkbox'],input[type='radio']" }, _create: function() { var self = this, input = this.element, o = this.options, inheritAttr = function( input, dataAttr ) { return input.jqmData( dataAttr ) || input.closest( "form, fieldset" ).jqmData( dataAttr ); }, // NOTE: Windows Phone could not find the label through a selector // filter works though. parentLabel = $( input ).closest( "label" ), label = parentLabel.length ? parentLabel : $( input ).closest( "form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')" ).find( "label" ).filter( "[for='" + input[0].id + "']" ).first(), inputtype = input[0].type, mini = inheritAttr( input, "mini" ) || o.mini, checkedState = inputtype + "-on", uncheckedState = inputtype + "-off", iconpos = inheritAttr( input, "iconpos" ), checkedClass = "ui-" + checkedState, uncheckedClass = "ui-" + uncheckedState; if ( inputtype !== "checkbox" && inputtype !== "radio" ) { return; } // Expose for other methods $.extend( this, { label: label, inputtype: inputtype, checkedClass: checkedClass, uncheckedClass: uncheckedClass, checkedicon: checkedState, uncheckedicon: uncheckedState }); // If there's no selected theme check the data attr if ( !o.theme ) { o.theme = $.mobile.getInheritedTheme( this.element, "c" ); } label.buttonMarkup({ theme: o.theme, icon: uncheckedState, shadow: false, mini: mini, iconpos: iconpos }); // Wrap the input + label in a div var wrapper = document.createElement('div'); wrapper.className = 'ui-' + inputtype; input.add( label ).wrapAll( wrapper ); label.bind({ vmouseover: function( event ) { if ( $( this ).parent().is( ".ui-disabled" ) ) { event.stopPropagation(); } }, vclick: function( event ) { if ( input.is( ":disabled" ) ) { event.preventDefault(); return; } self._cacheVals(); input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) ); // trigger click handler's bound directly to the input as a substitute for // how label clicks behave normally in the browsers // TODO: it would be nice to let the browser's handle the clicks and pass them // through to the associate input. we can swallow that click at the parent // wrapper element level input.triggerHandler( 'click' ); // Input set for common radio buttons will contain all the radio // buttons, but will not for checkboxes. clearing the checked status // of other radios ensures the active button state is applied properly self._getInputSet().not( input ).prop( "checked", false ); self._updateAll(); return false; } }); input .bind({ vmousedown: function() { self._cacheVals(); }, vclick: function() { var $this = $( this ); // Adds checked attribute to checked input when keyboard is used if ( $this.is( ":checked" ) ) { $this.prop( "checked", true); self._getInputSet().not( $this ).prop( "checked", false ); } else { $this.prop( "checked", false ); } self._updateAll(); }, focus: function() { label.addClass( $.mobile.focusClass ); }, blur: function() { label.removeClass( $.mobile.focusClass ); } }); this._handleFormReset(); this.refresh(); }, _cacheVals: function() { this._getInputSet().each(function() { $( this ).jqmData( "cacheVal", this.checked ); }); }, //returns either a set of radios with the same name attribute, or a single checkbox _getInputSet: function() { if ( this.inputtype === "checkbox" ) { return this.element; } return this.element.closest( "form, :jqmData(role='page'), :jqmData(role='dialog')" ) .find( "input[name='" + this.element[0].name + "'][type='" + this.inputtype + "']" ); }, _updateAll: function() { var self = this; this._getInputSet().each(function() { var $this = $( this ); if ( this.checked || self.inputtype === "checkbox" ) { $this.trigger( "change" ); } }) .checkboxradio( "refresh" ); }, _reset: function() { this.refresh(); }, refresh: function() { var input = this.element[ 0 ], active = " " + $.mobile.activeBtnClass, checkedClass = this.checkedClass + ( this.element.parents( ".ui-controlgroup-horizontal" ).length ? active : "" ), label = this.label; if ( input.checked ) { label.removeClass( this.uncheckedClass + active ).addClass( checkedClass ).buttonMarkup( { icon: this.checkedicon } ); } else { label.removeClass( checkedClass ).addClass( this.uncheckedClass ).buttonMarkup( { icon: this.uncheckedicon } ); } if ( input.disabled ) { this.disable(); } else { this.enable(); } }, disable: function() { this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" ); }, enable: function() { this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" ); } }, $.mobile.behaviors.formReset ) ); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.checkboxradio.prototype.enhanceWithin( e.target, true ); }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.button", $.mobile.widget, { options: { theme: null, icon: null, iconpos: null, corners: true, shadow: true, iconshadow: true, inline: null, mini: null, initSelector: "button, [type='button'], [type='submit'], [type='reset']" }, _create: function() { var $el = this.element, $button, // create a copy of this.options we can pass to buttonMarkup o = ( function( tdo ) { var key, ret = {}; for ( key in tdo ) { if ( tdo[ key ] !== null && key !== "initSelector" ) { ret[ key ] = tdo[ key ]; } } return ret; } )( this.options ), classes = "", $buttonPlaceholder; // if this is a link, check if it's been enhanced and, if not, use the right function if ( $el[ 0 ].tagName === "A" ) { if ( !$el.hasClass( "ui-btn" ) ) { $el.buttonMarkup(); } return; } // get the inherited theme // TODO centralize for all widgets if ( !this.options.theme ) { this.options.theme = $.mobile.getInheritedTheme( this.element, "c" ); } // TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577 /* if ( $el[0].className.length ) { classes = $el[0].className; } */ if ( !!~$el[0].className.indexOf( "ui-btn-left" ) ) { classes = "ui-btn-left"; } if ( !!~$el[0].className.indexOf( "ui-btn-right" ) ) { classes = "ui-btn-right"; } if ( $el.attr( "type" ) === "submit" || $el.attr( "type" ) === "reset" ) { if ( classes ) { classes += " ui-submit"; } else { classes = "ui-submit"; } } $( "label[for='" + $el.attr( "id" ) + "']" ).addClass( "ui-submit" ); // Add ARIA role this.button = $( "<div></div>" ) [ $el.html() ? "html" : "text" ]( $el.html() || $el.val() ) .insertBefore( $el ) .buttonMarkup( o ) .addClass( classes ) .append( $el.addClass( "ui-btn-hidden" ) ); $button = this.button; $el.bind({ focus: function() { $button.addClass( $.mobile.focusClass ); }, blur: function() { $button.removeClass( $.mobile.focusClass ); } }); this.refresh(); }, _setOption: function( key, value ) { var op = {}; op[ key ] = value; if ( key !== "initSelector" ) { this.button.buttonMarkup( op ); // Record the option change in the options and in the DOM data-* attributes this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value ); } this._super( "_setOption", key, value ); }, enable: function() { this.element.attr( "disabled", false ); this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); }, refresh: function() { var $el = this.element; if ( $el.prop("disabled") ) { this.disable(); } else { this.enable(); } // Grab the button's text element from its implementation-independent data item $( this.button.data( 'buttonElements' ).text )[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() ); } }); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.button.prototype.enhanceWithin( e.target, true ); }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.slider", $.mobile.widget, $.extend( { widgetEventPrefix: "slide", options: { theme: null, trackTheme: null, disabled: false, initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')", mini: false, highlight: false }, _create: function() { // TODO: Each of these should have comments explain what they're for var self = this, control = this.element, parentTheme = $.mobile.getInheritedTheme( control, "c" ), theme = this.options.theme || parentTheme, trackTheme = this.options.trackTheme || parentTheme, cType = control[ 0 ].nodeName.toLowerCase(), isSelect = this.isToggleSwitch = cType === "select", isRangeslider = control.parent().is( ":jqmData(role='rangeslider')" ), selectClass = ( this.isToggleSwitch ) ? "ui-slider-switch" : "", controlID = control.attr( "id" ), $label = $( "[for='" + controlID + "']" ), labelID = $label.attr( "id" ) || controlID + "-label", label = $label.attr( "id", labelID ), min = !this.isToggleSwitch ? parseFloat( control.attr( "min" ) ) : 0, max = !this.isToggleSwitch ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1, step = window.parseFloat( control.attr( "step" ) || 1 ), miniClass = ( this.options.mini || control.jqmData( "mini" ) ) ? " ui-mini" : "", domHandle = document.createElement( "a" ), handle = $( domHandle ), domSlider = document.createElement( "div" ), slider = $( domSlider ), valuebg = this.options.highlight && !this.isToggleSwitch ? (function() { var bg = document.createElement( "div" ); bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all"; return $( bg ).prependTo( slider ); })() : false, options, wrapper; domHandle.setAttribute( "href", "#" ); domSlider.setAttribute( "role", "application" ); domSlider.className = [this.isToggleSwitch ? "ui-slider " : "ui-slider-track ",selectClass," ui-btn-down-",trackTheme," ui-btn-corner-all", miniClass].join( "" ); domHandle.className = "ui-slider-handle"; domSlider.appendChild( domHandle ); handle.buttonMarkup({ corners: true, theme: theme, shadow: true }) .attr({ "role": "slider", "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": this._value(), "aria-valuetext": this._value(), "title": this._value(), "aria-labelledby": labelID }); $.extend( this, { slider: slider, handle: handle, type: cType, step: step, max: max, min: min, valuebg: valuebg, isRangeslider: isRangeslider, dragging: false, beforeStart: null, userModified: false, mouseMoved: false }); if ( this.isToggleSwitch ) { wrapper = document.createElement( "div" ); wrapper.className = "ui-slider-inneroffset"; for ( var j = 0, length = domSlider.childNodes.length; j < length; j++ ) { wrapper.appendChild( domSlider.childNodes[j] ); } domSlider.appendChild( wrapper ); // slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" ); // make the handle move with a smooth transition handle.addClass( "ui-slider-handle-snapping" ); options = control.find( "option" ); for ( var i = 0, optionsCount = options.length; i < optionsCount; i++ ) { var side = !i ? "b" : "a", sliderTheme = !i ? " ui-btn-down-" + trackTheme : ( " " + $.mobile.activeBtnClass ), sliderLabel = document.createElement( "div" ), sliderImg = document.createElement( "span" ); sliderImg.className = ["ui-slider-label ui-slider-label-", side, sliderTheme, " ui-btn-corner-all"].join( "" ); sliderImg.setAttribute( "role", "img" ); sliderImg.appendChild( document.createTextNode( options[i].innerHTML ) ); $( sliderImg ).prependTo( slider ); } self._labels = $( ".ui-slider-label", slider ); } label.addClass( "ui-slider" ); // monitor the input for updated values control.addClass( this.isToggleSwitch ? "ui-slider-switch" : "ui-slider-input" ); this._on( control, { "change": "_controlChange", "keyup": "_controlKeyup", "blur": "_controlBlur", "vmouseup": "_controlVMouseUp" }); slider.bind( "vmousedown", $.proxy( this._sliderVMouseDown, this ) ) .bind( "vclick", false ); // We have to instantiate a new function object for the unbind to work properly // since the method itself is defined in the prototype (causing it to unbind everything) this._on( document, { "vmousemove": "_preventDocumentDrag" }); this._on( slider.add( document ), { "vmouseup": "_sliderVMouseUp" }); slider.insertAfter( control ); // wrap in a div for styling purposes if ( !this.isToggleSwitch && !isRangeslider ) { wrapper = this.options.mini ? "<div class='ui-slider ui-mini'>" : "<div class='ui-slider'>"; control.add( slider ).wrapAll( wrapper ); } // Only add focus class to toggle switch, sliders get it automatically from ui-btn if ( this.isToggleSwitch ) { this.handle.bind({ focus: function() { slider.addClass( $.mobile.focusClass ); }, blur: function() { slider.removeClass( $.mobile.focusClass ); } }); } // bind the handle event callbacks and set the context to the widget instance this._on( this.handle, { "vmousedown": "_handleVMouseDown", "keydown": "_handleKeydown", "keyup": "_handleKeyup" }); this.handle.bind( "vclick", false ); this._handleFormReset(); this.refresh( undefined, undefined, true ); }, _controlChange: function( event ) { // if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again if ( this._trigger( "controlchange", event ) === false ) { return false; } if ( !this.mouseMoved ) { this.refresh( this._value(), true ); } }, _controlKeyup: function( event ) { // necessary? this.refresh( this._value(), true, true ); }, _controlBlur: function( event ) { this.refresh( this._value(), true ); }, // it appears the clicking the up and down buttons in chrome on // range/number inputs doesn't trigger a change until the field is // blurred. Here we check thif the value has changed and refresh _controlVMouseUp: function( event ) { this._checkedRefresh(); }, // NOTE force focus on handle _handleVMouseDown: function( event ) { this.handle.focus(); }, _handleKeydown: function( event ) { var index = this._value(); if ( this.options.disabled ) { return; } // In all cases prevent the default and mark the handle as active switch ( event.keyCode ) { case $.mobile.keyCode.HOME: case $.mobile.keyCode.END: case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; this.handle.addClass( "ui-state-active" ); } break; } // move the slider according to the keypress switch ( event.keyCode ) { case $.mobile.keyCode.HOME: this.refresh( this.min ); break; case $.mobile.keyCode.END: this.refresh( this.max ); break; case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: this.refresh( index + this.step ); break; case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: this.refresh( index - this.step ); break; } }, // remove active mark _handleKeyup: function( event ) { if ( this._keySliding ) { this._keySliding = false; this.handle.removeClass( "ui-state-active" ); } }, _sliderVMouseDown: function( event ) { // NOTE: we don't do this in refresh because we still want to // support programmatic alteration of disabled inputs if ( this.options.disabled || !( event.which === 1 || event.which === 0 || event.which === undefined ) ) { return false; } if ( this._trigger( "beforestart", event ) === false ) { return false; } this.dragging = true; this.userModified = false; this.mouseMoved = false; if ( this.isToggleSwitch ) { this.beforeStart = this.element[0].selectedIndex; } this.refresh( event ); this._trigger( "start" ); return false; }, _sliderVMouseUp: function() { if ( this.dragging ) { this.dragging = false; if ( this.isToggleSwitch ) { // make the handle move with a smooth transition this.handle.addClass( "ui-slider-handle-snapping" ); if ( this.mouseMoved ) { // this is a drag, change the value only if user dragged enough if ( this.userModified ) { this.refresh( this.beforeStart === 0 ? 1 : 0 ); } else { this.refresh( this.beforeStart ); } } else { // this is just a click, change the value this.refresh( this.beforeStart === 0 ? 1 : 0 ); } } this.mouseMoved = false; this._trigger( "stop" ); return false; } }, _preventDocumentDrag: function( event ) { // NOTE: we don't do this in refresh because we still want to // support programmatic alteration of disabled inputs if ( this._trigger( "drag", event ) === false) { return false; } if ( this.dragging && !this.options.disabled ) { // this.mouseMoved must be updated before refresh() because it will be used in the control "change" event this.mouseMoved = true; if ( this.isToggleSwitch ) { // make the handle move in sync with the mouse this.handle.removeClass( "ui-slider-handle-snapping" ); } this.refresh( event ); // only after refresh() you can calculate this.userModified this.userModified = this.beforeStart !== this.element[0].selectedIndex; return false; } }, _checkedRefresh: function() { if ( this.value !== this._value() ) { this.refresh( this._value() ); } }, _value: function() { return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat( this.element.val() ) ; }, _reset: function() { this.refresh( undefined, false, true ); }, refresh: function( val, isfromControl, preventInputUpdate ) { // NOTE: we don't return here because we want to support programmatic // alteration of the input value, which should still update the slider var self = this, parentTheme = $.mobile.getInheritedTheme( this.element, "c" ), theme = this.options.theme || parentTheme, trackTheme = this.options.trackTheme || parentTheme, left, width, data, tol; self.slider[0].className = [ this.isToggleSwitch ? "ui-slider ui-slider-switch" : "ui-slider-track"," ui-btn-down-" + trackTheme,' ui-btn-corner-all', ( this.options.mini ) ? " ui-mini":""].join( "" ); if ( this.options.disabled || this.element.attr( "disabled" ) ) { this.disable(); } // set the stored value for comparison later this.value = this._value(); if ( this.options.highlight && !this.isToggleSwitch && this.slider.find( ".ui-slider-bg" ).length === 0 ) { this.valuebg = (function() { var bg = document.createElement( "div" ); bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all"; return $( bg ).prependTo( self.slider ); })(); } this.handle.buttonMarkup({ corners: true, theme: theme, shadow: true }); var pxStep, percent, control = this.element, isInput = !this.isToggleSwitch, optionElements = isInput ? [] : control.find( "option" ), min = isInput ? parseFloat( control.attr( "min" ) ) : 0, max = isInput ? parseFloat( control.attr( "max" ) ) : optionElements.length - 1, step = ( isInput && parseFloat( control.attr( "step" ) ) > 0 ) ? parseFloat( control.attr( "step" ) ) : 1; if ( typeof val === "object" ) { data = val; // a slight tolerance helped get to the ends of the slider tol = 8; left = this.slider.offset().left; width = this.slider.width(); pxStep = width/((max-min)/step); if ( !this.dragging || data.pageX < left - tol || data.pageX > left + width + tol ) { return; } if ( pxStep > 1 ) { percent = ( ( data.pageX - left ) / width ) * 100; } else { percent = Math.round( ( ( data.pageX - left ) / width ) * 100 ); } } else { if ( val == null ) { val = isInput ? parseFloat( control.val() || 0 ) : control[0].selectedIndex; } percent = ( parseFloat( val ) - min ) / ( max - min ) * 100; } if ( isNaN( percent ) ) { return; } var newval = ( percent / 100 ) * ( max - min ) + min; //from jQuery UI slider, the following source will round to the nearest step var valModStep = ( newval - min ) % step; var alignValue = newval - valModStep; if ( Math.abs( valModStep ) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } var percentPerStep = 100/((max-min)/step); // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see jQueryUI: #4124) newval = parseFloat( alignValue.toFixed(5) ); if ( typeof pxStep === "undefined" ) { pxStep = width / ( (max-min) / step ); } if ( pxStep > 1 && isInput ) { percent = ( newval - min ) * percentPerStep * ( 1 / step ); } if ( percent < 0 ) { percent = 0; } if ( percent > 100 ) { percent = 100; } if ( newval < min ) { newval = min; } if ( newval > max ) { newval = max; } this.handle.css( "left", percent + "%" ); this.handle[0].setAttribute( "aria-valuenow", isInput ? newval : optionElements.eq( newval ).attr( "value" ) ); this.handle[0].setAttribute( "aria-valuetext", isInput ? newval : optionElements.eq( newval ).getEncodedText() ); this.handle[0].setAttribute( "title", isInput ? newval : optionElements.eq( newval ).getEncodedText() ); if ( this.valuebg ) { this.valuebg.css( "width", percent + "%" ); } // drag the label widths if ( this._labels ) { var handlePercent = this.handle.width() / this.slider.width() * 100, aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100, bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 ); this._labels.each(function() { var ab = $( this ).is( ".ui-slider-label-a" ); $( this ).width( ( ab ? aPercent : bPercent ) + "%" ); }); } if ( !preventInputUpdate ) { var valueChanged = false; // update control"s value if ( isInput ) { valueChanged = control.val() !== newval; control.val( newval ); } else { valueChanged = control[ 0 ].selectedIndex !== newval; control[ 0 ].selectedIndex = newval; } if ( this._trigger( "beforechange", val ) === false) { return false; } if ( !isfromControl && valueChanged ) { control.trigger( "change" ); } } }, enable: function() { this.element.attr( "disabled", false ); this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); } }, $.mobile.behaviors.formReset ) ); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.slider.prototype.enhanceWithin( e.target, true ); }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.rangeslider", $.mobile.widget, { options: { theme: null, trackTheme: null, disabled: false, initSelector: ":jqmData(role='rangeslider')", mini: false, highlight: true }, _create: function() { var secondLabel, $el = this.element, elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider", _inputFirst = $el.find( "input" ).first(), _inputLast = $el.find( "input" ).last(), label = $el.find( "label" ).first(), _sliderFirst = $.data( _inputFirst.get(0), "mobileSlider" ).slider, _sliderLast = $.data( _inputLast.get(0), "mobileSlider" ).slider, firstHandle = $.data( _inputFirst.get(0), "mobileSlider" ).handle, _sliders = $( "<div class=\"ui-rangeslider-sliders\" />" ).appendTo( $el ); if ( $el.find( "label" ).length > 1 ) { secondLabel = $el.find( "label" ).last().hide(); } _inputFirst.addClass( "ui-rangeslider-first" ); _inputLast.addClass( "ui-rangeslider-last" ); $el.addClass( elClass ); _sliderFirst.appendTo( _sliders ); _sliderLast.appendTo( _sliders ); label.prependTo( $el ); firstHandle.prependTo( _sliderLast ); $.extend( this, { _inputFirst: _inputFirst, _inputLast: _inputLast, _sliderFirst: _sliderFirst, _sliderLast: _sliderLast, _targetVal: null, _sliderTarget: false, _sliders: _sliders, _proxy: false }); this.refresh(); this._on( this.element.find( "input.ui-slider-input" ), { "slidebeforestart": "_slidebeforestart", "slidestop": "_slidestop", "slidedrag": "_slidedrag", "slidebeforechange": "_change", "blur": "_change", "keyup": "_change" }); this._on({ "mousedown":"_change" }); this._on( this.element.closest( "form" ), { "reset":"_handleReset" }); this._on( firstHandle, { "vmousedown": "_dragFirstHandle" }); }, _handleReset: function(){ var self = this; //we must wait for the stack to unwind before updateing other wise sliders will not have updated yet setTimeout( function(){ self._updateHighlight(); },0); }, _dragFirstHandle: function( event ) { //if the first handle is dragged send the event to the first slider $.data( this._inputFirst.get(0), "mobileSlider" ).dragging = true; $.data( this._inputFirst.get(0), "mobileSlider" ).refresh( event ); return false; }, _slidedrag: function( event ) { var first = $( event.target ).is( this._inputFirst ), otherSlider = ( first ) ? this._inputLast : this._inputFirst; this._sliderTarget = false; //if the drag was initiated on an extreme and the other handle is focused send the events to //the closest handle if ( ( this._proxy === "first" && first ) || ( this._proxy === "last" && !first ) ) { $.data( otherSlider.get(0), "mobileSlider" ).dragging = true; $.data( otherSlider.get(0), "mobileSlider" ).refresh( event ); return false; } }, _slidestop: function( event ) { var first = $( event.target ).is( this._inputFirst ); this._proxy = false; //this stops dragging of the handle and brings the active track to the front //this makes clicks on the track go the the last handle used this.element.find( "input" ).trigger( "vmouseup" ); this._sliderFirst.css( "z-index", first ? 1 : "" ); }, _slidebeforestart: function( event ) { this._sliderTarget = false; //if the track is the target remember this and the original value if ( $( event.originalEvent.target ).hasClass( "ui-slider-track" ) ) { this._sliderTarget = true; this._targetVal = $( event.target ).val(); } }, _setOption: function( options ) { this._superApply( options ); this.refresh(); }, refresh: function() { var $el = this.element, o = this.options; $el.find( "input" ).slider({ theme: o.theme, trackTheme: o.trackTheme, disabled: o.disabled, mini: o.mini, highlight: o.highlight }).slider( "refresh" ); this._updateHighlight(); }, _change: function( event ) { if ( event.type === "keyup" ) { this._updateHighlight(); return false; } var self = this, min = parseFloat( this._inputFirst.val(), 10 ), max = parseFloat( this._inputLast.val(), 10 ), first = $( event.target ).hasClass( "ui-rangeslider-first" ), thisSlider = first ? this._inputFirst : this._inputLast, otherSlider = first ? this._inputLast : this._inputFirst; if( ( this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle")) ){ thisSlider.blur(); } else if( event.type === "mousedown" ){ return; } if ( min > max && !this._sliderTarget ) { //this prevents min from being greater then max thisSlider.val( first ? max: min ).slider( "refresh" ); this._trigger( "normalize" ); } else if ( min > max ) { //this makes it so clicks on the target on either extreme go to the closest handle thisSlider.val( this._targetVal ).slider( "refresh" ); //You must wait for the stack to unwind so first slider is updated before updating second setTimeout( function() { otherSlider.val( first ? min: max ).slider( "refresh" ); $.data( otherSlider.get(0), "mobileSlider" ).handle.focus(); self._sliderFirst.css( "z-index", first ? "" : 1 ); self._trigger( "normalize" ); }, 0 ); this._proxy = ( first ) ? "first" : "last"; } //fixes issue where when both _sliders are at min they cannot be adjusted if ( min === max ) { $.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", 1 ); $.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", 0 ); } else { $.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" ); $.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" ); } this._updateHighlight(); if ( min >= max ) { return false; } }, _updateHighlight: function() { var min = parseInt( $.data( this._inputFirst.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ), max = parseInt( $.data( this._inputLast.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ), width = (max - min); this.element.find( ".ui-slider-bg" ).css({ "margin-left": min + "%", "width": width + "%" }); }, _destroy: function() { this.element.removeClass( "ui-rangeslider ui-mini" ).find( "label" ).show(); this._inputFirst.after( this._sliderFirst ); this._inputLast.after( this._sliderLast ); this._sliders.remove(); this.element.find( "input" ).removeClass( "ui-rangeslider-first ui-rangeslider-last" ).slider( "destroy" ); } }); $.widget( "mobile.rangeslider", $.mobile.rangeslider, $.mobile.behaviors.formReset ); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ) { $.mobile.rangeslider.prototype.enhanceWithin( e.target, true ); }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.selectmenu", $.mobile.widget, $.extend( { options: { theme: null, disabled: false, icon: "arrow-d", iconpos: "right", inline: false, corners: true, shadow: true, iconshadow: true, overlayTheme: "a", dividerTheme: "b", hidePlaceholderMenuItems: true, closeText: "Close", nativeMenu: true, // This option defaults to true on iOS devices. preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1, initSelector: "select:not( :jqmData(role='slider') )", mini: false }, _button: function() { return $( "<div/>" ); }, _setDisabled: function( value ) { this.element.attr( "disabled", value ); this.button.attr( "aria-disabled", value ); return this._setOption( "disabled", value ); }, _focusButton : function() { var self = this; setTimeout( function() { self.button.focus(); }, 40); }, _selectOptions: function() { return this.select.find( "option" ); }, // setup items that are generally necessary for select menu extension _preExtension: function() { var classes = ""; // TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577 /* if ( $el[0].className.length ) { classes = $el[0].className; } */ if ( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) { classes = " ui-btn-left"; } if ( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) { classes = " ui-btn-right"; } this.select = this.element.removeClass( "ui-btn-left ui-btn-right" ).wrap( "<div class='ui-select" + classes + "'>" ); this.selectID = this.select.attr( "id" ); this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" ); this.isMultiple = this.select[ 0 ].multiple; if ( !this.options.theme ) { this.options.theme = $.mobile.getInheritedTheme( this.select, "c" ); } }, _destroy: function() { var wrapper = this.element.parents( ".ui-select" ); if ( wrapper.length > 0 ) { if ( wrapper.is( ".ui-btn-left, .ui-btn-right" ) ) { this.element.addClass( wrapper.is( ".ui-btn-left" ) ? "ui-btn-left" : "ui-btn-right" ); } this.element.insertAfter( wrapper ); wrapper.remove(); } }, _create: function() { this._preExtension(); // Allows for extension of the native select for custom selects and other plugins // see select.custom for example extension // TODO explore plugin registration this._trigger( "beforeCreate" ); this.button = this._button(); var self = this, options = this.options, inline = options.inline || this.select.jqmData( "inline" ), mini = options.mini || this.select.jqmData( "mini" ), iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false, // IE throws an exception at options.item() function when // there is no selected item // select first in this case selectedIndex = this.select[ 0 ].selectedIndex === -1 ? 0 : this.select[ 0 ].selectedIndex, // TODO values buttonId and menuId are undefined here button = this.button .insertBefore( this.select ) .buttonMarkup( { theme: options.theme, icon: options.icon, iconpos: iconpos, inline: inline, corners: options.corners, shadow: options.shadow, iconshadow: options.iconshadow, mini: mini }); this.setButtonText(); // Opera does not properly support opacity on select elements // In Mini, it hides the element, but not its text // On the desktop,it seems to do the opposite // for these reasons, using the nativeMenu option results in a full native select in Opera if ( options.nativeMenu && window.opera && window.opera.version ) { button.addClass( "ui-select-nativeonly" ); } // Add counter for multi selects if ( this.isMultiple ) { this.buttonCount = $( "<span>" ) .addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" ) .hide() .appendTo( button.addClass('ui-li-has-count') ); } // Disable if specified if ( options.disabled || this.element.attr('disabled')) { this.disable(); } // Events on native select this.select.change(function() { self.refresh(); if ( !!options.nativeMenu ) { this.blur(); } }); this._handleFormReset(); this.build(); }, build: function() { var self = this; this.select .appendTo( self.button ) .bind( "vmousedown", function() { // Add active class to button self.button.addClass( $.mobile.activeBtnClass ); }) .bind( "focus", function() { self.button.addClass( $.mobile.focusClass ); }) .bind( "blur", function() { self.button.removeClass( $.mobile.focusClass ); }) .bind( "focus vmouseover", function() { self.button.trigger( "vmouseover" ); }) .bind( "vmousemove", function() { // Remove active class on scroll/touchmove self.button.removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur vmouseout", function() { self.button.trigger( "vmouseout" ) .removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur", function() { self.button.removeClass( "ui-btn-down-" + self.options.theme ); }); // In many situations, iOS will zoom into the select upon tap, this prevents that from happening self.button.bind( "vmousedown", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.label.bind( "click focus", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.select.bind( "focus", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.button.bind( "mouseup", function() { if ( self.options.preventFocusZoom ) { setTimeout(function() { $.mobile.zoom.enable( true ); }, 0 ); } }); self.select.bind( "blur", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.enable( true ); } }); }, selected: function() { return this._selectOptions().filter( ":selected" ); }, selectedIndices: function() { var self = this; return this.selected().map(function() { return self._selectOptions().index( this ); }).get(); }, setButtonText: function() { var self = this, selected = this.selected(), text = this.placeholder, span = $( document.createElement( "span" ) ); this.button.find( ".ui-btn-text" ).html(function() { if ( selected.length ) { text = selected.map(function() { return $( this ).text(); }).get().join( ", " ); } else { text = self.placeholder; } // TODO possibly aggregate multiple select option classes return span.text( text ) .addClass( self.select.attr( "class" ) ) .addClass( selected.attr( "class" ) ); }); }, setButtonCount: function() { var selected = this.selected(); // multiple count inside button if ( this.isMultiple ) { this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length ); } }, _reset: function() { this.refresh(); }, refresh: function() { this.setButtonText(); this.setButtonCount(); }, // open and close preserved in native selects // to simplify users code when looping over selects open: $.noop, close: $.noop, disable: function() { this._setDisabled( true ); this.button.addClass( "ui-disabled" ); }, enable: function() { this._setDisabled( false ); this.button.removeClass( "ui-disabled" ); } }, $.mobile.behaviors.formReset ) ); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.selectmenu.prototype.enhanceWithin( e.target, true ); }); })( jQuery ); (function( $, undefined ) { function fitSegmentInsideSegment( winSize, segSize, offset, desired ) { var ret = desired; if ( winSize < segSize ) { // Center segment if it's bigger than the window ret = offset + ( winSize - segSize ) / 2; } else { // Otherwise center it at the desired coordinate while keeping it completely inside the window ret = Math.min( Math.max( offset, desired - segSize / 2 ), offset + winSize - segSize ); } return ret; } function windowCoords() { var $win = $.mobile.window; return { x: $win.scrollLeft(), y: $win.scrollTop(), cx: ( window.innerWidth || $win.width() ), cy: ( window.innerHeight || $win.height() ) }; } $.widget( "mobile.popup", $.mobile.widget, { options: { theme: null, overlayTheme: null, shadow: true, corners: true, transition: "none", positionTo: "origin", tolerance: null, initSelector: ":jqmData(role='popup')", closeLinkSelector: "a:jqmData(rel='back')", closeLinkEvents: "click.popup", navigateEvents: "navigate.popup", closeEvents: "navigate.popup pagebeforechange.popup", dismissible: true, // NOTE Windows Phone 7 has a scroll position caching issue that // requires us to disable popup history management by default // https://github.com/jquery/jquery-mobile/issues/4784 // // NOTE this option is modified in _create! history: !$.mobile.browser.oldIE }, _eatEventAndClose: function( e ) { e.preventDefault(); e.stopImmediatePropagation(); if ( this.options.dismissible ) { this.close(); } return false; }, // Make sure the screen size is increased beyond the page height if the popup's causes the document to increase in height _resizeScreen: function() { var popupHeight = this._ui.container.outerHeight( true ); this._ui.screen.removeAttr( "style" ); if ( popupHeight > this._ui.screen.height() ) { this._ui.screen.height( popupHeight ); } }, _handleWindowKeyUp: function( e ) { if ( this._isOpen && e.keyCode === $.mobile.keyCode.ESCAPE ) { return this._eatEventAndClose( e ); } }, _expectResizeEvent: function() { var winCoords = windowCoords(); if ( this._resizeData ) { if ( winCoords.x === this._resizeData.winCoords.x && winCoords.y === this._resizeData.winCoords.y && winCoords.cx === this._resizeData.winCoords.cx && winCoords.cy === this._resizeData.winCoords.cy ) { // timeout not refreshed return false; } else { // clear existing timeout - it will be refreshed below clearTimeout( this._resizeData.timeoutId ); } } this._resizeData = { timeoutId: setTimeout( $.proxy( this, "_resizeTimeout" ), 200 ), winCoords: winCoords }; return true; }, _resizeTimeout: function() { if ( this._isOpen ) { if ( !this._expectResizeEvent() ) { if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-open the popup while leaving the screen intact this._ui.container.removeClass( "ui-popup-hidden" ); this.reposition( { positionTo: "window" } ); this._ignoreResizeEvents(); } this._resizeScreen(); this._resizeData = null; this._orientationchangeInProgress = false; } } else { this._resizeData = null; this._orientationchangeInProgress = false; } }, _ignoreResizeEvents: function() { var self = this; if ( this._ignoreResizeTo ) { clearTimeout( this._ignoreResizeTo ); } this._ignoreResizeTo = setTimeout( function() { self._ignoreResizeTo = 0; }, 1000 ); }, _handleWindowResize: function( e ) { if ( this._isOpen && this._ignoreResizeTo === 0 ) { if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) && !this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-close the popup while leaving the screen intact this._ui.container .addClass( "ui-popup-hidden" ) .removeAttr( "style" ); } } }, _handleWindowOrientationchange: function( e ) { if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) { this._expectResizeEvent(); this._orientationchangeInProgress = true; } }, // When the popup is open, attempting to focus on an element that is not a // child of the popup will redirect focus to the popup _handleDocumentFocusIn: function( e ) { var tgt = e.target, $tgt, ui = this._ui; if ( !this._isOpen ) { return; } if ( tgt !== ui.container[ 0 ] ) { $tgt = $( e.target ); if ( 0 === $tgt.parents().filter( ui.container[ 0 ] ).length ) { $( document.activeElement ).one( "focus", function( e ) { $tgt.blur(); }); ui.focusElement.focus(); e.preventDefault(); e.stopImmediatePropagation(); return false; } else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) { ui.focusElement = $tgt; } } this._ignoreResizeEvents(); }, _create: function() { var ui = { screen: $( "<div class='ui-screen-hidden ui-popup-screen'></div>" ), placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ), container: $( "<div class='ui-popup-container ui-popup-hidden'></div>" ) }, thisPage = this.element.closest( ".ui-page" ), myId = this.element.attr( "id" ), o = this.options, key, value; // We need to adjust the history option to be false if there's no AJAX nav. // We can't do it in the option declarations because those are run before // it is determined whether there shall be AJAX nav. o.history = o.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled; if ( thisPage.length === 0 ) { thisPage = $( "body" ); } // define the container for navigation event bindings // TODO this would be nice at the the mobile widget level o.container = o.container || $.mobile.pageContainer || thisPage; // Apply the proto thisPage.append( ui.screen ); ui.container.insertAfter( ui.screen ); // Leave a placeholder where the element used to be ui.placeholder.insertAfter( this.element ); if ( myId ) { ui.screen.attr( "id", myId + "-screen" ); ui.container.attr( "id", myId + "-popup" ); ui.placeholder.html( "<!-- placeholder for " + myId + " -->" ); } ui.container.append( this.element ); ui.focusElement = ui.container; // Add class to popup element this.element.addClass( "ui-popup" ); // Define instance variables $.extend( this, { _scrollTop: 0, _page: thisPage, _ui: ui, _fallbackTransition: "", _currentTransition: false, _prereqs: null, _isOpen: false, _tolerance: null, _resizeData: null, _ignoreResizeTo: 0, _orientationchangeInProgress: false }); // This duplicates the code from the various option setters below for // better performance. It must be kept in sync with those setters. this._applyTheme( this.element, o.theme, "body" ); this._applyTheme( this._ui.screen, o.overlayTheme, "overlay" ); this._applyTransition( o.transition ); this.element .toggleClass( "ui-overlay-shadow", o.shadow ) .toggleClass( "ui-corner-all", o.corners ); this._setTolerance( o.tolerance ); ui.screen.bind( "vclick", $.proxy( this, "_eatEventAndClose" ) ); this._on( $.mobile.window, { orientationchange: $.proxy( this, "_handleWindowOrientationchange" ), resize: $.proxy( this, "_handleWindowResize" ), keyup: $.proxy( this, "_handleWindowKeyUp" ) }); this._on( $.mobile.document, { focusin: $.proxy( this, "_handleDocumentFocusIn" ) }); }, _applyTheme: function( dst, theme, prefix ) { var classes = ( dst.attr( "class" ) || "").split( " " ), alreadyAdded = true, currentTheme = null, matches, themeStr = String( theme ); while ( classes.length > 0 ) { currentTheme = classes.pop(); matches = ( new RegExp( "^ui-" + prefix + "-([a-z])$" ) ).exec( currentTheme ); if ( matches && matches.length > 1 ) { currentTheme = matches[ 1 ]; break; } else { currentTheme = null; } } if ( theme !== currentTheme ) { dst.removeClass( "ui-" + prefix + "-" + currentTheme ); if ( ! ( theme === null || theme === "none" ) ) { dst.addClass( "ui-" + prefix + "-" + themeStr ); } } }, _setTheme: function( value ) { this._applyTheme( this.element, value, "body" ); }, _setOverlayTheme: function( value ) { this._applyTheme( this._ui.screen, value, "overlay" ); if ( this._isOpen ) { this._ui.screen.addClass( "in" ); } }, _setShadow: function( value ) { this.element.toggleClass( "ui-overlay-shadow", value ); }, _setCorners: function( value ) { this.element.toggleClass( "ui-corner-all", value ); }, _applyTransition: function( value ) { this._ui.container.removeClass( this._fallbackTransition ); if ( value && value !== "none" ) { this._fallbackTransition = $.mobile._maybeDegradeTransition( value ); if ( this._fallbackTransition === "none" ) { this._fallbackTransition = ""; } this._ui.container.addClass( this._fallbackTransition ); } }, _setTransition: function( value ) { if ( !this._currentTransition ) { this._applyTransition( value ); } }, _setTolerance: function( value ) { var tol = { t: 30, r: 15, b: 30, l: 15 }; if ( value !== undefined ) { var ar = String( value ).split( "," ); $.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } ); switch( ar.length ) { // All values are to be the same case 1: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.r = tol.b = tol.l = ar[ 0 ]; } break; // The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance case 2: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.b = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.l = tol.r = ar[ 1 ]; } break; // The array contains values in the order top, right, bottom, left case 4: if ( !isNaN( ar[ 0 ] ) ) { tol.t = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.r = ar[ 1 ]; } if ( !isNaN( ar[ 2 ] ) ) { tol.b = ar[ 2 ]; } if ( !isNaN( ar[ 3 ] ) ) { tol.l = ar[ 3 ]; } break; default: break; } } this._tolerance = tol; }, _setOption: function( key, value ) { var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 ); if ( this[ setter ] !== undefined ) { this[ setter ]( value ); } this._super( key, value ); }, // Try and center the overlay over the given coordinates _placementCoords: function( desired ) { // rectangle within which the popup must fit var winCoords = windowCoords(), rc = { x: this._tolerance.l, y: winCoords.y + this._tolerance.t, cx: winCoords.cx - this._tolerance.l - this._tolerance.r, cy: winCoords.cy - this._tolerance.t - this._tolerance.b }, menuSize, ret; // Clamp the width of the menu before grabbing its size this._ui.container.css( "max-width", rc.cx ); menuSize = { cx: this._ui.container.outerWidth( true ), cy: this._ui.container.outerHeight( true ) }; // Center the menu over the desired coordinates, while not going outside // the window tolerances. This will center wrt. the window if the popup is too large. ret = { x: fitSegmentInsideSegment( rc.cx, menuSize.cx, rc.x, desired.x ), y: fitSegmentInsideSegment( rc.cy, menuSize.cy, rc.y, desired.y ) }; // Make sure the top of the menu is visible ret.y = Math.max( 0, ret.y ); // If the height of the menu is smaller than the height of the document // align the bottom with the bottom of the document // fix for $.mobile.document.height() bug in core 1.7.2. var docEl = document.documentElement, docBody = document.body, docHeight = Math.max( docEl.clientHeight, docBody.scrollHeight, docBody.offsetHeight, docEl.scrollHeight, docEl.offsetHeight ); ret.y -= Math.min( ret.y, Math.max( 0, ret.y + menuSize.cy - docHeight ) ); return { left: ret.x, top: ret.y }; }, _createPrereqs: function( screenPrereq, containerPrereq, whenDone ) { var self = this, prereqs; // It is important to maintain both the local variable prereqs and self._prereqs. The local variable remains in // the closure of the functions which call the callbacks passed in. The comparison between the local variable and // self._prereqs is necessary, because once a function has been passed to .animationComplete() it will be called // next time an animation completes, even if that's not the animation whose end the function was supposed to catch // (for example, if an abort happens during the opening animation, the .animationComplete handler is not called for // that animation anymore, but the handler remains attached, so it is called the next time the popup is opened // - making it stale. Comparing the local variable prereqs to the widget-level variable self._prereqs ensures that // callbacks triggered by a stale .animationComplete will be ignored. prereqs = { screen: $.Deferred(), container: $.Deferred() }; prereqs.screen.then( function() { if ( prereqs === self._prereqs ) { screenPrereq(); } }); prereqs.container.then( function() { if ( prereqs === self._prereqs ) { containerPrereq(); } }); $.when( prereqs.screen, prereqs.container ).done( function() { if ( prereqs === self._prereqs ) { self._prereqs = null; whenDone(); } }); self._prereqs = prereqs; }, _animate: function( args ) { // NOTE before removing the default animation of the screen // this had an animate callback that would resolve the deferred // now the deferred is resolved immediately // TODO remove the dependency on the screen deferred this._ui.screen .removeClass( args.classToRemove ) .addClass( args.screenClassToAdd ); args.prereqs.screen.resolve(); if ( args.transition && args.transition !== "none" ) { if ( args.applyTransition ) { this._applyTransition( args.transition ); } if ( this._fallbackTransition ) { this._ui.container .animationComplete( $.proxy( args.prereqs.container, "resolve" ) ) .addClass( args.containerClassToAdd ) .removeClass( args.classToRemove ); return; } } this._ui.container.removeClass( args.classToRemove ); args.prereqs.container.resolve(); }, // The desired coordinates passed in will be returned untouched if no reference element can be identified via // desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid // x and y coordinates by specifying the center middle of the window if the coordinates are absent. // options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector _desiredCoords: function( o ) { var dst = null, offset, winCoords = windowCoords(), x = o.x, y = o.y, pTo = o.positionTo; // Establish which element will serve as the reference if ( pTo && pTo !== "origin" ) { if ( pTo === "window" ) { x = winCoords.cx / 2 + winCoords.x; y = winCoords.cy / 2 + winCoords.y; } else { try { dst = $( pTo ); } catch( e ) { dst = null; } if ( dst ) { dst.filter( ":visible" ); if ( dst.length === 0 ) { dst = null; } } } } // If an element was found, center over it if ( dst ) { offset = dst.offset(); x = offset.left + dst.outerWidth() / 2; y = offset.top + dst.outerHeight() / 2; } // Make sure x and y are valid numbers - center over the window if ( $.type( x ) !== "number" || isNaN( x ) ) { x = winCoords.cx / 2 + winCoords.x; } if ( $.type( y ) !== "number" || isNaN( y ) ) { y = winCoords.cy / 2 + winCoords.y; } return { x: x, y: y }; }, _reposition: function( o ) { // We only care about position-related parameters for repositioning o = { x: o.x, y: o.y, positionTo: o.positionTo }; this._trigger( "beforeposition", undefined, o ); this._ui.container.offset( this._placementCoords( this._desiredCoords( o ) ) ); }, reposition: function( o ) { if ( this._isOpen ) { this._reposition( o ); } }, _openPrereqsComplete: function() { this._ui.container.addClass( "ui-popup-active" ); this._isOpen = true; this._resizeScreen(); this._ui.container.attr( "tabindex", "0" ).focus(); this._ignoreResizeEvents(); this._trigger( "afteropen" ); }, _open: function( options ) { var o = $.extend( {}, this.options, options ), // TODO move blacklist to private method androidBlacklist = ( function() { var w = window, ua = navigator.userAgent, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ), andversion = !!androidmatch && androidmatch[ 1 ], chromematch = ua.indexOf( "Chrome" ) > -1; // Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome. if( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) { return true; } return false; }()); // Count down to triggering "popupafteropen" - we have two prerequisites: // 1. The popup window animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrereqs( $.noop, $.noop, $.proxy( this, "_openPrereqsComplete" ) ); this._currentTransition = o.transition; this._applyTransition( o.transition ); if ( !this.options.theme ) { this._setTheme( this._page.jqmData( "theme" ) || $.mobile.getInheritedTheme( this._page, "c" ) ); } this._ui.screen.removeClass( "ui-screen-hidden" ); this._ui.container.removeClass( "ui-popup-hidden" ); // Give applications a chance to modify the contents of the container before it appears this._reposition( o ); if ( this.options.overlayTheme && androidBlacklist ) { /* TODO: The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser: https://github.com/scottjehl/Device-Bugs/issues/3 This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ): https://github.com/jquery/jquery-mobile/issues/4816 https://github.com/jquery/jquery-mobile/issues/4844 https://github.com/jquery/jquery-mobile/issues/4874 */ // TODO sort out why this._page isn't working this.element.closest( ".ui-page" ).addClass( "ui-popup-open" ); } this._animate({ additionalCondition: true, transition: o.transition, classToRemove: "", screenClassToAdd: "in", containerClassToAdd: "in", applyTransition: false, prereqs: this._prereqs }); }, _closePrereqScreen: function() { this._ui.screen .removeClass( "out" ) .addClass( "ui-screen-hidden" ); }, _closePrereqContainer: function() { this._ui.container .removeClass( "reverse out" ) .addClass( "ui-popup-hidden" ) .removeAttr( "style" ); }, _closePrereqsDone: function() { var container = this._ui.container; container.removeAttr( "tabindex" ); // remove the global mutex for popups $.mobile.popup.active = undefined; // Blur elements inside the container, including the container $( ":focus", container[ 0 ] ).add( container[ 0 ] ).blur(); // alert users that the popup is closed this._trigger( "afterclose" ); }, _close: function( immediate ) { this._ui.container.removeClass( "ui-popup-active" ); this._page.removeClass( "ui-popup-open" ); this._isOpen = false; // Count down to triggering "popupafterclose" - we have two prerequisites: // 1. The popup window reverse animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrereqs( $.proxy( this, "_closePrereqScreen" ), $.proxy( this, "_closePrereqContainer" ), $.proxy( this, "_closePrereqsDone" ) ); this._animate( { additionalCondition: this._ui.screen.hasClass( "in" ), transition: ( immediate ? "none" : ( this._currentTransition ) ), classToRemove: "in", screenClassToAdd: "out", containerClassToAdd: "reverse out", applyTransition: true, prereqs: this._prereqs }); }, _unenhance: function() { // Put the element back to where the placeholder was and remove the "ui-popup" class this._setTheme( "none" ); this.element // Cannot directly insertAfter() - we need to detach() first, because // insertAfter() will do nothing if the payload div was not attached // to the DOM at the time the widget was created, and so the payload // will remain inside the container even after we call insertAfter(). // If that happens and we remove the container a few lines below, we // will cause an infinite recursion - #5244 .detach() .insertAfter( this._ui.placeholder ) .removeClass( "ui-popup ui-overlay-shadow ui-corner-all" ); this._ui.screen.remove(); this._ui.container.remove(); this._ui.placeholder.remove(); }, _destroy: function() { if ( $.mobile.popup.active === this ) { this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) ); this.close(); } else { this._unenhance(); } }, _closePopup: function( e, data ) { var parsedDst, toUrl, o = this.options, immediate = false; // restore location on screen window.scrollTo( 0, this._scrollTop ); if ( e && e.type === "pagebeforechange" && data ) { // Determine whether we need to rapid-close the popup, or whether we can // take the time to run the closing transition if ( typeof data.toPage === "string" ) { parsedDst = data.toPage; } else { parsedDst = data.toPage.jqmData( "url" ); } parsedDst = $.mobile.path.parseUrl( parsedDst ); toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash; if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) { // Going to a different page - close immediately immediate = true; } else { e.preventDefault(); } } // remove nav bindings o.container.unbind( o.closeEvents ); // unbind click handlers added when history is disabled this.element.undelegate( o.closeLinkSelector, o.closeLinkEvents ); this._close( immediate ); }, // any navigation event after a popup is opened should close the popup // NOTE the pagebeforechange is bound to catch navigation events that don't // alter the url (eg, dialogs from popups) _bindContainerClose: function() { this.options.container .one( this.options.closeEvents, $.proxy( this, "_closePopup" ) ); }, // TODO no clear deliniation of what should be here and // what should be in _open. Seems to be "visual" vs "history" for now open: function( options ) { var self = this, opts = this.options, url, hashkey, activePage, currentIsDialog, hasHash, urlHistory; // make sure open is idempotent if( $.mobile.popup.active ) { return; } // set the global popup mutex $.mobile.popup.active = this; this._scrollTop = $.mobile.window.scrollTop(); // if history alteration is disabled close on navigate events // and leave the url as is if( !( opts.history ) ) { self._open( options ); self._bindContainerClose(); // When histoy is disabled we have to grab the data-rel // back link clicks so we can close the popup instead of // relying on history to do it for us self.element .delegate( opts.closeLinkSelector, opts.closeLinkEvents, function( e ) { self.close(); e.preventDefault(); }); return; } // cache some values for min/readability urlHistory = $.mobile.urlHistory; hashkey = $.mobile.dialogHashKey; activePage = $.mobile.activePage; currentIsDialog = activePage.is( ".ui-dialog" ); this._myUrl = url = urlHistory.getActive().url; hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 ); if ( hasHash ) { self._open( options ); self._bindContainerClose(); return; } // if the current url has no dialog hash key proceed as normal // otherwise, if the page is a dialog simply tack on the hash key if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ){ url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey); } else { url = $.mobile.path.parseLocation().hash + hashkey; } // Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) { url += hashkey; } // swallow the the initial navigation event, and bind for the next $(window).one( "beforenavigate", function( e ) { e.preventDefault(); self._open( options ); self._bindContainerClose(); }); this.urlAltered = true; $.mobile.navigate( url, {role: "dialog"} ); }, close: function() { // make sure close is idempotent if( $.mobile.popup.active !== this ) { return; } this._scrollTop = $.mobile.window.scrollTop(); if( this.options.history && this.urlAltered ) { $.mobile.back(); this.urlAltered = false; } else { // simulate the nav bindings having fired this._closePopup(); } } }); // TODO this can be moved inside the widget $.mobile.popup.handleLink = function( $link ) { var closestPage = $link.closest( ":jqmData(role='page')" ), scope = ( ( closestPage.length === 0 ) ? $( "body" ) : closestPage ), // NOTE make sure to get only the hash, ie7 (wp7) return the absolute href // in this case ruining the element selection popup = $( $.mobile.path.parseUrl($link.attr( "href" )).hash, scope[0] ), offset; if ( popup.data( "mobile-popup" ) ) { offset = $link.offset(); popup.popup( "open", { x: offset.left + $link.outerWidth() / 2, y: offset.top + $link.outerHeight() / 2, transition: $link.jqmData( "transition" ), positionTo: $link.jqmData( "position-to" ) }); } //remove after delay setTimeout( function() { // Check if we are in a listview var $parent = $link.parent().parent(); if ($parent.hasClass("ui-li")) { $link = $parent.parent(); } $link.removeClass( $.mobile.activeBtnClass ); }, 300 ); }; // TODO move inside _create $.mobile.document.bind( "pagebeforechange", function( e, data ) { if ( data.options.role === "popup" ) { $.mobile.popup.handleLink( data.options.link ); e.preventDefault(); } }); $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.popup.prototype.enhanceWithin( e.target, true ); }); })( jQuery ); /* * custom "selectmenu" plugin */ (function( $, undefined ) { var extendSelect = function( widget ) { var select = widget.select, origDestroy = widget._destroy, selectID = widget.selectID, prefix = ( selectID ? selectID : ( ( $.mobile.ns || "" ) + "uuid-" + widget.uuid ) ), popupID = prefix + "-listbox", dialogID = prefix + "-dialog", label = widget.label, thisPage = widget.select.closest( ".ui-page" ), selectOptions = widget._selectOptions(), isMultiple = widget.isMultiple = widget.select[ 0 ].multiple, buttonId = selectID + "-button", menuId = selectID + "-menu", menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' id='" + dialogID + "' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" + "<div data-" + $.mobile.ns + "role='header'>" + "<div class='ui-title'>" + label.getEncodedText() + "</div>"+ "</div>"+ "<div data-" + $.mobile.ns + "role='content'></div>"+ "</div>" ), listbox = $( "<div id='" + popupID + "' class='ui-selectmenu'>" ).insertAfter( widget.select ).popup( { theme: widget.options.overlayTheme } ), list = $( "<ul>", { "class": "ui-selectmenu-list", "id": menuId, "role": "listbox", "aria-labelledby": buttonId }).attr( "data-" + $.mobile.ns + "theme", widget.options.theme ) .attr( "data-" + $.mobile.ns + "divider-theme", widget.options.dividerTheme ) .appendTo( listbox ), header = $( "<div>", { "class": "ui-header ui-bar-" + widget.options.theme }).prependTo( listbox ), headerTitle = $( "<h1>", { "class": "ui-title" }).appendTo( header ), menuPageContent, menuPageClose, headerClose; if ( widget.isMultiple ) { headerClose = $( "<a>", { "text": widget.options.closeText, "href": "#", "class": "ui-btn-left" }).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup(); } $.extend( widget, { select: widget.select, selectID: selectID, buttonId: buttonId, menuId: menuId, popupID: popupID, dialogID: dialogID, thisPage: thisPage, menuPage: menuPage, label: label, selectOptions: selectOptions, isMultiple: isMultiple, theme: widget.options.theme, listbox: listbox, list: list, header: header, headerTitle: headerTitle, headerClose: headerClose, menuPageContent: menuPageContent, menuPageClose: menuPageClose, placeholder: "", build: function() { var self = this, escapeId = function( id ) { return id.replace( /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g, "\\$1" ); }; // Create list from select, update state self.refresh(); if ( self._origTabIndex === undefined ) { // Map undefined to false, because self._origTabIndex === undefined // indicates that we have not yet checked whether the select has // originally had a tabindex attribute, whereas false indicates that // we have checked the select for such an attribute, and have found // none present. self._origTabIndex = ( self.select[ 0 ].getAttribute( "tabindex" ) === null ) ? false : self.select.attr( "tabindex" ); } self.select.attr( "tabindex", "-1" ).focus(function() { $( this ).blur(); self.button.focus(); }); // Button events self.button.bind( "vclick keydown" , function( event ) { if ( self.options.disabled || self.isOpen ) { return; } if (event.type === "vclick" || event.keyCode && (event.keyCode === $.mobile.keyCode.ENTER || event.keyCode === $.mobile.keyCode.SPACE)) { self._decideFormat(); if ( self.menuType === "overlay" ) { self.button.attr( "href", "#" + escapeId( self.popupID ) ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "popup" ); } else { self.button.attr( "href", "#" + escapeId( self.dialogID ) ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "dialog" ); } self.isOpen = true; // Do not prevent default, so the navigation may have a chance to actually open the chosen format } }); // Events for list items self.list.attr( "role", "listbox" ) .bind( "focusin", function( e ) { $( e.target ) .attr( "tabindex", "0" ) .trigger( "vmouseover" ); }) .bind( "focusout", function( e ) { $( e.target ) .attr( "tabindex", "-1" ) .trigger( "vmouseout" ); }) .delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) { // index of option tag to be selected var oldIndex = self.select[ 0 ].selectedIndex, newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ), option = self._selectOptions().eq( newIndex )[ 0 ]; // toggle selected status on the tag for multi selects option.selected = self.isMultiple ? !option.selected : true; // toggle checkbox class for multiple selects if ( self.isMultiple ) { $( this ).find( ".ui-icon" ) .toggleClass( "ui-icon-checkbox-on", option.selected ) .toggleClass( "ui-icon-checkbox-off", !option.selected ); } // trigger change if value changed if ( self.isMultiple || oldIndex !== newIndex ) { self.select.trigger( "change" ); } // hide custom select for single selects only - otherwise focus clicked item // We need to grab the clicked item the hard way, because the list may have been rebuilt if ( self.isMultiple ) { self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex ) .addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus(); } else { self.close(); } event.preventDefault(); }) .keydown(function( event ) { //keyboard events for menu items var target = $( event.target ), li = target.closest( "li" ), prev, next; // switch logic based on which key was pressed switch ( event.keyCode ) { // up or left arrow keys case 38: prev = li.prev().not( ".ui-selectmenu-placeholder" ); if ( prev.is( ".ui-li-divider" ) ) { prev = prev.prev(); } // if there's a previous option, focus it if ( prev.length ) { target .blur() .attr( "tabindex", "-1" ); prev.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus(); } return false; // down or right arrow keys case 40: next = li.next(); if ( next.is( ".ui-li-divider" ) ) { next = next.next(); } // if there's a next option, focus it if ( next.length ) { target .blur() .attr( "tabindex", "-1" ); next.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus(); } return false; // If enter or space is pressed, trigger click case 13: case 32: target.trigger( "click" ); return false; } }); // button refocus ensures proper height calculation // by removing the inline style and ensuring page inclusion self.menuPage.bind( "pagehide", function() { // TODO centralize page removal binding / handling in the page plugin. // Suggestion from @jblas to do refcounting // // TODO extremely confusing dependency on the open method where the pagehide.remove // bindings are stripped to prevent the parent page from disappearing. The way // we're keeping pages in the DOM right now sucks // // rebind the page remove that was unbound in the open function // to allow for the parent page removal from actions other than the use // of a dialog sized custom select // // doing this here provides for the back button on the custom select dialog $.mobile._bindPageRemove.call( self.thisPage ); }); // Events on the popup self.listbox.bind( "popupafterclose", function( event ) { self.close(); }); // Close button on small overlays if ( self.isMultiple ) { self.headerClose.click(function() { if ( self.menuType === "overlay" ) { self.close(); return false; } }); } // track this dependency so that when the parent page // is removed on pagehide it will also remove the menupage self.thisPage.addDependents( this.menuPage ); }, _isRebuildRequired: function() { var list = this.list.find( "li" ), options = this._selectOptions(); // TODO exceedingly naive method to determine difference // ignores value changes etc in favor of a forcedRebuild // from the user in the refresh method return options.text() !== list.text(); }, selected: function() { return this._selectOptions().filter( ":selected:not( :jqmData(placeholder='true') )" ); }, refresh: function( forceRebuild , foo ) { var self = this, select = this.element, isMultiple = this.isMultiple, indicies; if ( forceRebuild || this._isRebuildRequired() ) { self._buildList(); } indicies = this.selectedIndices(); self.setButtonText(); self.setButtonCount(); self.list.find( "li:not(.ui-li-divider)" ) .removeClass( $.mobile.activeBtnClass ) .attr( "aria-selected", false ) .each(function( i ) { if ( $.inArray( i, indicies ) > -1 ) { var item = $( this ); // Aria selected attr item.attr( "aria-selected", true ); // Multiple selects: add the "on" checkbox state to the icon if ( self.isMultiple ) { item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" ); } else { if ( item.is( ".ui-selectmenu-placeholder" ) ) { item.next().addClass( $.mobile.activeBtnClass ); } else { item.addClass( $.mobile.activeBtnClass ); } } } }); }, close: function() { if ( this.options.disabled || !this.isOpen ) { return; } var self = this; if ( self.menuType === "page" ) { self.menuPage.dialog( "close" ); self.list.appendTo( self.listbox ); } else { self.listbox.popup( "close" ); } self._focusButton(); // allow the dialog to be closed again self.isOpen = false; }, open: function() { this.button.click(); }, _decideFormat: function() { var self = this, $window = $.mobile.window, selfListParent = self.list.parent(), menuHeight = selfListParent.outerHeight(), menuWidth = selfListParent.outerWidth(), activePage = $( "." + $.mobile.activePageClass ), scrollTop = $window.scrollTop(), btnOffset = self.button.offset().top, screenHeight = $window.height(), screenWidth = $window.width(); function focusMenuItem() { var selector = self.list.find( "." + $.mobile.activeBtnClass + " a" ); if ( selector.length === 0 ) { selector = self.list.find( "li.ui-btn:not( :jqmData(placeholder='true') ) a" ); } selector.first().focus().closest( "li" ).addClass( "ui-btn-down-" + widget.options.theme ); } if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) { self.menuPage.appendTo( $.mobile.pageContainer ).page(); self.menuPageContent = menuPage.find( ".ui-content" ); self.menuPageClose = menuPage.find( ".ui-header a" ); // prevent the parent page from being removed from the DOM, // otherwise the results of selecting a list item in the dialog // fall into a black hole self.thisPage.unbind( "pagehide.remove" ); //for WebOS/Opera Mini (set lastscroll using button offset) if ( scrollTop === 0 && btnOffset > screenHeight ) { self.thisPage.one( "pagehide", function() { $( this ).jqmData( "lastScroll", btnOffset ); }); } self.menuPage .one( "pageshow", function() { focusMenuItem(); }) .one( "pagehide", function() { self.close(); }); self.menuType = "page"; self.menuPageContent.append( self.list ); self.menuPage.find("div .ui-title").text(self.label.text()); } else { self.menuType = "overlay"; self.listbox.one( "popupafteropen", focusMenuItem ); } }, _buildList: function() { var self = this, o = this.options, placeholder = this.placeholder, needPlaceholder = true, optgroups = [], lis = [], dataIcon = self.isMultiple ? "checkbox-off" : "false"; self.list.empty().filter( ".ui-listview" ).listview( "destroy" ); var $options = self.select.find( "option" ), numOptions = $options.length, select = this.select[ 0 ], dataPrefix = 'data-' + $.mobile.ns, dataIndexAttr = dataPrefix + 'option-index', dataIconAttr = dataPrefix + 'icon', dataRoleAttr = dataPrefix + 'role', dataPlaceholderAttr = dataPrefix + 'placeholder', fragment = document.createDocumentFragment(), isPlaceholderItem = false, optGroup; for (var i = 0; i < numOptions;i++, isPlaceholderItem = false) { var option = $options[i], $option = $( option ), parent = option.parentNode, text = $option.text(), anchor = document.createElement( 'a' ), classes = []; anchor.setAttribute( 'href', '#' ); anchor.appendChild( document.createTextNode( text ) ); // Are we inside an optgroup? if ( parent !== select && parent.nodeName.toLowerCase() === "optgroup" ) { var optLabel = parent.getAttribute( 'label' ); if ( optLabel !== optGroup ) { var divider = document.createElement( 'li' ); divider.setAttribute( dataRoleAttr, 'list-divider' ); divider.setAttribute( 'role', 'option' ); divider.setAttribute( 'tabindex', '-1' ); divider.appendChild( document.createTextNode( optLabel ) ); fragment.appendChild( divider ); optGroup = optLabel; } } if ( needPlaceholder && ( !option.getAttribute( "value" ) || text.length === 0 || $option.jqmData( "placeholder" ) ) ) { needPlaceholder = false; isPlaceholderItem = true; // If we have identified a placeholder, record the fact that it was // us who have added the placeholder to the option and mark it // retroactively in the select as well if ( null === option.getAttribute( dataPlaceholderAttr ) ) { this._removePlaceholderAttr = true; } option.setAttribute( dataPlaceholderAttr, true ); if ( o.hidePlaceholderMenuItems ) { classes.push( "ui-selectmenu-placeholder" ); } if ( placeholder !== text ) { placeholder = self.placeholder = text; } } var item = document.createElement('li'); if ( option.disabled ) { classes.push( "ui-disabled" ); item.setAttribute('aria-disabled',true); } item.setAttribute( dataIndexAttr,i ); item.setAttribute( dataIconAttr, dataIcon ); if ( isPlaceholderItem ) { item.setAttribute( dataPlaceholderAttr, true ); } item.className = classes.join( " " ); item.setAttribute( 'role', 'option' ); anchor.setAttribute( 'tabindex', '-1' ); item.appendChild( anchor ); fragment.appendChild( item ); } self.list[0].appendChild( fragment ); // Hide header if it's not a multiselect and there's no placeholder if ( !this.isMultiple && !placeholder.length ) { this.header.hide(); } else { this.headerTitle.text( this.placeholder ); } // Now populated, create listview self.list.listview(); }, _button: function() { return $( "<a>", { "href": "#", "role": "button", // TODO value is undefined at creation "id": this.buttonId, "aria-haspopup": "true", // TODO value is undefined at creation "aria-owns": this.menuId }); }, _destroy: function() { this.close(); // Restore the tabindex attribute to its original value if ( this._origTabIndex !== undefined ) { if ( this._origTabIndex !== false ) { this.select.attr( "tabindex", this._origTabIndex ); } else { this.select.removeAttr( "tabindex" ); } } // Remove the placeholder attribute if we were the ones to add it if ( this._removePlaceholderAttr ) { this._selectOptions().removeAttr( "data-" + $.mobile.ns + "placeholder" ); } // Remove the popup this.listbox.remove(); // Remove the dialog this.menuPage.remove(); // Chain up origDestroy.apply( this, arguments ); } }); }; // issue #3894 - core doesn't trigger events on disabled delegates $.mobile.document.bind( "selectmenubeforecreate", function( event ) { var selectmenuWidget = $( event.target ).data( "mobile-selectmenu" ); if ( !selectmenuWidget.options.nativeMenu && selectmenuWidget.element.parents( ":jqmData(role='popup')" ).length === 0 ) { extendSelect( selectmenuWidget ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.controlgroup", $.mobile.widget, $.extend( { options: { shadow: false, corners: true, excludeInvisible: true, type: "vertical", mini: false, initSelector: ":jqmData(role='controlgroup')" }, _create: function() { var $el = this.element, ui = { inner: $( "<div class='ui-controlgroup-controls'></div>" ), legend: $( "<div role='heading' class='ui-controlgroup-label'></div>" ) }, grouplegend = $el.children( "legend" ), self = this; // Apply the proto $el.wrapInner( ui.inner ); if ( grouplegend.length ) { ui.legend.append( grouplegend ).insertBefore( $el.children( 0 ) ); } $el.addClass( "ui-corner-all ui-controlgroup" ); $.extend( this, { _initialRefresh: true }); $.each( this.options, function( key, value ) { // Cause initial options to be applied by their handler by temporarily setting the option to undefined // - the handler then sets it to the initial value self.options[ key ] = undefined; self._setOption( key, value, true ); }); }, _init: function() { this.refresh(); }, _setOption: function( key, value ) { var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 ); if ( this[ setter ] !== undefined ) { this[ setter ]( value ); } this._super( key, value ); this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value ); }, _setType: function( value ) { this.element .removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" ) .addClass( "ui-controlgroup-" + value ); this.refresh(); }, _setCorners: function( value ) { this.element.toggleClass( "ui-corner-all", value ); }, _setShadow: function( value ) { this.element.toggleClass( "ui-shadow", value ); }, _setMini: function( value ) { this.element.toggleClass( "ui-mini", value ); }, container: function() { return this.element.children( ".ui-controlgroup-controls" ); }, refresh: function() { var els = this.element.find( ".ui-btn" ).not( ".ui-slider-handle" ), create = this._initialRefresh; if ( $.mobile.checkboxradio ) { this.element.find( ":mobile-checkboxradio" ).checkboxradio( "refresh" ); } this._addFirstLastClasses( els, this.options.excludeInvisible ? this._getVisibles( els, create ) : els, create ); this._initialRefresh = false; } }, $.mobile.behaviors.addFirstLastClasses ) ); // TODO: Implement a mechanism to allow widgets to become enhanced in the // correct order when their correct enhancement depends on other widgets in // the page being correctly enhanced already. // // For now, we wait until dom-ready to attach the controlgroup's enhancement // hook, because by that time, all the other widgets' enhancement hooks should // already be in place, ensuring that all widgets that need to be grouped will // already have been enhanced by the time the controlgroup is created. $( function() { $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.controlgroup.prototype.enhanceWithin( e.target, true ); }); }); })(jQuery); (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ) { //links within content areas, tests included with page $( e.target ) .find( "a" ) .jqmEnhanceable() .filter( ":jqmData(rel='popup')[href][href!='']" ) .each( function() { // Accessibility info for popups var e = this, href = $( this ).attr( "href" ), idref = href.substring( 1 ); e.setAttribute( "aria-haspopup", true ); e.setAttribute( "aria-owns", idref ); e.setAttribute( "aria-expanded", false ); $( document ) .on( "popupafteropen", href, function() { e.setAttribute( "aria-expanded", true ); }) .on( "popupafterclose", href, function() { e.setAttribute( "aria-expanded", false ); }); }) .end() .not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" ) .addClass( "ui-link" ); }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.fixedtoolbar", $.mobile.widget, { options: { visibleOnPageShow: true, disablePageZoom: true, transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown) fullscreen: false, tapToggle: true, tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-popup, .ui-panel, .ui-panel-dismiss-open", hideDuringFocus: "input, textarea, select", updatePagePadding: true, trackPersistentToolbars: true, // Browser detection! Weeee, here we go... // Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately. // Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience. // Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window // The following function serves to rule out some popular browsers with known fixed-positioning issues // This is a plugin option like any other, so feel free to improve or overwrite it supportBlacklist: function() { return !$.support.fixedPosition; }, initSelector: ":jqmData(position='fixed')" }, _create: function() { var self = this, o = self.options, $el = self.element, tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer", $page = $el.closest( ".ui-page" ); // Feature detecting support for if ( o.supportBlacklist() ) { self.destroy(); return; } $el.addClass( "ui-"+ tbtype +"-fixed" ); // "fullscreen" overlay positioning if ( o.fullscreen ) { $el.addClass( "ui-"+ tbtype +"-fullscreen" ); $page.addClass( "ui-page-" + tbtype + "-fullscreen" ); } // If not fullscreen, add class to page to set top or bottom padding else{ $page.addClass( "ui-page-" + tbtype + "-fixed" ); } $.extend( this, { _thisPage: null }); self._addTransitionClass(); self._bindPageEvents(); self._bindToggleHandlers(); }, _addTransitionClass: function() { var tclass = this.options.transition; if ( tclass && tclass !== "none" ) { // use appropriate slide for header or footer if ( tclass === "slide" ) { tclass = this.element.is( ".ui-header" ) ? "slidedown" : "slideup"; } this.element.addClass( tclass ); } }, _bindPageEvents: function() { this._thisPage = this.element.closest( ".ui-page" ); //page event bindings // Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up // This method is meant to disable zoom while a fixed-positioned toolbar page is visible this._on( this._thisPage, { "pagebeforeshow": "_handlePageBeforeShow", "webkitAnimationStart":"_handleAnimationStart", "animationstart":"_handleAnimationStart", "updatelayout": "_handleAnimationStart", "pageshow": "_handlePageShow", "pagebeforehide": "_handlePageBeforeHide" }); }, _handlePageBeforeShow: function() { var o = this.options; if ( o.disablePageZoom ) { $.mobile.zoom.disable( true ); } if ( !o.visibleOnPageShow ) { this.hide( true ); } }, _handleAnimationStart: function() { if ( this.options.updatePagePadding ) { this.updatePagePadding( this._thisPage ); } }, _handlePageShow: function() { this.updatePagePadding( this._thisPage ); if ( this.options.updatePagePadding ) { this._on( $.mobile.window, { "throttledresize": "updatePagePadding" } ); } }, _handlePageBeforeHide: function( e, ui ) { var o = this.options; if ( o.disablePageZoom ) { $.mobile.zoom.enable( true ); } if ( o.updatePagePadding ) { this._off( $.mobile.window, "throttledresize" ); } if ( o.trackPersistentToolbars ) { var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this._thisPage ), thisHeader = $( ".ui-header-fixed:jqmData(id)", this._thisPage ), nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(), nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $(); if ( nextFooter.length || nextHeader.length ) { nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer ); ui.nextPage.one( "pageshow", function() { nextHeader.prependTo( this ); nextFooter.appendTo( this ); }); } } }, _visible: true, // This will set the content element's top or bottom padding equal to the toolbar's height updatePagePadding: function( tbPage ) { var $el = this.element, header = $el.is( ".ui-header" ), pos = parseFloat( $el.css( header ? "top" : "bottom" ) ); // This behavior only applies to "fixed", not "fullscreen" if ( this.options.fullscreen ) { return; } // tbPage argument can be a Page object or an event, if coming from throttled resize. tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this._thisPage || $el.closest( ".ui-page" ); $( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos ); }, _useTransition: function( notransition ) { var $win = $.mobile.window, $el = this.element, scroll = $win.scrollTop(), elHeight = $el.height(), pHeight = $el.closest( ".ui-page" ).height(), viewportHeight = $.mobile.getScreenHeight(), tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer"; return !notransition && ( this.options.transition && this.options.transition !== "none" && ( ( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) || ( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight ) ) || this.options.fullscreen ); }, show: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element; if ( this._useTransition( notransition ) ) { $el .removeClass( "out " + hideClass ) .addClass( "in" ) .animationComplete(function () { $el.removeClass('in'); }); } else { $el.removeClass( hideClass ); } this._visible = true; }, hide: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element, // if it's a slide transition, our new transitions need the reverse class as well to slide outward outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" ); if( this._useTransition( notransition ) ) { $el .addClass( outclass ) .removeClass( "in" ) .animationComplete(function() { $el.addClass( hideClass ).removeClass( outclass ); }); } else { $el.addClass( hideClass ).removeClass( outclass ); } this._visible = false; }, toggle: function() { this[ this._visible ? "hide" : "show" ](); }, _bindToggleHandlers: function() { var self = this, o = self.options, $el = self.element, delayShow, delayHide, isVisible = true; // tap toggle $el.closest( ".ui-page" ) .bind( "vclick", function( e ) { if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) { self.toggle(); } }) .bind( "focusin focusout", function( e ) { //this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which //positions fixed toolbars in the middle of the screen on pop if the input is near the top or //bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment //and issue #4113 Header and footer change their position after keyboard popup - iOS //and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) { //Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system //controls causes fixed position, tap-toggle false Header to reveal itself // isVisible instead of self._visible because the focusin and focusout events fire twice at the same time // Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed // by a focusout when a native selects opens and the other way around when it closes. if ( e.type === "focusout" && !isVisible ) { isVisible = true; //wait for the stack to unwind and see if we have jumped to another input clearTimeout( delayHide ); delayShow = setTimeout( function() { self.show(); }, 0 ); } else if ( e.type === "focusin" && !!isVisible ) { //if we have jumped to another input clear the time out to cancel the show. clearTimeout( delayShow ); isVisible = false; delayHide = setTimeout( function() { self.hide(); }, 0 ); } } }); }, _destroy: function() { var $el = this.element, header = $el.is( ".ui-header" ); $el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" ); $el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" ); $el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" ); } }); //auto self-init widgets $.mobile.document .bind( "pagecreate create", function( e ) { // DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element. // This line ensures it still works, but we recommend moving the attribute to the toolbars themselves. if ( $( e.target ).jqmData( "fullscreen" ) ) { $( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true ); } $.mobile.fixedtoolbar.prototype.enhanceWithin( e.target ); }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.fixedtoolbar", $.mobile.fixedtoolbar, { _create: function() { this._super(); this._workarounds(); }, //check the browser and version and run needed workarounds _workarounds: function() { var ua = navigator.userAgent, platform = navigator.platform, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], os = null, self = this; //set the os we are working in if it dosent match one with workarounds return if( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ){ os = "ios"; } else if( ua.indexOf( "Android" ) > -1 ){ os = "android"; } else { return; } //check os version if it dosent match one with workarounds return if( os === "ios" ) { //iOS workarounds self._bindScrollWorkaround(); } else if( os === "android" && wkversion && wkversion < 534 ) { //Android 2.3 run all Android 2.3 workaround self._bindScrollWorkaround(); self._bindListThumbWorkaround(); } else { return; } }, //Utility class for checking header and footer positions relative to viewport _viewportOffset: function() { var $el = this.element, header = $el.is( ".ui-header" ), offset = Math.abs($el.offset().top - $.mobile.window.scrollTop()); if( !header ) { offset = Math.round(offset - $.mobile.window.height() + $el.outerHeight())-60; } return offset; }, //bind events for _triggerRedraw() function _bindScrollWorkaround: function() { var self = this; //bind to scrollstop and check if the toolbars are correctly positioned this._on( $.mobile.window, { scrollstop: function() { var viewportOffset = self._viewportOffset(); //check if the header is visible and if its in the right place if( viewportOffset > 2 && self._visible) { self._triggerRedraw(); } }}); }, //this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3 //and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used //the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar //setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other //platforms we scope this with the class ui-android-2x-fix _bindListThumbWorkaround: function() { this.element.closest(".ui-page").addClass( "ui-android-2x-fixed" ); }, //this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android //and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers. //this also addresses not on fixed toolbars page in docs //adding 1px of padding to the bottom then removing it causes a "redraw" //which positions the toolbars correctly (they will always be visually correct) _triggerRedraw: function() { var paddingBottom = parseFloat( $( ".ui-page-active" ).css( "padding-bottom" ) ); //trigger page redraw to fix incorrectly positioned fixed elements $( ".ui-page-active" ).css( "padding-bottom", ( paddingBottom + 1 ) +"px" ); //if the padding is reset with out a timeout the reposition will not occure. //this is independant of JQM the browser seems to need the time to react. setTimeout( function() { $( ".ui-page-active" ).css( "padding-bottom", paddingBottom + "px" ); }, 0 ); }, destroy: function() { this._super(); //Remove the class we added to the page previously in android 2.x this.element.closest(".ui-page-active").removeClass( "ui-android-2x-fix" ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.panel", $.mobile.widget, { options: { classes: { panel: "ui-panel", panelOpen: "ui-panel-open", panelClosed: "ui-panel-closed", panelFixed: "ui-panel-fixed", panelInner: "ui-panel-inner", modal: "ui-panel-dismiss", modalOpen: "ui-panel-dismiss-open", pagePanel: "ui-page-panel", pagePanelOpen: "ui-page-panel-open", contentWrap: "ui-panel-content-wrap", contentWrapOpen: "ui-panel-content-wrap-open", contentWrapClosed: "ui-panel-content-wrap-closed", contentFixedToolbar: "ui-panel-content-fixed-toolbar", contentFixedToolbarOpen: "ui-panel-content-fixed-toolbar-open", contentFixedToolbarClosed: "ui-panel-content-fixed-toolbar-closed", animate: "ui-panel-animate" }, animate: true, theme: "c", position: "left", dismissible: true, display: "reveal", //accepts reveal, push, overlay initSelector: ":jqmData(role='panel')", swipeClose: true, positionFixed: false }, _panelID: null, _closeLink: null, _page: null, _modal: null, _panelInner: null, _wrapper: null, _fixedToolbar: null, _create: function() { var self = this, $el = self.element, page = $el.closest( ":jqmData(role='page')" ), _getPageTheme = function() { var $theme = $.data( page[0], "mobilePage" ).options.theme, $pageThemeClass = "ui-body-" + $theme; return $pageThemeClass; }, _getPanelInner = function() { var $panelInner = $el.find( "." + self.options.classes.panelInner ); if ( $panelInner.length === 0 ) { $panelInner = $el.children().wrapAll( '<div class="' + self.options.classes.panelInner + '" />' ).parent(); } return $panelInner; }, _getWrapper = function() { var $wrapper = page.find( "." + self.options.classes.contentWrap ); if ( $wrapper.length === 0 ) { $wrapper = page.children( ".ui-header:not(:jqmData(position='fixed')), .ui-content:not(:jqmData(role='popup')), .ui-footer:not(:jqmData(position='fixed'))" ).wrapAll( '<div class="' + self.options.classes.contentWrap + ' ' + _getPageTheme() + '" />' ).parent(); if ( $.support.cssTransform3d && !!self.options.animate ) { $wrapper.addClass( self.options.classes.animate ); } } return $wrapper; }, _getFixedToolbar = function() { var $fixedToolbar = page.find( "." + self.options.classes.contentFixedToolbar ); if ( $fixedToolbar.length === 0 ) { $fixedToolbar = page.find( ".ui-header:jqmData(position='fixed'), .ui-footer:jqmData(position='fixed')" ).addClass( self.options.classes.contentFixedToolbar ); if ( $.support.cssTransform3d && !!self.options.animate ) { $fixedToolbar.addClass( self.options.classes.animate ); } } return $fixedToolbar; }; // expose some private props to other methods $.extend( this, { _panelID: $el.attr( "id" ), _closeLink: $el.find( ":jqmData(rel='close')" ), _page: $el.closest( ":jqmData(role='page')" ), _pageTheme: _getPageTheme(), _panelInner: _getPanelInner(), _wrapper: _getWrapper(), _fixedToolbar: _getFixedToolbar() }); self._addPanelClasses(); self._wrapper.addClass( this.options.classes.contentWrapClosed ); self._fixedToolbar.addClass( this.options.classes.contentFixedToolbarClosed ); // add class to page so we can set "overflow-x: hidden;" for it to fix Android zoom issue self._page.addClass( self.options.classes.pagePanel ); // if animating, add the class to do so if ( $.support.cssTransform3d && !!self.options.animate ) { this.element.addClass( self.options.classes.animate ); } self._bindUpdateLayout(); self._bindCloseEvents(); self._bindLinkListeners(); self._bindPageEvents(); if ( !!self.options.dismissible ) { self._createModal(); } self._bindSwipeEvents(); }, _createModal: function( options ) { var self = this; self._modal = $( "<div class='" + self.options.classes.modal + "' data-panelid='" + self._panelID + "'></div>" ) .on( "mousedown", function() { self.close(); }) .appendTo( this._page ); }, _getPosDisplayClasses: function( prefix ) { return prefix + "-position-" + this.options.position + " " + prefix + "-display-" + this.options.display; }, _getPanelClasses: function() { var panelClasses = this.options.classes.panel + " " + this._getPosDisplayClasses( this.options.classes.panel ) + " " + this.options.classes.panelClosed; if ( this.options.theme ) { panelClasses += " ui-body-" + this.options.theme; } if ( !!this.options.positionFixed ) { panelClasses += " " + this.options.classes.panelFixed; } return panelClasses; }, _addPanelClasses: function() { this.element.addClass( this._getPanelClasses() ); }, _bindCloseEvents: function() { var self = this; self._closeLink.on( "click.panel" , function( e ) { e.preventDefault(); self.close(); return false; }); self.element.on( "click.panel" , "a:jqmData(ajax='false')", function( e ) { self.close(); }); }, _positionPanel: function() { var self = this, panelInnerHeight = self._panelInner.outerHeight(), expand = panelInnerHeight > $.mobile.getScreenHeight(); if ( expand || !self.options.positionFixed ) { if ( expand ) { self._unfixPanel(); $.mobile.resetActivePageHeight( panelInnerHeight ); } self._scrollIntoView( panelInnerHeight ); } else { self._fixPanel(); } }, _scrollIntoView: function( panelInnerHeight ) { if ( panelInnerHeight < $( window ).scrollTop() ) { window.scrollTo( 0, 0 ); } }, _bindFixListener: function() { this._on( $( window ), { "throttledresize": "_positionPanel" }); }, _unbindFixListener: function() { this._off( $( window ), "throttledresize" ); }, _unfixPanel: function() { if ( !!this.options.positionFixed && $.support.fixedPosition ) { this.element.removeClass( this.options.classes.panelFixed ); } }, _fixPanel: function() { if ( !!this.options.positionFixed && $.support.fixedPosition ) { this.element.addClass( this.options.classes.panelFixed ); } }, _bindUpdateLayout: function() { var self = this; self.element.on( "updatelayout", function( e ) { if ( self._open ) { self._positionPanel(); } }); }, _bindLinkListeners: function() { var self = this; self._page.on( "click.panel" , "a", function( e ) { if ( this.href.split( "#" )[ 1 ] === self._panelID && self._panelID !== undefined ) { e.preventDefault(); var $link = $( this ), $parent; if ( ! $link.hasClass( "ui-link" ) ) { // Check if we are in a listview $parent = $link.parent().parent(); if ( $parent.hasClass( "ui-li" ) ) { $link = $parent.parent(); } $link.addClass( $.mobile.activeBtnClass ); self.element.one( "panelopen panelclose", function() { $link.removeClass( $.mobile.activeBtnClass ); }); } self.toggle(); return false; } }); }, _bindSwipeEvents: function() { var self = this, area = self._modal ? self.element.add( self._modal ) : self.element; // on swipe, close the panel if( !!self.options.swipeClose ) { if ( self.options.position === "left" ) { area.on( "swipeleft.panel", function( e ) { self.close(); }); } else { area.on( "swiperight.panel", function( e ) { self.close(); }); } } }, _bindPageEvents: function() { var self = this; self._page // Close the panel if another panel on the page opens .on( "panelbeforeopen", function( e ) { if ( self._open && e.target !== self.element[ 0 ] ) { self.close(); } }) // clean up open panels after page hide .on( "pagehide", function( e ) { if ( self._open ) { self.close( true ); } }) // on escape, close? might need to have a target check too... .on( "keyup.panel", function( e ) { if ( e.keyCode === 27 && self._open ) { self.close(); } }); }, // state storage of open or closed _open: false, _contentWrapOpenClasses: null, _fixedToolbarOpenClasses: null, _modalOpenClasses: null, open: function( immediate ) { if ( !this._open ) { var self = this, o = self.options, _openPanel = function() { self._page.off( "panelclose" ); self._page.jqmData( "panel", "open" ); if ( !immediate && $.support.cssTransform3d && !!o.animate ) { self.element.add( self._wrapper ).on( self._transitionEndEvents, complete ); } else { setTimeout( complete, 0 ); } if ( self.options.theme && self.options.display !== "overlay" ) { self._page .removeClass( self._pageTheme ) .addClass( "ui-body-" + self.options.theme ); } self.element.removeClass( o.classes.panelClosed ).addClass( o.classes.panelOpen ); self._positionPanel(); // Fix for IE7 min-height bug if ( self.options.theme && self.options.display !== "overlay" ) { self._wrapper.css( "min-height", self._page.css( "min-height" ) ); } self._contentWrapOpenClasses = self._getPosDisplayClasses( o.classes.contentWrap ); self._wrapper .removeClass( o.classes.contentWrapClosed ) .addClass( self._contentWrapOpenClasses + " " + o.classes.contentWrapOpen ); self._fixedToolbarOpenClasses = self._getPosDisplayClasses( o.classes.contentFixedToolbar ); self._fixedToolbar .removeClass( o.classes.contentFixedToolbarClosed ) .addClass( self._fixedToolbarOpenClasses + " " + o.classes.contentFixedToolbarOpen ); self._modalOpenClasses = self._getPosDisplayClasses( o.classes.modal ) + " " + o.classes.modalOpen; if ( self._modal ) { self._modal.addClass( self._modalOpenClasses ); } }, complete = function() { self.element.add( self._wrapper ).off( self._transitionEndEvents, complete ); self._page.addClass( o.classes.pagePanelOpen ); self._bindFixListener(); self._trigger( "open" ); }; if ( this.element.closest( ".ui-page-active" ).length < 0 ) { immediate = true; } self._trigger( "beforeopen" ); if ( self._page.jqmData('panel') === "open" ) { self._page.on( "panelclose", function() { _openPanel(); }); } else { _openPanel(); } self._open = true; } }, close: function( immediate ) { if ( this._open ) { var o = this.options, self = this, _closePanel = function() { if ( !immediate && $.support.cssTransform3d && !!o.animate ) { self.element.add( self._wrapper ).on( self._transitionEndEvents, complete ); } else { setTimeout( complete, 0 ); } self._page.removeClass( o.classes.pagePanelOpen ); self.element.removeClass( o.classes.panelOpen ); self._wrapper.removeClass( o.classes.contentWrapOpen ); self._fixedToolbar.removeClass( o.classes.contentFixedToolbarOpen ); if ( self._modal ) { self._modal.removeClass( self._modalOpenClasses ); } }, complete = function() { if ( self.options.theme && self.options.display !== "overlay" ) { self._page.removeClass( "ui-body-" + self.options.theme ).addClass( self._pageTheme ); // reset fix for IE7 min-height bug self._wrapper.css( "min-height", "" ); } self.element.add( self._wrapper ).off( self._transitionEndEvents, complete ); self.element.addClass( o.classes.panelClosed ); self._wrapper .removeClass( self._contentWrapOpenClasses ) .addClass( o.classes.contentWrapClosed ); self._fixedToolbar .removeClass( self._fixedToolbarOpenClasses ) .addClass( o.classes.contentFixedToolbarClosed ); self._fixPanel(); self._unbindFixListener(); $.mobile.resetActivePageHeight(); self._page.jqmRemoveData( "panel" ); self._trigger( "close" ); }; if ( this.element.closest( ".ui-page-active" ).length < 0 ) { immediate = true; } self._trigger( "beforeclose" ); _closePanel(); self._open = false; } }, toggle: function( options ) { this[ this._open ? "close" : "open" ](); }, _transitionEndEvents: "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd", _destroy: function() { var classes = this.options.classes, theme = this.options.theme, hasOtherSiblingPanels = this.element.siblings( "." + classes.panel ).length; // create if ( !hasOtherSiblingPanels ) { this._wrapper.children().unwrap(); this._page.find( "a" ).unbind( "panelopen panelclose" ); this._page.removeClass( classes.pagePanel ); if ( this._open ) { this._page.jqmRemoveData( "panel" ); this._page.removeClass( classes.pagePanelOpen ); if ( theme ) { this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme ); } $.mobile.resetActivePageHeight(); } } else if ( this._open ) { this._wrapper.removeClass( classes.contentWrapOpen ); this._fixedToolbar.removeClass( classes.contentFixedToolbarOpen ); this._page.jqmRemoveData( "panel" ); this._page.removeClass( classes.pagePanelOpen ); if ( theme ) { this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme ); } } this._panelInner.children().unwrap(); this.element.removeClass( [ this._getPanelClasses(), classes.panelAnimate ].join( " " ) ) .off( "swipeleft.panel swiperight.panel" ) .off( "panelbeforeopen" ) .off( "panelhide" ) .off( "keyup.panel" ) .off( "updatelayout" ); this._closeLink.off( "click.panel" ); if ( this._modal ) { this._modal.remove(); } // open and close this.element.off( this._transitionEndEvents ) .removeClass( [ classes.panelUnfixed, classes.panelClosed, classes.panelOpen ].join( " " ) ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ) { $.mobile.panel.prototype.enhanceWithin( e.target ); }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", $.mobile.widget, { options: { classes: { table: "ui-table" }, initSelector: ":jqmData(role='table')" }, _create: function() { var self = this; self.refresh( true ); }, refresh: function (create) { var self = this, trs = this.element.find( "thead tr" ); if ( create ) { this.element.addClass( this.options.classes.table ); } // Expose headers and allHeaders properties on the widget // headers references the THs within the first TR in the table self.headers = this.element.find( "tr:eq(0)" ).children(); // allHeaders references headers, plus all THs in the thead, which may include several rows, or not self.allHeaders = self.headers.add( trs.children() ); trs.each(function(){ var coltally = 0; $( this ).children().each(function( i ){ var span = parseInt( $( this ).attr( "colspan" ), 10 ), sel = ":nth-child(" + ( coltally + 1 ) + ")"; $( this ) .jqmData( "colstart", coltally + 1 ); if( span ){ for( var j = 0; j < span - 1; j++ ){ coltally++; sel += ", :nth-child(" + ( coltally + 1 ) + ")"; } } if ( create === undefined ) { $(this).jqmData("cells", ""); } // Store "cells" data on header as a reference to all cells in the same column as this TH $( this ) .jqmData( "cells", self.element.find( "tr" ).not( trs.eq(0) ).not( this ).children( sel ) ); coltally++; }); }); // update table modes if ( create === undefined ) { this.element.trigger( 'refresh' ); } } }); //auto self-init widgets $.mobile.document.bind( "pagecreate create", function( e ) { $.mobile.table.prototype.enhanceWithin( e.target ); }); })( jQuery ); (function( $, undefined ) { $.mobile.table.prototype.options.mode = "columntoggle"; $.mobile.table.prototype.options.columnBtnTheme = null; $.mobile.table.prototype.options.columnPopupTheme = null; $.mobile.table.prototype.options.columnBtnText = "Columns..."; $.mobile.table.prototype.options.classes = $.extend( $.mobile.table.prototype.options.classes, { popup: "ui-table-columntoggle-popup", columnBtn: "ui-table-columntoggle-btn", priorityPrefix: "ui-table-priority-", columnToggleTable: "ui-table-columntoggle" } ); $.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) { var $table = $( this ), self = $table.data( "mobile-table" ), event = e.type, o = self.options, ns = $.mobile.ns, id = ( $table.attr( "id" ) || o.classes.popup ) + "-popup", /* TODO BETTER FALLBACK ID HERE */ $menuButton, $popup, $menu, $switchboard; if ( o.mode !== "columntoggle" ) { return; } if ( event !== "refresh" ) { self.element.addClass( o.classes.columnToggleTable ); $menuButton = $( "<a href='#" + id + "' class='" + o.classes.columnBtn + "' data-" + ns + "rel='popup' data-" + ns + "mini='true'>" + o.columnBtnText + "</a>" ), $popup = $( "<div data-" + ns + "role='popup' data-" + ns + "role='fieldcontain' class='" + o.classes.popup + "' id='" + id + "'></div>"), $menu = $("<fieldset data-" + ns + "role='controlgroup'></fieldset>"); } // create the hide/show toggles self.headers.not( "td" ).each(function( i ) { var priority = $( this ).jqmData( "priority" ), $cells = $( this ).add( $( this ).jqmData( "cells" ) ); if ( priority ) { $cells.addClass( o.classes.priorityPrefix + priority ); if ( event !== "refresh" ) { $("<label><input type='checkbox' checked />" + $( this ).text() + "</label>" ) .appendTo( $menu ) .children( 0 ) .jqmData( "cells", $cells ) .checkboxradio({ theme: o.columnPopupTheme }); } else { $( '#' + id + ' fieldset div:eq(' + i +')').find('input').jqmData( 'cells', $cells ); } } }); if ( event !== "refresh" ) { $menu.appendTo( $popup ); } // bind change event listeners to inputs - TODO: move to a private method? if ( $menu === undefined ) { $switchboard = $('#' + id + ' fieldset'); } else { $switchboard = $menu; } if ( event !== "refresh" ) { $switchboard.on( "change", "input", function( e ){ if( this.checked ){ $( this ).jqmData( "cells" ).removeClass( "ui-table-cell-hidden" ).addClass( "ui-table-cell-visible" ); } else { $( this ).jqmData( "cells" ).removeClass( "ui-table-cell-visible" ).addClass( "ui-table-cell-hidden" ); } }); $menuButton .insertBefore( $table ) .buttonMarkup({ theme: o.columnBtnTheme }); $popup .insertBefore( $table ) .popup(); } // refresh method self.update = function(){ $switchboard.find( "input" ).each( function(){ if (this.checked) { this.checked = $( this ).jqmData( "cells" ).eq(0).css( "display" ) === "table-cell"; if (event === "refresh") { $( this ).jqmData( "cells" ).addClass('ui-table-cell-visible'); } } else { $( this ).jqmData( "cells" ).addClass('ui-table-cell-hidden'); } $( this ).checkboxradio( "refresh" ); }); }; $.mobile.window.on( "throttledresize", self.update ); self.update(); }); })( jQuery ); (function( $, undefined ) { $.mobile.table.prototype.options.mode = "reflow"; $.mobile.table.prototype.options.classes = $.extend( $.mobile.table.prototype.options.classes, { reflowTable: "ui-table-reflow", cellLabels: "ui-table-cell-label" } ); $.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) { var $table = $( this ), event = e.type, self = $table.data( "mobile-table" ), o = self.options; // If it's not reflow mode, return here. if( o.mode !== "reflow" ){ return; } if ( event !== "refresh" ) { self.element.addClass( o.classes.reflowTable ); } // get headers in reverse order so that top-level headers are appended last var reverseHeaders = $( self.allHeaders.get().reverse() ); // create the hide/show toggles reverseHeaders.each(function( i ){ var $cells = $( this ).jqmData( "cells" ), colstart = $( this ).jqmData( "colstart" ), hierarchyClass = $cells.not( this ).filter( "thead th" ).length && " ui-table-cell-label-top", text = $(this).text(); if( text !== "" ){ if( hierarchyClass ){ var iteration = parseInt( $( this ).attr( "colspan" ), 10 ), filter = ""; if( iteration ){ filter = "td:nth-child("+ iteration +"n + " + ( colstart ) +")"; } $cells.filter( filter ).prepend( "<b class='" + o.classes.cellLabels + hierarchyClass + "'>" + text + "</b>" ); } else { $cells.prepend( "<b class='" + o.classes.cellLabels + "'>" + text + "</b>" ); } } }); }); })( jQuery ); (function( $, window ) { $.mobile.iosorientationfixEnabled = true; // This fix addresses an iOS bug, so return early if the UA claims it's something else. var ua = navigator.userAgent; if( !( /iPhone|iPad|iPod/.test( navigator.platform ) && /OS [1-5]_[0-9_]* like Mac OS X/i.test( ua ) && ua.indexOf( "AppleWebKit" ) > -1 ) ){ $.mobile.iosorientationfixEnabled = false; return; } var zoom = $.mobile.zoom, evt, x, y, z, aig; function checkTilt( e ) { evt = e.originalEvent; aig = evt.accelerationIncludingGravity; x = Math.abs( aig.x ); y = Math.abs( aig.y ); z = Math.abs( aig.z ); // If portrait orientation and in one of the danger zones if ( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ) { if ( zoom.enabled ) { zoom.disable(); } } else if ( !zoom.enabled ) { zoom.enable(); } } $.mobile.document.on( "mobileinit", function(){ if( $.mobile.iosorientationfixEnabled ){ $.mobile.window .bind( "orientationchange.iosorientationfix", zoom.enable ) .bind( "devicemotion.iosorientationfix", checkTilt ); } }); }( jQuery, this )); (function( $, window, undefined ) { var $html = $( "html" ), $head = $( "head" ), $window = $.mobile.window; //remove initial build class (only present on first pageshow) function hideRenderingClass() { $html.removeClass( "ui-mobile-rendering" ); } // trigger mobileinit event - useful hook for configuring $.mobile settings before they're used $( window.document ).trigger( "mobileinit" ); // support conditions // if device support condition(s) aren't met, leave things as they are -> a basic, usable experience, // otherwise, proceed with the enhancements if ( !$.mobile.gradeA() ) { return; } // override ajaxEnabled on platforms that have known conflicts with hash history updates // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini) if ( $.mobile.ajaxBlacklist ) { $.mobile.ajaxEnabled = false; } // Add mobile, initial load "rendering" classes to docEl $html.addClass( "ui-mobile ui-mobile-rendering" ); // This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire, // this ensures the rendering class is removed after 5 seconds, so content is visible and accessible setTimeout( hideRenderingClass, 5000 ); $.extend( $.mobile, { // find and enhance the pages in the dom and transition to the first page. initializePage: function() { // find present pages var path = $.mobile.path, $pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" ), hash = path.stripHash( path.stripQueryParams(path.parseLocation().hash) ), hashPage = document.getElementById( hash ); // if no pages are found, create one with body's inner html if ( !$pages.length ) { $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 ); } // add dialogs, set data-url attrs $pages.each(function() { var $this = $( this ); // unless the data url is already set set it to the pathname if ( !$this.jqmData( "url" ) ) { $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search ); } }); // define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback) $.mobile.firstPage = $pages.first(); // define page container $.mobile.pageContainer = $.mobile.firstPage.parent().addClass( "ui-mobile-viewport" ); // initialize navigation events now, after mobileinit has occurred and the page container // has been created but before the rest of the library is alerted to that fact $.mobile.navreadyDeferred.resolve(); // alert listeners that the pagecontainer has been determined for binding // to events triggered on it $window.trigger( "pagecontainercreate" ); // cue page loading message $.mobile.showPageLoadingMsg(); //remove initial build class (only present on first pageshow) hideRenderingClass(); // if hashchange listening is disabled, there's no hash deeplink, // the hash is not valid (contains more than one # or does not start with #) // or there is no page with that hash, change to the first page in the DOM // Remember, however, that the hash can also be a path! if ( ! ( $.mobile.hashListeningEnabled && $.mobile.path.isHashValid( location.hash ) && ( $( hashPage ).is( ':jqmData(role="page")' ) || $.mobile.path.isPath( hash ) || hash === $.mobile.dialogHashKey ) ) ) { // Store the initial destination if ( $.mobile.path.isHashValid( location.hash ) ) { $.mobile.urlHistory.initialDst = hash.replace( "#", "" ); } // make sure to set initial popstate state if it exists // so that navigation back to the initial page works properly if( $.event.special.navigate.isPushStateEnabled() ) { $.mobile.navigate.navigator.squash( path.parseLocation().href ); } $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true }); } else { // trigger hashchange or navigate to squash and record the correct // history entry for an initial hash path if( !$.event.special.navigate.isPushStateEnabled() ) { $window.trigger( "hashchange", [true] ); } else { // TODO figure out how to simplify this interaction with the initial history entry // at the bottom js/navigate/navigate.js $.mobile.navigate.history.stack = []; $.mobile.navigate( $.mobile.path.isPath( location.hash ) ? location.hash : location.href ); } } } }); // check which scrollTop value should be used by scrolling to 1 immediately at domready // then check what the scroll top is. Android will report 0... others 1 // note that this initial scroll won't hide the address bar. It's just for the check. $(function() { window.scrollTo( 0, 1 ); // if defaultHomeScroll hasn't been set yet, see if scrollTop is 1 // it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar) // so if it's 1, use 0 from now on $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $.mobile.window.scrollTop() === 1 ) ? 0 : 1; //dom-ready inits if ( $.mobile.autoInitializePage ) { $.mobile.initializePage(); } // window load event // hide iOS browser chrome on load $window.load( $.mobile.silentScroll ); if ( !$.support.cssPointerEvents ) { // IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons // by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser. // https://github.com/jquery/jquery-mobile/issues/3558 $.mobile.document.delegate( ".ui-disabled", "vclick", function( e ) { e.preventDefault(); e.stopImmediatePropagation(); } ); } }); }( jQuery, this )); }));
ajax/libs/yui/3.10.0/event-custom-base/event-custom-base-coverage.js
blairvanderhoof/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/event-custom-base/event-custom-base.js']) { __coverage__['build/event-custom-base/event-custom-base.js'] = {"path":"build/event-custom-base/event-custom-base.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0,"165":0,"166":0,"167":0,"168":0,"169":0,"170":0,"171":0,"172":0,"173":0,"174":0,"175":0,"176":0,"177":0,"178":0,"179":0,"180":0,"181":0,"182":0,"183":0,"184":0,"185":0,"186":0,"187":0,"188":0,"189":0,"190":0,"191":0,"192":0,"193":0,"194":0,"195":0,"196":0,"197":0,"198":0,"199":0,"200":0,"201":0,"202":0,"203":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"210":0,"211":0,"212":0,"213":0,"214":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"221":0,"222":0,"223":0,"224":0,"225":0,"226":0,"227":0,"228":0,"229":0,"230":0,"231":0,"232":0,"233":0,"234":0,"235":0,"236":0,"237":0,"238":0,"239":0,"240":0,"241":0,"242":0,"243":0,"244":0,"245":0,"246":0,"247":0,"248":0,"249":0,"250":0,"251":0,"252":0,"253":0,"254":0,"255":0,"256":0,"257":0,"258":0,"259":0,"260":0,"261":0,"262":0,"263":0,"264":0,"265":0,"266":0,"267":0,"268":0,"269":0,"270":0,"271":0,"272":0,"273":0,"274":0,"275":0,"276":0,"277":0,"278":0,"279":0,"280":0,"281":0,"282":0,"283":0,"284":0,"285":0,"286":0,"287":0,"288":0,"289":0,"290":0,"291":0,"292":0,"293":0,"294":0,"295":0,"296":0,"297":0,"298":0,"299":0,"300":0,"301":0,"302":0,"303":0,"304":0,"305":0,"306":0,"307":0,"308":0,"309":0,"310":0,"311":0,"312":0,"313":0,"314":0,"315":0,"316":0,"317":0,"318":0,"319":0,"320":0,"321":0,"322":0,"323":0,"324":0,"325":0,"326":0,"327":0,"328":0,"329":0,"330":0,"331":0,"332":0,"333":0,"334":0,"335":0,"336":0,"337":0,"338":0,"339":0,"340":0,"341":0,"342":0,"343":0,"344":0,"345":0,"346":0,"347":0,"348":0,"349":0,"350":0,"351":0,"352":0,"353":0,"354":0,"355":0,"356":0,"357":0,"358":0,"359":0,"360":0,"361":0,"362":0,"363":0,"364":0,"365":0,"366":0,"367":0,"368":0,"369":0,"370":0,"371":0,"372":0,"373":0,"374":0,"375":0,"376":0,"377":0,"378":0,"379":0,"380":0,"381":0,"382":0,"383":0,"384":0,"385":0,"386":0,"387":0,"388":0,"389":0,"390":0,"391":0,"392":0,"393":0,"394":0,"395":0,"396":0,"397":0,"398":0,"399":0,"400":0,"401":0,"402":0,"403":0,"404":0,"405":0,"406":0,"407":0,"408":0,"409":0,"410":0,"411":0,"412":0,"413":0,"414":0,"415":0,"416":0,"417":0,"418":0,"419":0,"420":0,"421":0,"422":0,"423":0,"424":0,"425":0,"426":0,"427":0,"428":0,"429":0,"430":0,"431":0,"432":0,"433":0,"434":0,"435":0,"436":0,"437":0,"438":0,"439":0,"440":0,"441":0,"442":0,"443":0,"444":0,"445":0,"446":0,"447":0,"448":0,"449":0,"450":0,"451":0,"452":0,"453":0,"454":0,"455":0,"456":0,"457":0,"458":0,"459":0,"460":0,"461":0,"462":0,"463":0,"464":0,"465":0,"466":0,"467":0,"468":0,"469":0,"470":0,"471":0,"472":0,"473":0,"474":0,"475":0,"476":0,"477":0,"478":0,"479":0,"480":0,"481":0,"482":0,"483":0,"484":0,"485":0,"486":0,"487":0,"488":0,"489":0,"490":0,"491":0,"492":0,"493":0,"494":0,"495":0,"496":0,"497":0,"498":0,"499":0,"500":0,"501":0,"502":0,"503":0,"504":0,"505":0,"506":0,"507":0,"508":0,"509":0,"510":0,"511":0,"512":0,"513":0,"514":0,"515":0,"516":0,"517":0,"518":0,"519":0,"520":0,"521":0,"522":0,"523":0,"524":0,"525":0,"526":0,"527":0,"528":0,"529":0,"530":0,"531":0,"532":0,"533":0,"534":0,"535":0,"536":0,"537":0,"538":0,"539":0,"540":0,"541":0,"542":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0,0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0],"33":[0,0],"34":[0,0],"35":[0,0],"36":[0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0,0],"52":[0,0],"53":[0,0],"54":[0,0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0],"60":[0,0],"61":[0,0],"62":[0,0],"63":[0,0],"64":[0,0],"65":[0,0],"66":[0,0],"67":[0,0],"68":[0,0],"69":[0,0],"70":[0,0],"71":[0,0],"72":[0,0],"73":[0,0],"74":[0,0],"75":[0,0],"76":[0,0],"77":[0,0],"78":[0,0],"79":[0,0],"80":[0,0],"81":[0,0],"82":[0,0],"83":[0,0],"84":[0,0],"85":[0,0],"86":[0,0],"87":[0,0],"88":[0,0,0],"89":[0,0],"90":[0,0],"91":[0,0],"92":[0,0],"93":[0,0],"94":[0,0],"95":[0,0],"96":[0,0],"97":[0,0],"98":[0,0],"99":[0,0],"100":[0,0],"101":[0,0],"102":[0,0],"103":[0,0],"104":[0,0],"105":[0,0],"106":[0,0],"107":[0,0],"108":[0,0],"109":[0,0],"110":[0,0],"111":[0,0],"112":[0,0],"113":[0,0],"114":[0,0],"115":[0,0],"116":[0,0],"117":[0,0],"118":[0,0],"119":[0,0],"120":[0,0],"121":[0,0],"122":[0,0],"123":[0,0],"124":[0,0],"125":[0,0],"126":[0,0],"127":[0,0],"128":[0,0],"129":[0,0],"130":[0,0],"131":[0,0,0],"132":[0,0],"133":[0,0],"134":[0,0],"135":[0,0],"136":[0,0],"137":[0,0],"138":[0,0],"139":[0,0],"140":[0,0],"141":[0,0],"142":[0,0],"143":[0,0],"144":[0,0],"145":[0,0],"146":[0,0],"147":[0,0],"148":[0,0],"149":[0,0],"150":[0,0],"151":[0,0],"152":[0,0],"153":[0,0],"154":[0,0],"155":[0,0],"156":[0,0],"157":[0,0],"158":[0,0],"159":[0,0],"160":[0,0],"161":[0,0],"162":[0,0],"163":[0,0],"164":[0,0],"165":[0,0],"166":[0,0],"167":[0,0,0],"168":[0,0],"169":[0,0],"170":[0,0],"171":[0,0],"172":[0,0,0,0],"173":[0,0],"174":[0,0],"175":[0,0],"176":[0,0],"177":[0,0],"178":[0,0],"179":[0,0],"180":[0,0,0,0],"181":[0,0],"182":[0,0],"183":[0,0],"184":[0,0],"185":[0,0],"186":[0,0],"187":[0,0,0,0,0],"188":[0,0],"189":[0,0],"190":[0,0],"191":[0,0],"192":[0,0],"193":[0,0],"194":[0,0],"195":[0,0],"196":[0,0],"197":[0,0],"198":[0,0],"199":[0,0,0,0,0],"200":[0,0],"201":[0,0],"202":[0,0],"203":[0,0],"204":[0,0],"205":[0,0],"206":[0,0],"207":[0,0],"208":[0,0],"209":[0,0],"210":[0,0,0,0],"211":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":29},"end":{"line":1,"column":48}}},"2":{"name":"(anonymous_2)","line":75,"loc":{"start":{"line":75,"column":12},"end":{"line":75,"column":38}}},"3":{"name":"(anonymous_3)","line":112,"loc":{"start":{"line":112,"column":11},"end":{"line":112,"column":37}}},"4":{"name":"(anonymous_4)","line":136,"loc":{"start":{"line":136,"column":13},"end":{"line":136,"column":42}}},"5":{"name":"(anonymous_5)","line":152,"loc":{"start":{"line":152,"column":23},"end":{"line":152,"column":34}}},"6":{"name":"(anonymous_6)","line":173,"loc":{"start":{"line":173,"column":12},"end":{"line":173,"column":29}}},"7":{"name":"(anonymous_7)","line":212,"loc":{"start":{"line":212,"column":12},"end":{"line":212,"column":31}}},"8":{"name":"(anonymous_8)","line":227,"loc":{"start":{"line":227,"column":31},"end":{"line":227,"column":56}}},"9":{"name":"(anonymous_9)","line":242,"loc":{"start":{"line":242,"column":30},"end":{"line":242,"column":45}}},"10":{"name":"(anonymous_10)","line":261,"loc":{"start":{"line":261,"column":27},"end":{"line":261,"column":39}}},"11":{"name":"(anonymous_11)","line":329,"loc":{"start":{"line":329,"column":15},"end":{"line":329,"column":38}}},"12":{"name":"(anonymous_12)","line":343,"loc":{"start":{"line":343,"column":17},"end":{"line":343,"column":42}}},"13":{"name":"(anonymous_13)","line":358,"loc":{"start":{"line":358,"column":10},"end":{"line":358,"column":32}}},"14":{"name":"(anonymous_14)","line":371,"loc":{"start":{"line":371,"column":13},"end":{"line":371,"column":27}}},"15":{"name":"(anonymous_15)","line":432,"loc":{"start":{"line":432,"column":17},"end":{"line":432,"column":36}}},"16":{"name":"(anonymous_16)","line":468,"loc":{"start":{"line":468,"column":16},"end":{"line":468,"column":41}}},"17":{"name":"(anonymous_17)","line":701,"loc":{"start":{"line":701,"column":13},"end":{"line":701,"column":28}}},"18":{"name":"(anonymous_18)","line":744,"loc":{"start":{"line":744,"column":13},"end":{"line":744,"column":28}}},"19":{"name":"(anonymous_19)","line":757,"loc":{"start":{"line":757,"column":13},"end":{"line":757,"column":24}}},"20":{"name":"(anonymous_20)","line":808,"loc":{"start":{"line":808,"column":17},"end":{"line":808,"column":36}}},"21":{"name":"(anonymous_21)","line":825,"loc":{"start":{"line":825,"column":9},"end":{"line":825,"column":43}}},"22":{"name":"(anonymous_22)","line":870,"loc":{"start":{"line":870,"column":15},"end":{"line":870,"column":37}}},"23":{"name":"(anonymous_23)","line":884,"loc":{"start":{"line":884,"column":8},"end":{"line":884,"column":30}}},"24":{"name":"(anonymous_24)","line":906,"loc":{"start":{"line":906,"column":11},"end":{"line":906,"column":33}}},"25":{"name":"(anonymous_25)","line":919,"loc":{"start":{"line":919,"column":12},"end":{"line":919,"column":34}}},"26":{"name":"(anonymous_26)","line":962,"loc":{"start":{"line":962,"column":17},"end":{"line":962,"column":28}}},"27":{"name":"(anonymous_27)","line":973,"loc":{"start":{"line":973,"column":13},"end":{"line":973,"column":35}}},"28":{"name":"(anonymous_28)","line":993,"loc":{"start":{"line":993,"column":9},"end":{"line":993,"column":28}}},"29":{"name":"(anonymous_29)","line":1013,"loc":{"start":{"line":1013,"column":10},"end":{"line":1013,"column":21}}},"30":{"name":"(anonymous_30)","line":1035,"loc":{"start":{"line":1035,"column":11},"end":{"line":1035,"column":26}}},"31":{"name":"(anonymous_31)","line":1066,"loc":{"start":{"line":1066,"column":16},"end":{"line":1066,"column":31}}},"32":{"name":"(anonymous_32)","line":1081,"loc":{"start":{"line":1081,"column":17},"end":{"line":1081,"column":32}}},"33":{"name":"(anonymous_33)","line":1098,"loc":{"start":{"line":1098,"column":15},"end":{"line":1098,"column":40}}},"34":{"name":"(anonymous_34)","line":1124,"loc":{"start":{"line":1124,"column":16},"end":{"line":1124,"column":31}}},"35":{"name":"(anonymous_35)","line":1146,"loc":{"start":{"line":1146,"column":20},"end":{"line":1146,"column":31}}},"36":{"name":"(anonymous_36)","line":1155,"loc":{"start":{"line":1155,"column":15},"end":{"line":1155,"column":26}}},"37":{"name":"(anonymous_37)","line":1169,"loc":{"start":{"line":1169,"column":13},"end":{"line":1169,"column":34}}},"38":{"name":"(anonymous_38)","line":1220,"loc":{"start":{"line":1220,"column":15},"end":{"line":1220,"column":49}}},"39":{"name":"(anonymous_39)","line":1271,"loc":{"start":{"line":1271,"column":13},"end":{"line":1271,"column":35}}},"40":{"name":"(anonymous_40)","line":1312,"loc":{"start":{"line":1312,"column":12},"end":{"line":1312,"column":31}}},"41":{"name":"(anonymous_41)","line":1344,"loc":{"start":{"line":1344,"column":14},"end":{"line":1344,"column":36}}},"42":{"name":"(anonymous_42)","line":1352,"loc":{"start":{"line":1352,"column":14},"end":{"line":1352,"column":25}}},"43":{"name":"(anonymous_43)","line":1364,"loc":{"start":{"line":1364,"column":16},"end":{"line":1364,"column":35}}},"44":{"name":"(anonymous_44)","line":1384,"loc":{"start":{"line":1384,"column":11},"end":{"line":1384,"column":26}}},"45":{"name":"(anonymous_45)","line":1387,"loc":{"start":{"line":1387,"column":35},"end":{"line":1387,"column":47}}},"46":{"name":"(anonymous_46)","line":1398,"loc":{"start":{"line":1398,"column":12},"end":{"line":1398,"column":23}}},"47":{"name":"(anonymous_47)","line":1423,"loc":{"start":{"line":1423,"column":13},"end":{"line":1423,"column":28}}},"48":{"name":"(anonymous_48)","line":1458,"loc":{"start":{"line":1458,"column":25},"end":{"line":1458,"column":40}}},"49":{"name":"(anonymous_49)","line":1469,"loc":{"start":{"line":1469,"column":15},"end":{"line":1469,"column":35}}},"50":{"name":"(anonymous_50)","line":1485,"loc":{"start":{"line":1485,"column":26},"end":{"line":1485,"column":46}}},"51":{"name":"(anonymous_51)","line":1514,"loc":{"start":{"line":1514,"column":9},"end":{"line":1514,"column":24}}},"52":{"name":"(anonymous_52)","line":1562,"loc":{"start":{"line":1562,"column":10},"end":{"line":1562,"column":21}}},"53":{"name":"(anonymous_53)","line":1564,"loc":{"start":{"line":1564,"column":21},"end":{"line":1564,"column":36}}},"54":{"name":"(anonymous_54)","line":1584,"loc":{"start":{"line":1584,"column":15},"end":{"line":1584,"column":26}}},"55":{"name":"(anonymous_55)","line":1586,"loc":{"start":{"line":1586,"column":21},"end":{"line":1586,"column":36}}},"56":{"name":"(anonymous_56)","line":1610,"loc":{"start":{"line":1610,"column":15},"end":{"line":1610,"column":35}}},"57":{"name":"(anonymous_57)","line":1643,"loc":{"start":{"line":1643,"column":8},"end":{"line":1643,"column":36}}},"58":{"name":"(anonymous_58)","line":1675,"loc":{"start":{"line":1675,"column":25},"end":{"line":1675,"column":40}}},"59":{"name":"(anonymous_59)","line":1765,"loc":{"start":{"line":1765,"column":15},"end":{"line":1765,"column":26}}},"60":{"name":"(anonymous_60)","line":1785,"loc":{"start":{"line":1785,"column":12},"end":{"line":1785,"column":40}}},"61":{"name":"(anonymous_61)","line":1812,"loc":{"start":{"line":1812,"column":22},"end":{"line":1812,"column":50}}},"62":{"name":"(anonymous_62)","line":1887,"loc":{"start":{"line":1887,"column":17},"end":{"line":1887,"column":28}}},"63":{"name":"(anonymous_63)","line":1898,"loc":{"start":{"line":1898,"column":15},"end":{"line":1898,"column":30}}},"64":{"name":"(anonymous_64)","line":1910,"loc":{"start":{"line":1910,"column":20},"end":{"line":1910,"column":31}}},"65":{"name":"(anonymous_65)","line":1980,"loc":{"start":{"line":1980,"column":13},"end":{"line":1980,"column":34}}},"66":{"name":"(anonymous_66)","line":1995,"loc":{"start":{"line":1995,"column":25},"end":{"line":1995,"column":40}}},"67":{"name":"(anonymous_67)","line":2020,"loc":{"start":{"line":2020,"column":19},"end":{"line":2020,"column":34}}},"68":{"name":"(anonymous_68)","line":2044,"loc":{"start":{"line":2044,"column":15},"end":{"line":2044,"column":50}}},"69":{"name":"(anonymous_69)","line":2096,"loc":{"start":{"line":2096,"column":14},"end":{"line":2096,"column":43}}},"70":{"name":"(anonymous_70)","line":2143,"loc":{"start":{"line":2143,"column":10},"end":{"line":2143,"column":25}}},"71":{"name":"(anonymous_71)","line":2215,"loc":{"start":{"line":2215,"column":16},"end":{"line":2215,"column":35}}},"72":{"name":"(anonymous_72)","line":2240,"loc":{"start":{"line":2240,"column":14},"end":{"line":2240,"column":39}}},"73":{"name":"(anonymous_73)","line":2265,"loc":{"start":{"line":2265,"column":11},"end":{"line":2265,"column":30}}},"74":{"name":"(anonymous_74)","line":2303,"loc":{"start":{"line":2303,"column":12},"end":{"line":2303,"column":23}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":2454,"column":39}},"2":{"start":{"line":9,"column":0},"end":{"line":12,"column":2}},"3":{"start":{"line":29,"column":0},"end":{"line":178,"column":2}},"4":{"start":{"line":76,"column":8},"end":{"line":76,"column":22}},"5":{"start":{"line":77,"column":8},"end":{"line":80,"column":9}},"6":{"start":{"line":78,"column":12},"end":{"line":78,"column":60}},"7":{"start":{"line":79,"column":12},"end":{"line":79,"column":36}},"8":{"start":{"line":82,"column":8},"end":{"line":82,"column":52}},"9":{"start":{"line":113,"column":8},"end":{"line":113,"column":22}},"10":{"start":{"line":114,"column":8},"end":{"line":117,"column":9}},"11":{"start":{"line":115,"column":12},"end":{"line":115,"column":60}},"12":{"start":{"line":116,"column":12},"end":{"line":116,"column":36}},"13":{"start":{"line":119,"column":8},"end":{"line":119,"column":51}},"14":{"start":{"line":138,"column":8},"end":{"line":138,"column":38}},"15":{"start":{"line":140,"column":8},"end":{"line":143,"column":9}},"16":{"start":{"line":142,"column":12},"end":{"line":142,"column":29}},"17":{"start":{"line":145,"column":8},"end":{"line":145,"column":24}},"18":{"start":{"line":147,"column":8},"end":{"line":155,"column":9}},"19":{"start":{"line":149,"column":12},"end":{"line":149,"column":47}},"20":{"start":{"line":152,"column":12},"end":{"line":154,"column":14}},"21":{"start":{"line":153,"column":16},"end":{"line":153,"column":60}},"22":{"start":{"line":158,"column":8},"end":{"line":158,"column":37}},"23":{"start":{"line":161,"column":8},"end":{"line":161,"column":39}},"24":{"start":{"line":163,"column":8},"end":{"line":163,"column":46}},"25":{"start":{"line":174,"column":8},"end":{"line":176,"column":9}},"26":{"start":{"line":175,"column":12},"end":{"line":175,"column":28}},"27":{"start":{"line":180,"column":0},"end":{"line":180,"column":10}},"28":{"start":{"line":212,"column":0},"end":{"line":218,"column":2}},"29":{"start":{"line":213,"column":4},"end":{"line":213,"column":19}},"30":{"start":{"line":214,"column":4},"end":{"line":214,"column":26}},"31":{"start":{"line":215,"column":4},"end":{"line":215,"column":27}},"32":{"start":{"line":216,"column":4},"end":{"line":216,"column":21}},"33":{"start":{"line":217,"column":4},"end":{"line":217,"column":20}},"34":{"start":{"line":227,"column":0},"end":{"line":233,"column":2}},"35":{"start":{"line":228,"column":4},"end":{"line":232,"column":5}},"36":{"start":{"line":229,"column":8},"end":{"line":229,"column":29}},"37":{"start":{"line":231,"column":8},"end":{"line":231,"column":30}},"38":{"start":{"line":242,"column":0},"end":{"line":245,"column":2}},"39":{"start":{"line":243,"column":4},"end":{"line":243,"column":28}},"40":{"start":{"line":244,"column":4},"end":{"line":244,"column":27}},"41":{"start":{"line":261,"column":0},"end":{"line":314,"column":2}},"42":{"start":{"line":263,"column":4},"end":{"line":267,"column":26}},"43":{"start":{"line":270,"column":4},"end":{"line":287,"column":5}},"44":{"start":{"line":271,"column":8},"end":{"line":286,"column":9}},"45":{"start":{"line":272,"column":12},"end":{"line":272,"column":46}},"46":{"start":{"line":273,"column":12},"end":{"line":285,"column":13}},"47":{"start":{"line":274,"column":16},"end":{"line":284,"column":17}},"48":{"start":{"line":276,"column":24},"end":{"line":276,"column":42}},"49":{"start":{"line":278,"column":24},"end":{"line":278,"column":43}},"50":{"start":{"line":279,"column":24},"end":{"line":279,"column":30}},"51":{"start":{"line":281,"column":24},"end":{"line":281,"column":41}},"52":{"start":{"line":282,"column":24},"end":{"line":282,"column":30}},"53":{"start":{"line":290,"column":4},"end":{"line":292,"column":5}},"54":{"start":{"line":291,"column":8},"end":{"line":291,"column":48}},"55":{"start":{"line":294,"column":4},"end":{"line":294,"column":28}},"56":{"start":{"line":295,"column":4},"end":{"line":295,"column":27}},"57":{"start":{"line":298,"column":4},"end":{"line":311,"column":5}},"58":{"start":{"line":299,"column":8},"end":{"line":310,"column":9}},"59":{"start":{"line":300,"column":12},"end":{"line":300,"column":49}},"60":{"start":{"line":302,"column":12},"end":{"line":309,"column":13}},"61":{"start":{"line":303,"column":16},"end":{"line":303,"column":37}},"62":{"start":{"line":305,"column":19},"end":{"line":309,"column":13}},"63":{"start":{"line":306,"column":16},"end":{"line":306,"column":39}},"64":{"start":{"line":308,"column":16},"end":{"line":308,"column":39}},"65":{"start":{"line":313,"column":4},"end":{"line":313,"column":15}},"66":{"start":{"line":329,"column":0},"end":{"line":332,"column":2}},"67":{"start":{"line":330,"column":4},"end":{"line":330,"column":19}},"68":{"start":{"line":331,"column":4},"end":{"line":331,"column":27}},"69":{"start":{"line":343,"column":0},"end":{"line":346,"column":2}},"70":{"start":{"line":344,"column":4},"end":{"line":344,"column":19}},"71":{"start":{"line":345,"column":4},"end":{"line":345,"column":31}},"72":{"start":{"line":358,"column":0},"end":{"line":361,"column":2}},"73":{"start":{"line":359,"column":4},"end":{"line":359,"column":19}},"74":{"start":{"line":360,"column":4},"end":{"line":360,"column":25}},"75":{"start":{"line":371,"column":0},"end":{"line":373,"column":2}},"76":{"start":{"line":372,"column":4},"end":{"line":372,"column":19}},"77":{"start":{"line":385,"column":0},"end":{"line":385,"column":19}},"78":{"start":{"line":399,"column":0},"end":{"line":442,"column":6}},"79":{"start":{"line":433,"column":8},"end":{"line":433,"column":14}},"80":{"start":{"line":435,"column":8},"end":{"line":439,"column":9}},"81":{"start":{"line":436,"column":12},"end":{"line":438,"column":13}},"82":{"start":{"line":437,"column":16},"end":{"line":437,"column":28}},"83":{"start":{"line":441,"column":8},"end":{"line":441,"column":17}},"84":{"start":{"line":468,"column":0},"end":{"line":498,"column":2}},"85":{"start":{"line":470,"column":4},"end":{"line":470,"column":49}},"86":{"start":{"line":472,"column":4},"end":{"line":472,"column":23}},"87":{"start":{"line":474,"column":4},"end":{"line":474,"column":21}},"88":{"start":{"line":475,"column":4},"end":{"line":475,"column":54}},"89":{"start":{"line":477,"column":4},"end":{"line":493,"column":5}},"90":{"start":{"line":491,"column":8},"end":{"line":491,"column":30}},"91":{"start":{"line":492,"column":8},"end":{"line":492,"column":25}},"92":{"start":{"line":495,"column":4},"end":{"line":497,"column":5}},"93":{"start":{"line":496,"column":8},"end":{"line":496,"column":41}},"94":{"start":{"line":523,"column":0},"end":{"line":523,"column":41}},"95":{"start":{"line":525,"column":0},"end":{"line":525,"column":38}},"96":{"start":{"line":527,"column":0},"end":{"line":1210,"column":2}},"97":{"start":{"line":702,"column":8},"end":{"line":706,"column":31}},"98":{"start":{"line":708,"column":8},"end":{"line":710,"column":9}},"99":{"start":{"line":709,"column":12},"end":{"line":709,"column":28}},"100":{"start":{"line":712,"column":8},"end":{"line":714,"column":9}},"101":{"start":{"line":713,"column":12},"end":{"line":713,"column":30}},"102":{"start":{"line":716,"column":8},"end":{"line":727,"column":9}},"103":{"start":{"line":717,"column":12},"end":{"line":717,"column":36}},"104":{"start":{"line":718,"column":12},"end":{"line":718,"column":33}},"105":{"start":{"line":720,"column":12},"end":{"line":722,"column":13}},"106":{"start":{"line":721,"column":16},"end":{"line":721,"column":33}},"107":{"start":{"line":724,"column":12},"end":{"line":726,"column":13}},"108":{"start":{"line":725,"column":16},"end":{"line":725,"column":35}},"109":{"start":{"line":729,"column":8},"end":{"line":731,"column":9}},"110":{"start":{"line":730,"column":12},"end":{"line":730,"column":46}},"111":{"start":{"line":733,"column":8},"end":{"line":733,"column":23}},"112":{"start":{"line":745,"column":8},"end":{"line":745,"column":30}},"113":{"start":{"line":746,"column":8},"end":{"line":747,"column":50}},"114":{"start":{"line":748,"column":8},"end":{"line":748,"column":23}},"115":{"start":{"line":749,"column":8},"end":{"line":749,"column":51}},"116":{"start":{"line":759,"column":8},"end":{"line":763,"column":26}},"117":{"start":{"line":765,"column":8},"end":{"line":768,"column":9}},"118":{"start":{"line":766,"column":12},"end":{"line":766,"column":47}},"119":{"start":{"line":767,"column":12},"end":{"line":767,"column":44}},"120":{"start":{"line":770,"column":8},"end":{"line":782,"column":9}},"121":{"start":{"line":771,"column":12},"end":{"line":775,"column":13}},"122":{"start":{"line":772,"column":16},"end":{"line":772,"column":48}},"123":{"start":{"line":774,"column":16},"end":{"line":774,"column":44}},"124":{"start":{"line":777,"column":12},"end":{"line":781,"column":13}},"125":{"start":{"line":778,"column":16},"end":{"line":778,"column":37}},"126":{"start":{"line":780,"column":16},"end":{"line":780,"column":26}},"127":{"start":{"line":784,"column":8},"end":{"line":796,"column":9}},"128":{"start":{"line":785,"column":12},"end":{"line":789,"column":13}},"129":{"start":{"line":786,"column":16},"end":{"line":786,"column":54}},"130":{"start":{"line":788,"column":16},"end":{"line":788,"column":48}},"131":{"start":{"line":791,"column":12},"end":{"line":795,"column":13}},"132":{"start":{"line":792,"column":16},"end":{"line":792,"column":41}},"133":{"start":{"line":794,"column":16},"end":{"line":794,"column":28}},"134":{"start":{"line":798,"column":8},"end":{"line":798,"column":30}},"135":{"start":{"line":809,"column":8},"end":{"line":809,"column":35}},"136":{"start":{"line":828,"column":8},"end":{"line":828,"column":58}},"137":{"start":{"line":830,"column":8},"end":{"line":836,"column":9}},"138":{"start":{"line":831,"column":12},"end":{"line":835,"column":13}},"139":{"start":{"line":832,"column":16},"end":{"line":832,"column":77}},"140":{"start":{"line":834,"column":16},"end":{"line":834,"column":48}},"141":{"start":{"line":838,"column":8},"end":{"line":850,"column":9}},"142":{"start":{"line":839,"column":12},"end":{"line":842,"column":13}},"143":{"start":{"line":840,"column":16},"end":{"line":840,"column":34}},"144":{"start":{"line":841,"column":16},"end":{"line":841,"column":39}},"145":{"start":{"line":843,"column":12},"end":{"line":843,"column":33}},"146":{"start":{"line":845,"column":12},"end":{"line":848,"column":13}},"147":{"start":{"line":846,"column":16},"end":{"line":846,"column":39}},"148":{"start":{"line":847,"column":16},"end":{"line":847,"column":37}},"149":{"start":{"line":849,"column":12},"end":{"line":849,"column":38}},"150":{"start":{"line":852,"column":8},"end":{"line":858,"column":9}},"151":{"start":{"line":853,"column":12},"end":{"line":857,"column":13}},"152":{"start":{"line":854,"column":16},"end":{"line":854,"column":38}},"153":{"start":{"line":856,"column":16},"end":{"line":856,"column":43}},"154":{"start":{"line":860,"column":8},"end":{"line":860,"column":42}},"155":{"start":{"line":871,"column":8},"end":{"line":871,"column":79}},"156":{"start":{"line":872,"column":8},"end":{"line":872,"column":46}},"157":{"start":{"line":885,"column":8},"end":{"line":885,"column":79}},"158":{"start":{"line":887,"column":8},"end":{"line":891,"column":9}},"159":{"start":{"line":888,"column":12},"end":{"line":890,"column":15}},"160":{"start":{"line":892,"column":8},"end":{"line":892,"column":46}},"161":{"start":{"line":907,"column":8},"end":{"line":907,"column":79}},"162":{"start":{"line":908,"column":8},"end":{"line":908,"column":47}},"163":{"start":{"line":921,"column":8},"end":{"line":923,"column":9}},"164":{"start":{"line":922,"column":12},"end":{"line":922,"column":31}},"165":{"start":{"line":925,"column":8},"end":{"line":928,"column":34}},"166":{"start":{"line":930,"column":8},"end":{"line":938,"column":9}},"167":{"start":{"line":931,"column":12},"end":{"line":937,"column":13}},"168":{"start":{"line":932,"column":16},"end":{"line":932,"column":28}},"169":{"start":{"line":933,"column":16},"end":{"line":936,"column":17}},"170":{"start":{"line":934,"column":20},"end":{"line":934,"column":45}},"171":{"start":{"line":935,"column":20},"end":{"line":935,"column":28}},"172":{"start":{"line":940,"column":8},"end":{"line":948,"column":9}},"173":{"start":{"line":941,"column":12},"end":{"line":947,"column":13}},"174":{"start":{"line":942,"column":16},"end":{"line":942,"column":30}},"175":{"start":{"line":943,"column":16},"end":{"line":946,"column":17}},"176":{"start":{"line":944,"column":20},"end":{"line":944,"column":47}},"177":{"start":{"line":945,"column":20},"end":{"line":945,"column":28}},"178":{"start":{"line":950,"column":8},"end":{"line":950,"column":21}},"179":{"start":{"line":963,"column":8},"end":{"line":963,"column":50}},"180":{"start":{"line":976,"column":8},"end":{"line":976,"column":16}},"181":{"start":{"line":978,"column":8},"end":{"line":978,"column":35}},"182":{"start":{"line":980,"column":8},"end":{"line":982,"column":9}},"183":{"start":{"line":981,"column":12},"end":{"line":981,"column":25}},"184":{"start":{"line":984,"column":8},"end":{"line":984,"column":20}},"185":{"start":{"line":1019,"column":8},"end":{"line":1019,"column":22}},"186":{"start":{"line":1020,"column":8},"end":{"line":1020,"column":41}},"187":{"start":{"line":1022,"column":8},"end":{"line":1022,"column":32}},"188":{"start":{"line":1037,"column":8},"end":{"line":1055,"column":9}},"189":{"start":{"line":1038,"column":12},"end":{"line":1038,"column":24}},"190":{"start":{"line":1044,"column":12},"end":{"line":1044,"column":30}},"191":{"start":{"line":1046,"column":12},"end":{"line":1048,"column":13}},"192":{"start":{"line":1047,"column":16},"end":{"line":1047,"column":38}},"193":{"start":{"line":1050,"column":12},"end":{"line":1054,"column":13}},"194":{"start":{"line":1051,"column":16},"end":{"line":1051,"column":46}},"195":{"start":{"line":1053,"column":16},"end":{"line":1053,"column":45}},"196":{"start":{"line":1067,"column":8},"end":{"line":1067,"column":25}},"197":{"start":{"line":1068,"column":8},"end":{"line":1068,"column":27}},"198":{"start":{"line":1069,"column":8},"end":{"line":1073,"column":9}},"199":{"start":{"line":1070,"column":12},"end":{"line":1070,"column":38}},"200":{"start":{"line":1071,"column":12},"end":{"line":1071,"column":42}},"201":{"start":{"line":1072,"column":12},"end":{"line":1072,"column":42}},"202":{"start":{"line":1074,"column":8},"end":{"line":1076,"column":9}},"203":{"start":{"line":1075,"column":12},"end":{"line":1075,"column":34}},"204":{"start":{"line":1077,"column":8},"end":{"line":1077,"column":43}},"205":{"start":{"line":1082,"column":8},"end":{"line":1082,"column":32}},"206":{"start":{"line":1083,"column":8},"end":{"line":1083,"column":37}},"207":{"start":{"line":1099,"column":8},"end":{"line":1099,"column":20}},"208":{"start":{"line":1101,"column":8},"end":{"line":1111,"column":9}},"209":{"start":{"line":1102,"column":12},"end":{"line":1102,"column":24}},"210":{"start":{"line":1103,"column":12},"end":{"line":1110,"column":13}},"211":{"start":{"line":1104,"column":16},"end":{"line":1106,"column":17}},"212":{"start":{"line":1105,"column":20},"end":{"line":1105,"column":37}},"213":{"start":{"line":1107,"column":16},"end":{"line":1109,"column":17}},"214":{"start":{"line":1108,"column":20},"end":{"line":1108,"column":33}},"215":{"start":{"line":1113,"column":8},"end":{"line":1113,"column":20}},"216":{"start":{"line":1125,"column":8},"end":{"line":1137,"column":9}},"217":{"start":{"line":1127,"column":12},"end":{"line":1127,"column":34}},"218":{"start":{"line":1128,"column":12},"end":{"line":1128,"column":33}},"219":{"start":{"line":1130,"column":12},"end":{"line":1132,"column":13}},"220":{"start":{"line":1131,"column":16},"end":{"line":1131,"column":35}},"221":{"start":{"line":1134,"column":12},"end":{"line":1136,"column":13}},"222":{"start":{"line":1135,"column":16},"end":{"line":1135,"column":49}},"223":{"start":{"line":1147,"column":8},"end":{"line":1147,"column":53}},"224":{"start":{"line":1156,"column":8},"end":{"line":1156,"column":29}},"225":{"start":{"line":1170,"column":8},"end":{"line":1170,"column":27}},"226":{"start":{"line":1172,"column":8},"end":{"line":1175,"column":9}},"227":{"start":{"line":1173,"column":12},"end":{"line":1173,"column":71}},"228":{"start":{"line":1174,"column":12},"end":{"line":1174,"column":43}},"229":{"start":{"line":1177,"column":8},"end":{"line":1189,"column":9}},"230":{"start":{"line":1178,"column":12},"end":{"line":1188,"column":13}},"231":{"start":{"line":1179,"column":16},"end":{"line":1179,"column":34}},"232":{"start":{"line":1181,"column":16},"end":{"line":1187,"column":17}},"233":{"start":{"line":1182,"column":20},"end":{"line":1186,"column":21}},"234":{"start":{"line":1183,"column":24},"end":{"line":1183,"column":48}},"235":{"start":{"line":1185,"column":24},"end":{"line":1185,"column":46}},"236":{"start":{"line":1191,"column":8},"end":{"line":1197,"column":9}},"237":{"start":{"line":1192,"column":12},"end":{"line":1196,"column":13}},"238":{"start":{"line":1193,"column":16},"end":{"line":1193,"column":41}},"239":{"start":{"line":1195,"column":16},"end":{"line":1195,"column":46}},"240":{"start":{"line":1199,"column":8},"end":{"line":1204,"column":9}},"241":{"start":{"line":1200,"column":12},"end":{"line":1203,"column":15}},"242":{"start":{"line":1206,"column":8},"end":{"line":1208,"column":9}},"243":{"start":{"line":1207,"column":12},"end":{"line":1207,"column":29}},"244":{"start":{"line":1220,"column":0},"end":{"line":1266,"column":2}},"245":{"start":{"line":1228,"column":4},"end":{"line":1228,"column":17}},"246":{"start":{"line":1235,"column":4},"end":{"line":1235,"column":27}},"247":{"start":{"line":1242,"column":4},"end":{"line":1242,"column":23}},"248":{"start":{"line":1249,"column":4},"end":{"line":1249,"column":21}},"249":{"start":{"line":1251,"column":4},"end":{"line":1251,"column":22}},"250":{"start":{"line":1268,"column":0},"end":{"line":1356,"column":2}},"251":{"start":{"line":1272,"column":8},"end":{"line":1280,"column":9}},"252":{"start":{"line":1273,"column":12},"end":{"line":1279,"column":13}},"253":{"start":{"line":1274,"column":16},"end":{"line":1274,"column":31}},"254":{"start":{"line":1275,"column":16},"end":{"line":1275,"column":36}},"255":{"start":{"line":1277,"column":16},"end":{"line":1277,"column":38}},"256":{"start":{"line":1278,"column":16},"end":{"line":1278,"column":28}},"257":{"start":{"line":1281,"column":8},"end":{"line":1281,"column":31}},"258":{"start":{"line":1282,"column":8},"end":{"line":1297,"column":9}},"259":{"start":{"line":1284,"column":16},"end":{"line":1284,"column":56}},"260":{"start":{"line":1285,"column":16},"end":{"line":1285,"column":22}},"261":{"start":{"line":1287,"column":16},"end":{"line":1287,"column":58}},"262":{"start":{"line":1288,"column":16},"end":{"line":1288,"column":22}},"263":{"start":{"line":1290,"column":16},"end":{"line":1296,"column":17}},"264":{"start":{"line":1291,"column":20},"end":{"line":1291,"column":38}},"265":{"start":{"line":1292,"column":20},"end":{"line":1292,"column":52}},"266":{"start":{"line":1293,"column":20},"end":{"line":1293,"column":46}},"267":{"start":{"line":1295,"column":20},"end":{"line":1295,"column":42}},"268":{"start":{"line":1299,"column":8},"end":{"line":1301,"column":9}},"269":{"start":{"line":1300,"column":12},"end":{"line":1300,"column":29}},"270":{"start":{"line":1303,"column":8},"end":{"line":1303,"column":19}},"271":{"start":{"line":1313,"column":8},"end":{"line":1314,"column":23}},"272":{"start":{"line":1316,"column":8},"end":{"line":1318,"column":9}},"273":{"start":{"line":1317,"column":12},"end":{"line":1317,"column":61}},"274":{"start":{"line":1321,"column":8},"end":{"line":1329,"column":9}},"275":{"start":{"line":1322,"column":12},"end":{"line":1322,"column":44}},"276":{"start":{"line":1324,"column":12},"end":{"line":1328,"column":13}},"277":{"start":{"line":1325,"column":16},"end":{"line":1325,"column":48}},"278":{"start":{"line":1327,"column":16},"end":{"line":1327,"column":59}},"279":{"start":{"line":1331,"column":8},"end":{"line":1331,"column":19}},"280":{"start":{"line":1345,"column":8},"end":{"line":1349,"column":9}},"281":{"start":{"line":1346,"column":12},"end":{"line":1346,"column":66}},"282":{"start":{"line":1348,"column":12},"end":{"line":1348,"column":36}},"283":{"start":{"line":1353,"column":8},"end":{"line":1353,"column":23}},"284":{"start":{"line":1364,"column":0},"end":{"line":1381,"column":2}},"285":{"start":{"line":1372,"column":4},"end":{"line":1372,"column":19}},"286":{"start":{"line":1380,"column":4},"end":{"line":1380,"column":19}},"287":{"start":{"line":1383,"column":0},"end":{"line":1426,"column":2}},"288":{"start":{"line":1385,"column":8},"end":{"line":1385,"column":32}},"289":{"start":{"line":1386,"column":8},"end":{"line":1390,"column":9}},"290":{"start":{"line":1387,"column":12},"end":{"line":1389,"column":15}},"291":{"start":{"line":1388,"column":16},"end":{"line":1388,"column":40}},"292":{"start":{"line":1399,"column":8},"end":{"line":1399,"column":44}},"293":{"start":{"line":1400,"column":8},"end":{"line":1410,"column":9}},"294":{"start":{"line":1401,"column":12},"end":{"line":1408,"column":13}},"295":{"start":{"line":1402,"column":16},"end":{"line":1404,"column":17}},"296":{"start":{"line":1403,"column":20},"end":{"line":1403,"column":48}},"297":{"start":{"line":1406,"column":16},"end":{"line":1406,"column":38}},"298":{"start":{"line":1407,"column":16},"end":{"line":1407,"column":29}},"299":{"start":{"line":1412,"column":8},"end":{"line":1412,"column":24}},"300":{"start":{"line":1424,"column":8},"end":{"line":1424,"column":59}},"301":{"start":{"line":1452,"column":0},"end":{"line":1544,"column":6}},"302":{"start":{"line":1459,"column":8},"end":{"line":1459,"column":51}},"303":{"start":{"line":1471,"column":8},"end":{"line":1473,"column":9}},"304":{"start":{"line":1472,"column":12},"end":{"line":1472,"column":24}},"305":{"start":{"line":1475,"column":8},"end":{"line":1475,"column":45}},"306":{"start":{"line":1487,"column":8},"end":{"line":1487,"column":47}},"307":{"start":{"line":1489,"column":8},"end":{"line":1491,"column":9}},"308":{"start":{"line":1490,"column":12},"end":{"line":1490,"column":21}},"309":{"start":{"line":1493,"column":8},"end":{"line":1493,"column":36}},"310":{"start":{"line":1495,"column":8},"end":{"line":1498,"column":9}},"311":{"start":{"line":1496,"column":12},"end":{"line":1496,"column":25}},"312":{"start":{"line":1497,"column":12},"end":{"line":1497,"column":46}},"313":{"start":{"line":1500,"column":8},"end":{"line":1500,"column":42}},"314":{"start":{"line":1502,"column":8},"end":{"line":1508,"column":9}},"315":{"start":{"line":1503,"column":12},"end":{"line":1503,"column":46}},"316":{"start":{"line":1504,"column":12},"end":{"line":1504,"column":30}},"317":{"start":{"line":1505,"column":12},"end":{"line":1507,"column":13}},"318":{"start":{"line":1506,"column":16},"end":{"line":1506,"column":25}},"319":{"start":{"line":1511,"column":8},"end":{"line":1511,"column":72}},"320":{"start":{"line":1516,"column":8},"end":{"line":1517,"column":21}},"321":{"start":{"line":1519,"column":8},"end":{"line":1529,"column":9}},"322":{"start":{"line":1520,"column":12},"end":{"line":1528,"column":14}},"323":{"start":{"line":1531,"column":8},"end":{"line":1531,"column":34}},"324":{"start":{"line":1533,"column":8},"end":{"line":1543,"column":9}},"325":{"start":{"line":1534,"column":12},"end":{"line":1534,"column":45}},"326":{"start":{"line":1536,"column":12},"end":{"line":1538,"column":13}},"327":{"start":{"line":1537,"column":16},"end":{"line":1537,"column":43}},"328":{"start":{"line":1540,"column":12},"end":{"line":1542,"column":13}},"329":{"start":{"line":1541,"column":16},"end":{"line":1541,"column":46}},"330":{"start":{"line":1546,"column":0},"end":{"line":2307,"column":2}},"331":{"start":{"line":1563,"column":8},"end":{"line":1563,"column":52}},"332":{"start":{"line":1564,"column":8},"end":{"line":1568,"column":11}},"333":{"start":{"line":1565,"column":12},"end":{"line":1567,"column":13}},"334":{"start":{"line":1566,"column":16},"end":{"line":1566,"column":37}},"335":{"start":{"line":1569,"column":8},"end":{"line":1569,"column":22}},"336":{"start":{"line":1585,"column":8},"end":{"line":1585,"column":55}},"337":{"start":{"line":1586,"column":8},"end":{"line":1590,"column":11}},"338":{"start":{"line":1587,"column":12},"end":{"line":1589,"column":13}},"339":{"start":{"line":1588,"column":16},"end":{"line":1588,"column":37}},"340":{"start":{"line":1591,"column":8},"end":{"line":1591,"column":22}},"341":{"start":{"line":1611,"column":8},"end":{"line":1611,"column":67}},"342":{"start":{"line":1645,"column":8},"end":{"line":1648,"column":46}},"343":{"start":{"line":1651,"column":8},"end":{"line":1655,"column":11}},"344":{"start":{"line":1657,"column":8},"end":{"line":1693,"column":9}},"345":{"start":{"line":1659,"column":12},"end":{"line":1661,"column":13}},"346":{"start":{"line":1660,"column":16},"end":{"line":1660,"column":58}},"347":{"start":{"line":1663,"column":12},"end":{"line":1663,"column":19}},"348":{"start":{"line":1664,"column":12},"end":{"line":1664,"column":24}},"349":{"start":{"line":1665,"column":12},"end":{"line":1665,"column":50}},"350":{"start":{"line":1666,"column":12},"end":{"line":1666,"column":21}},"351":{"start":{"line":1668,"column":12},"end":{"line":1670,"column":13}},"352":{"start":{"line":1669,"column":16},"end":{"line":1669,"column":29}},"353":{"start":{"line":1672,"column":12},"end":{"line":1672,"column":32}},"354":{"start":{"line":1673,"column":12},"end":{"line":1673,"column":31}},"355":{"start":{"line":1675,"column":12},"end":{"line":1690,"column":21}},"356":{"start":{"line":1677,"column":16},"end":{"line":1680,"column":17}},"357":{"start":{"line":1678,"column":20},"end":{"line":1678,"column":60}},"358":{"start":{"line":1679,"column":20},"end":{"line":1679,"column":39}},"359":{"start":{"line":1682,"column":16},"end":{"line":1682,"column":53}},"360":{"start":{"line":1684,"column":16},"end":{"line":1684,"column":49}},"361":{"start":{"line":1685,"column":16},"end":{"line":1685,"column":28}},"362":{"start":{"line":1686,"column":16},"end":{"line":1686,"column":28}},"363":{"start":{"line":1688,"column":16},"end":{"line":1688,"column":52}},"364":{"start":{"line":1692,"column":12},"end":{"line":1692,"column":66}},"365":{"start":{"line":1695,"column":8},"end":{"line":1695,"column":34}},"366":{"start":{"line":1696,"column":8},"end":{"line":1696,"column":25}},"367":{"start":{"line":1697,"column":8},"end":{"line":1697,"column":29}},"368":{"start":{"line":1700,"column":8},"end":{"line":1704,"column":9}},"369":{"start":{"line":1701,"column":12},"end":{"line":1701,"column":50}},"370":{"start":{"line":1702,"column":12},"end":{"line":1702,"column":53}},"371":{"start":{"line":1703,"column":12},"end":{"line":1703,"column":39}},"372":{"start":{"line":1706,"column":8},"end":{"line":1706,"column":24}},"373":{"start":{"line":1708,"column":8},"end":{"line":1738,"column":9}},"374":{"start":{"line":1710,"column":12},"end":{"line":1710,"column":44}},"375":{"start":{"line":1711,"column":12},"end":{"line":1711,"column":51}},"376":{"start":{"line":1712,"column":12},"end":{"line":1712,"column":32}},"377":{"start":{"line":1714,"column":12},"end":{"line":1729,"column":13}},"378":{"start":{"line":1715,"column":16},"end":{"line":1715,"column":28}},"379":{"start":{"line":1717,"column":16},"end":{"line":1721,"column":17}},"380":{"start":{"line":1718,"column":20},"end":{"line":1718,"column":50}},"381":{"start":{"line":1719,"column":23},"end":{"line":1721,"column":17}},"382":{"start":{"line":1720,"column":20},"end":{"line":1720,"column":43}},"383":{"start":{"line":1723,"column":16},"end":{"line":1723,"column":58}},"384":{"start":{"line":1726,"column":16},"end":{"line":1728,"column":17}},"385":{"start":{"line":1727,"column":20},"end":{"line":1727,"column":32}},"386":{"start":{"line":1732,"column":12},"end":{"line":1736,"column":13}},"387":{"start":{"line":1733,"column":16},"end":{"line":1733,"column":49}},"388":{"start":{"line":1734,"column":19},"end":{"line":1736,"column":13}},"389":{"start":{"line":1735,"column":16},"end":{"line":1735,"column":47}},"390":{"start":{"line":1740,"column":8},"end":{"line":1748,"column":9}},"391":{"start":{"line":1741,"column":12},"end":{"line":1741,"column":59}},"392":{"start":{"line":1742,"column":12},"end":{"line":1742,"column":131}},"393":{"start":{"line":1745,"column":12},"end":{"line":1747,"column":13}},"394":{"start":{"line":1746,"column":16},"end":{"line":1746,"column":41}},"395":{"start":{"line":1750,"column":8},"end":{"line":1754,"column":9}},"396":{"start":{"line":1751,"column":12},"end":{"line":1751,"column":64}},"397":{"start":{"line":1752,"column":12},"end":{"line":1752,"column":76}},"398":{"start":{"line":1753,"column":12},"end":{"line":1753,"column":53}},"399":{"start":{"line":1756,"column":8},"end":{"line":1756,"column":46}},"400":{"start":{"line":1766,"column":8},"end":{"line":1766,"column":46}},"401":{"start":{"line":1787,"column":8},"end":{"line":1790,"column":56}},"402":{"start":{"line":1793,"column":8},"end":{"line":1804,"column":9}},"403":{"start":{"line":1794,"column":12},"end":{"line":1798,"column":13}},"404":{"start":{"line":1795,"column":16},"end":{"line":1797,"column":17}},"405":{"start":{"line":1796,"column":20},"end":{"line":1796,"column":48}},"406":{"start":{"line":1799,"column":12},"end":{"line":1801,"column":13}},"407":{"start":{"line":1800,"column":16},"end":{"line":1800,"column":60}},"408":{"start":{"line":1803,"column":12},"end":{"line":1803,"column":24}},"409":{"start":{"line":1806,"column":8},"end":{"line":1822,"column":10}},"410":{"start":{"line":1813,"column":12},"end":{"line":1813,"column":45}},"411":{"start":{"line":1814,"column":12},"end":{"line":1821,"column":13}},"412":{"start":{"line":1815,"column":16},"end":{"line":1820,"column":17}},"413":{"start":{"line":1816,"column":20},"end":{"line":1816,"column":40}},"414":{"start":{"line":1817,"column":20},"end":{"line":1819,"column":21}},"415":{"start":{"line":1818,"column":24},"end":{"line":1818,"column":44}},"416":{"start":{"line":1824,"column":8},"end":{"line":1854,"column":9}},"417":{"start":{"line":1826,"column":12},"end":{"line":1826,"column":40}},"418":{"start":{"line":1827,"column":12},"end":{"line":1827,"column":28}},"419":{"start":{"line":1828,"column":12},"end":{"line":1828,"column":67}},"420":{"start":{"line":1830,"column":12},"end":{"line":1842,"column":13}},"421":{"start":{"line":1831,"column":16},"end":{"line":1839,"column":17}},"422":{"start":{"line":1832,"column":20},"end":{"line":1832,"column":55}},"423":{"start":{"line":1834,"column":20},"end":{"line":1838,"column":21}},"424":{"start":{"line":1835,"column":24},"end":{"line":1837,"column":25}},"425":{"start":{"line":1836,"column":28},"end":{"line":1836,"column":60}},"426":{"start":{"line":1841,"column":16},"end":{"line":1841,"column":28}},"427":{"start":{"line":1845,"column":15},"end":{"line":1854,"column":9}},"428":{"start":{"line":1846,"column":12},"end":{"line":1846,"column":26}},"429":{"start":{"line":1847,"column":12},"end":{"line":1847,"column":24}},"430":{"start":{"line":1849,"column":15},"end":{"line":1854,"column":9}},"431":{"start":{"line":1850,"column":12},"end":{"line":1850,"column":50}},"432":{"start":{"line":1851,"column":12},"end":{"line":1851,"column":44}},"433":{"start":{"line":1852,"column":12},"end":{"line":1852,"column":36}},"434":{"start":{"line":1853,"column":12},"end":{"line":1853,"column":24}},"435":{"start":{"line":1856,"column":8},"end":{"line":1856,"column":45}},"436":{"start":{"line":1859,"column":8},"end":{"line":1871,"column":9}},"437":{"start":{"line":1860,"column":12},"end":{"line":1860,"column":50}},"438":{"start":{"line":1862,"column":12},"end":{"line":1870,"column":13}},"439":{"start":{"line":1863,"column":16},"end":{"line":1863,"column":44}},"440":{"start":{"line":1864,"column":16},"end":{"line":1864,"column":28}},"441":{"start":{"line":1866,"column":19},"end":{"line":1870,"column":13}},"442":{"start":{"line":1867,"column":16},"end":{"line":1867,"column":31}},"443":{"start":{"line":1868,"column":16},"end":{"line":1868,"column":52}},"444":{"start":{"line":1869,"column":16},"end":{"line":1869,"column":28}},"445":{"start":{"line":1874,"column":8},"end":{"line":1874,"column":28}},"446":{"start":{"line":1875,"column":8},"end":{"line":1877,"column":9}},"447":{"start":{"line":1876,"column":12},"end":{"line":1876,"column":35}},"448":{"start":{"line":1879,"column":8},"end":{"line":1879,"column":20}},"449":{"start":{"line":1888,"column":8},"end":{"line":1888,"column":50}},"450":{"start":{"line":1899,"column":8},"end":{"line":1899,"column":33}},"451":{"start":{"line":1911,"column":8},"end":{"line":1911,"column":53}},"452":{"start":{"line":1982,"column":8},"end":{"line":1985,"column":34}},"453":{"start":{"line":1987,"column":8},"end":{"line":2002,"column":9}},"454":{"start":{"line":1988,"column":12},"end":{"line":1990,"column":13}},"455":{"start":{"line":1989,"column":16},"end":{"line":1989,"column":43}},"456":{"start":{"line":1991,"column":12},"end":{"line":1991,"column":54}},"457":{"start":{"line":1993,"column":12},"end":{"line":1993,"column":21}},"458":{"start":{"line":1995,"column":12},"end":{"line":2000,"column":21}},"459":{"start":{"line":1996,"column":16},"end":{"line":1998,"column":17}},"460":{"start":{"line":1997,"column":20},"end":{"line":1997,"column":41}},"461":{"start":{"line":1999,"column":16},"end":{"line":1999,"column":63}},"462":{"start":{"line":2004,"column":8},"end":{"line":2004,"column":19}},"463":{"start":{"line":2022,"column":8},"end":{"line":2022,"column":45}},"464":{"start":{"line":2024,"column":8},"end":{"line":2028,"column":9}},"465":{"start":{"line":2025,"column":12},"end":{"line":2025,"column":49}},"466":{"start":{"line":2027,"column":12},"end":{"line":2027,"column":24}},"467":{"start":{"line":2046,"column":8},"end":{"line":2051,"column":36}},"468":{"start":{"line":2053,"column":8},"end":{"line":2053,"column":30}},"469":{"start":{"line":2056,"column":8},"end":{"line":2060,"column":9}},"470":{"start":{"line":2057,"column":12},"end":{"line":2059,"column":15}},"471":{"start":{"line":2062,"column":8},"end":{"line":2070,"column":9}},"472":{"start":{"line":2064,"column":12},"end":{"line":2064,"column":72}},"473":{"start":{"line":2066,"column":12},"end":{"line":2069,"column":13}},"474":{"start":{"line":2067,"column":16},"end":{"line":2067,"column":31}},"475":{"start":{"line":2068,"column":16},"end":{"line":2068,"column":37}},"476":{"start":{"line":2072,"column":8},"end":{"line":2074,"column":9}},"477":{"start":{"line":2073,"column":12},"end":{"line":2073,"column":41}},"478":{"start":{"line":2076,"column":8},"end":{"line":2076,"column":18}},"479":{"start":{"line":2097,"column":8},"end":{"line":2097,"column":33}},"480":{"start":{"line":2099,"column":8},"end":{"line":2113,"column":9}},"481":{"start":{"line":2100,"column":12},"end":{"line":2106,"column":13}},"482":{"start":{"line":2101,"column":16},"end":{"line":2101,"column":33}},"483":{"start":{"line":2102,"column":16},"end":{"line":2102,"column":52}},"484":{"start":{"line":2104,"column":16},"end":{"line":2104,"column":31}},"485":{"start":{"line":2105,"column":16},"end":{"line":2105,"column":38}},"486":{"start":{"line":2108,"column":12},"end":{"line":2112,"column":13}},"487":{"start":{"line":2109,"column":16},"end":{"line":2109,"column":47}},"488":{"start":{"line":2110,"column":16},"end":{"line":2110,"column":35}},"489":{"start":{"line":2111,"column":16},"end":{"line":2111,"column":52}},"490":{"start":{"line":2145,"column":8},"end":{"line":2154,"column":17}},"491":{"start":{"line":2156,"column":8},"end":{"line":2168,"column":9}},"492":{"start":{"line":2160,"column":12},"end":{"line":2164,"column":13}},"493":{"start":{"line":2161,"column":16},"end":{"line":2161,"column":38}},"494":{"start":{"line":2163,"column":16},"end":{"line":2163,"column":26}},"495":{"start":{"line":2167,"column":12},"end":{"line":2167,"column":73}},"496":{"start":{"line":2170,"column":8},"end":{"line":2172,"column":9}},"497":{"start":{"line":2171,"column":12},"end":{"line":2171,"column":36}},"498":{"start":{"line":2174,"column":8},"end":{"line":2176,"column":9}},"499":{"start":{"line":2175,"column":12},"end":{"line":2175,"column":33}},"500":{"start":{"line":2178,"column":8},"end":{"line":2178,"column":30}},"501":{"start":{"line":2180,"column":8},"end":{"line":2186,"column":9}},"502":{"start":{"line":2181,"column":12},"end":{"line":2181,"column":41}},"503":{"start":{"line":2183,"column":12},"end":{"line":2185,"column":13}},"504":{"start":{"line":2184,"column":16},"end":{"line":2184,"column":37}},"505":{"start":{"line":2189,"column":8},"end":{"line":2193,"column":9}},"506":{"start":{"line":2190,"column":12},"end":{"line":2192,"column":15}},"507":{"start":{"line":2196,"column":8},"end":{"line":2210,"column":9}},"508":{"start":{"line":2197,"column":12},"end":{"line":2199,"column":13}},"509":{"start":{"line":2198,"column":16},"end":{"line":2198,"column":60}},"510":{"start":{"line":2202,"column":12},"end":{"line":2202,"column":23}},"511":{"start":{"line":2205,"column":12},"end":{"line":2207,"column":13}},"512":{"start":{"line":2206,"column":16},"end":{"line":2206,"column":33}},"513":{"start":{"line":2209,"column":12},"end":{"line":2209,"column":33}},"514":{"start":{"line":2212,"column":8},"end":{"line":2212,"column":43}},"515":{"start":{"line":2216,"column":8},"end":{"line":2216,"column":16}},"516":{"start":{"line":2219,"column":8},"end":{"line":2227,"column":9}},"517":{"start":{"line":2220,"column":12},"end":{"line":2220,"column":35}},"518":{"start":{"line":2221,"column":12},"end":{"line":2221,"column":44}},"519":{"start":{"line":2222,"column":12},"end":{"line":2226,"column":13}},"520":{"start":{"line":2223,"column":16},"end":{"line":2223,"column":36}},"521":{"start":{"line":2224,"column":16},"end":{"line":2224,"column":36}},"522":{"start":{"line":2225,"column":16},"end":{"line":2225,"column":34}},"523":{"start":{"line":2229,"column":8},"end":{"line":2229,"column":19}},"524":{"start":{"line":2241,"column":8},"end":{"line":2241,"column":19}},"525":{"start":{"line":2243,"column":8},"end":{"line":2246,"column":9}},"526":{"start":{"line":2244,"column":12},"end":{"line":2244,"column":45}},"527":{"start":{"line":2245,"column":12},"end":{"line":2245,"column":54}},"528":{"start":{"line":2247,"column":8},"end":{"line":2247,"column":32}},"529":{"start":{"line":2248,"column":8},"end":{"line":2248,"column":31}},"530":{"start":{"line":2267,"column":8},"end":{"line":2267,"column":47}},"531":{"start":{"line":2269,"column":8},"end":{"line":2282,"column":9}},"532":{"start":{"line":2271,"column":16},"end":{"line":2271,"column":57}},"533":{"start":{"line":2278,"column":16},"end":{"line":2278,"column":35}},"534":{"start":{"line":2279,"column":16},"end":{"line":2279,"column":22}},"535":{"start":{"line":2281,"column":16},"end":{"line":2281,"column":43}},"536":{"start":{"line":2284,"column":8},"end":{"line":2284,"column":38}},"537":{"start":{"line":2304,"column":8},"end":{"line":2304,"column":46}},"538":{"start":{"line":2309,"column":0},"end":{"line":2309,"column":19}},"539":{"start":{"line":2312,"column":0},"end":{"line":2312,"column":23}},"540":{"start":{"line":2313,"column":0},"end":{"line":2313,"column":31}},"541":{"start":{"line":2315,"column":0},"end":{"line":2315,"column":56}},"542":{"start":{"line":2325,"column":0},"end":{"line":2325,"column":32}}},"branchMap":{"1":{"line":77,"type":"if","locations":[{"start":{"line":77,"column":8},"end":{"line":77,"column":8}},{"start":{"line":77,"column":8},"end":{"line":77,"column":8}}]},"2":{"line":114,"type":"if","locations":[{"start":{"line":114,"column":8},"end":{"line":114,"column":8}},{"start":{"line":114,"column":8},"end":{"line":114,"column":8}}]},"3":{"line":140,"type":"if","locations":[{"start":{"line":140,"column":8},"end":{"line":140,"column":8}},{"start":{"line":140,"column":8},"end":{"line":140,"column":8}}]},"4":{"line":147,"type":"if","locations":[{"start":{"line":147,"column":8},"end":{"line":147,"column":8}},{"start":{"line":147,"column":8},"end":{"line":147,"column":8}}]},"5":{"line":174,"type":"if","locations":[{"start":{"line":174,"column":8},"end":{"line":174,"column":8}},{"start":{"line":174,"column":8},"end":{"line":174,"column":8}}]},"6":{"line":228,"type":"if","locations":[{"start":{"line":228,"column":4},"end":{"line":228,"column":4}},{"start":{"line":228,"column":4},"end":{"line":228,"column":4}}]},"7":{"line":271,"type":"if","locations":[{"start":{"line":271,"column":8},"end":{"line":271,"column":8}},{"start":{"line":271,"column":8},"end":{"line":271,"column":8}}]},"8":{"line":273,"type":"if","locations":[{"start":{"line":273,"column":12},"end":{"line":273,"column":12}},{"start":{"line":273,"column":12},"end":{"line":273,"column":12}}]},"9":{"line":274,"type":"switch","locations":[{"start":{"line":275,"column":20},"end":{"line":276,"column":42}},{"start":{"line":277,"column":20},"end":{"line":279,"column":30}},{"start":{"line":280,"column":20},"end":{"line":282,"column":30}},{"start":{"line":283,"column":20},"end":{"line":283,"column":28}}]},"10":{"line":290,"type":"if","locations":[{"start":{"line":290,"column":4},"end":{"line":290,"column":4}},{"start":{"line":290,"column":4},"end":{"line":290,"column":4}}]},"11":{"line":299,"type":"if","locations":[{"start":{"line":299,"column":8},"end":{"line":299,"column":8}},{"start":{"line":299,"column":8},"end":{"line":299,"column":8}}]},"12":{"line":302,"type":"if","locations":[{"start":{"line":302,"column":12},"end":{"line":302,"column":12}},{"start":{"line":302,"column":12},"end":{"line":302,"column":12}}]},"13":{"line":302,"type":"binary-expr","locations":[{"start":{"line":302,"column":16},"end":{"line":302,"column":22}},{"start":{"line":302,"column":26},"end":{"line":302,"column":56}}]},"14":{"line":305,"type":"if","locations":[{"start":{"line":305,"column":19},"end":{"line":305,"column":19}},{"start":{"line":305,"column":19},"end":{"line":305,"column":19}}]},"15":{"line":305,"type":"binary-expr","locations":[{"start":{"line":305,"column":23},"end":{"line":305,"column":29}},{"start":{"line":305,"column":33},"end":{"line":305,"column":70}}]},"16":{"line":436,"type":"if","locations":[{"start":{"line":436,"column":12},"end":{"line":436,"column":12}},{"start":{"line":436,"column":12},"end":{"line":436,"column":12}}]},"17":{"line":436,"type":"binary-expr","locations":[{"start":{"line":436,"column":16},"end":{"line":436,"column":31}},{"start":{"line":436,"column":36},"end":{"line":436,"column":38}},{"start":{"line":436,"column":42},"end":{"line":436,"column":51}}]},"18":{"line":477,"type":"if","locations":[{"start":{"line":477,"column":4},"end":{"line":477,"column":4}},{"start":{"line":477,"column":4},"end":{"line":477,"column":4}}]},"19":{"line":495,"type":"if","locations":[{"start":{"line":495,"column":4},"end":{"line":495,"column":4}},{"start":{"line":495,"column":4},"end":{"line":495,"column":4}}]},"20":{"line":708,"type":"if","locations":[{"start":{"line":708,"column":8},"end":{"line":708,"column":8}},{"start":{"line":708,"column":8},"end":{"line":708,"column":8}}]},"21":{"line":712,"type":"if","locations":[{"start":{"line":712,"column":8},"end":{"line":712,"column":8}},{"start":{"line":712,"column":8},"end":{"line":712,"column":8}}]},"22":{"line":716,"type":"if","locations":[{"start":{"line":716,"column":8},"end":{"line":716,"column":8}},{"start":{"line":716,"column":8},"end":{"line":716,"column":8}}]},"23":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":12},"end":{"line":720,"column":12}},{"start":{"line":720,"column":12},"end":{"line":720,"column":12}}]},"24":{"line":724,"type":"if","locations":[{"start":{"line":724,"column":12},"end":{"line":724,"column":12}},{"start":{"line":724,"column":12},"end":{"line":724,"column":12}}]},"25":{"line":729,"type":"if","locations":[{"start":{"line":729,"column":8},"end":{"line":729,"column":8}},{"start":{"line":729,"column":8},"end":{"line":729,"column":8}}]},"26":{"line":730,"type":"cond-expr","locations":[{"start":{"line":730,"column":40},"end":{"line":730,"column":41}},{"start":{"line":730,"column":44},"end":{"line":730,"column":45}}]},"27":{"line":765,"type":"if","locations":[{"start":{"line":765,"column":8},"end":{"line":765,"column":8}},{"start":{"line":765,"column":8},"end":{"line":765,"column":8}}]},"28":{"line":770,"type":"if","locations":[{"start":{"line":770,"column":8},"end":{"line":770,"column":8}},{"start":{"line":770,"column":8},"end":{"line":770,"column":8}}]},"29":{"line":771,"type":"if","locations":[{"start":{"line":771,"column":12},"end":{"line":771,"column":12}},{"start":{"line":771,"column":12},"end":{"line":771,"column":12}}]},"30":{"line":777,"type":"if","locations":[{"start":{"line":777,"column":12},"end":{"line":777,"column":12}},{"start":{"line":777,"column":12},"end":{"line":777,"column":12}}]},"31":{"line":784,"type":"if","locations":[{"start":{"line":784,"column":8},"end":{"line":784,"column":8}},{"start":{"line":784,"column":8},"end":{"line":784,"column":8}}]},"32":{"line":785,"type":"if","locations":[{"start":{"line":785,"column":12},"end":{"line":785,"column":12}},{"start":{"line":785,"column":12},"end":{"line":785,"column":12}}]},"33":{"line":791,"type":"if","locations":[{"start":{"line":791,"column":12},"end":{"line":791,"column":12}},{"start":{"line":791,"column":12},"end":{"line":791,"column":12}}]},"34":{"line":830,"type":"if","locations":[{"start":{"line":830,"column":8},"end":{"line":830,"column":8}},{"start":{"line":830,"column":8},"end":{"line":830,"column":8}}]},"35":{"line":830,"type":"binary-expr","locations":[{"start":{"line":830,"column":12},"end":{"line":830,"column":25}},{"start":{"line":830,"column":29},"end":{"line":830,"column":39}}]},"36":{"line":831,"type":"if","locations":[{"start":{"line":831,"column":12},"end":{"line":831,"column":12}},{"start":{"line":831,"column":12},"end":{"line":831,"column":12}}]},"37":{"line":838,"type":"if","locations":[{"start":{"line":838,"column":8},"end":{"line":838,"column":8}},{"start":{"line":838,"column":8},"end":{"line":838,"column":8}}]},"38":{"line":839,"type":"if","locations":[{"start":{"line":839,"column":12},"end":{"line":839,"column":12}},{"start":{"line":839,"column":12},"end":{"line":839,"column":12}}]},"39":{"line":845,"type":"if","locations":[{"start":{"line":845,"column":12},"end":{"line":845,"column":12}},{"start":{"line":845,"column":12},"end":{"line":845,"column":12}}]},"40":{"line":852,"type":"if","locations":[{"start":{"line":852,"column":8},"end":{"line":852,"column":8}},{"start":{"line":852,"column":8},"end":{"line":852,"column":8}}]},"41":{"line":853,"type":"if","locations":[{"start":{"line":853,"column":12},"end":{"line":853,"column":12}},{"start":{"line":853,"column":12},"end":{"line":853,"column":12}}]},"42":{"line":871,"type":"cond-expr","locations":[{"start":{"line":871,"column":41},"end":{"line":871,"column":71}},{"start":{"line":871,"column":74},"end":{"line":871,"column":78}}]},"43":{"line":885,"type":"cond-expr","locations":[{"start":{"line":885,"column":41},"end":{"line":885,"column":71}},{"start":{"line":885,"column":74},"end":{"line":885,"column":78}}]},"44":{"line":887,"type":"if","locations":[{"start":{"line":887,"column":8},"end":{"line":887,"column":8}},{"start":{"line":887,"column":8},"end":{"line":887,"column":8}}]},"45":{"line":887,"type":"binary-expr","locations":[{"start":{"line":887,"column":12},"end":{"line":887,"column":26}},{"start":{"line":887,"column":30},"end":{"line":887,"column":39}}]},"46":{"line":907,"type":"cond-expr","locations":[{"start":{"line":907,"column":41},"end":{"line":907,"column":71}},{"start":{"line":907,"column":74},"end":{"line":907,"column":78}}]},"47":{"line":921,"type":"if","locations":[{"start":{"line":921,"column":8},"end":{"line":921,"column":8}},{"start":{"line":921,"column":8},"end":{"line":921,"column":8}}]},"48":{"line":921,"type":"binary-expr","locations":[{"start":{"line":921,"column":12},"end":{"line":921,"column":14}},{"start":{"line":921,"column":18},"end":{"line":921,"column":27}}]},"49":{"line":930,"type":"if","locations":[{"start":{"line":930,"column":8},"end":{"line":930,"column":8}},{"start":{"line":930,"column":8},"end":{"line":930,"column":8}}]},"50":{"line":933,"type":"if","locations":[{"start":{"line":933,"column":16},"end":{"line":933,"column":16}},{"start":{"line":933,"column":16},"end":{"line":933,"column":16}}]},"51":{"line":933,"type":"binary-expr","locations":[{"start":{"line":933,"column":20},"end":{"line":933,"column":21}},{"start":{"line":933,"column":26},"end":{"line":933,"column":29}},{"start":{"line":933,"column":33},"end":{"line":933,"column":44}}]},"52":{"line":940,"type":"if","locations":[{"start":{"line":940,"column":8},"end":{"line":940,"column":8}},{"start":{"line":940,"column":8},"end":{"line":940,"column":8}}]},"53":{"line":943,"type":"if","locations":[{"start":{"line":943,"column":16},"end":{"line":943,"column":16}},{"start":{"line":943,"column":16},"end":{"line":943,"column":16}}]},"54":{"line":943,"type":"binary-expr","locations":[{"start":{"line":943,"column":20},"end":{"line":943,"column":21}},{"start":{"line":943,"column":26},"end":{"line":943,"column":29}},{"start":{"line":943,"column":33},"end":{"line":943,"column":44}}]},"55":{"line":980,"type":"if","locations":[{"start":{"line":980,"column":8},"end":{"line":980,"column":8}},{"start":{"line":980,"column":8},"end":{"line":980,"column":8}}]},"56":{"line":980,"type":"binary-expr","locations":[{"start":{"line":980,"column":12},"end":{"line":980,"column":25}},{"start":{"line":980,"column":29},"end":{"line":980,"column":45}}]},"57":{"line":1037,"type":"if","locations":[{"start":{"line":1037,"column":8},"end":{"line":1037,"column":8}},{"start":{"line":1037,"column":8},"end":{"line":1037,"column":8}}]},"58":{"line":1037,"type":"binary-expr","locations":[{"start":{"line":1037,"column":12},"end":{"line":1037,"column":25}},{"start":{"line":1037,"column":29},"end":{"line":1037,"column":39}}]},"59":{"line":1046,"type":"if","locations":[{"start":{"line":1046,"column":12},"end":{"line":1046,"column":12}},{"start":{"line":1046,"column":12},"end":{"line":1046,"column":12}}]},"60":{"line":1050,"type":"if","locations":[{"start":{"line":1050,"column":12},"end":{"line":1050,"column":12}},{"start":{"line":1050,"column":12},"end":{"line":1050,"column":12}}]},"61":{"line":1069,"type":"if","locations":[{"start":{"line":1069,"column":8},"end":{"line":1069,"column":8}},{"start":{"line":1069,"column":8},"end":{"line":1069,"column":8}}]},"62":{"line":1074,"type":"if","locations":[{"start":{"line":1074,"column":8},"end":{"line":1074,"column":8}},{"start":{"line":1074,"column":8},"end":{"line":1074,"column":8}}]},"63":{"line":1077,"type":"cond-expr","locations":[{"start":{"line":1077,"column":30},"end":{"line":1077,"column":35}},{"start":{"line":1077,"column":38},"end":{"line":1077,"column":42}}]},"64":{"line":1082,"type":"binary-expr","locations":[{"start":{"line":1082,"column":18},"end":{"line":1082,"column":25}},{"start":{"line":1082,"column":29},"end":{"line":1082,"column":31}}]},"65":{"line":1103,"type":"if","locations":[{"start":{"line":1103,"column":12},"end":{"line":1103,"column":12}},{"start":{"line":1103,"column":12},"end":{"line":1103,"column":12}}]},"66":{"line":1103,"type":"binary-expr","locations":[{"start":{"line":1103,"column":16},"end":{"line":1103,"column":17}},{"start":{"line":1103,"column":21},"end":{"line":1103,"column":25}}]},"67":{"line":1104,"type":"if","locations":[{"start":{"line":1104,"column":16},"end":{"line":1104,"column":16}},{"start":{"line":1104,"column":16},"end":{"line":1104,"column":16}}]},"68":{"line":1107,"type":"if","locations":[{"start":{"line":1107,"column":16},"end":{"line":1107,"column":16}},{"start":{"line":1107,"column":16},"end":{"line":1107,"column":16}}]},"69":{"line":1125,"type":"if","locations":[{"start":{"line":1125,"column":8},"end":{"line":1125,"column":8}},{"start":{"line":1125,"column":8},"end":{"line":1125,"column":8}}]},"70":{"line":1125,"type":"binary-expr","locations":[{"start":{"line":1125,"column":12},"end":{"line":1125,"column":25}},{"start":{"line":1125,"column":29},"end":{"line":1125,"column":43}}]},"71":{"line":1130,"type":"if","locations":[{"start":{"line":1130,"column":12},"end":{"line":1130,"column":12}},{"start":{"line":1130,"column":12},"end":{"line":1130,"column":12}}]},"72":{"line":1134,"type":"if","locations":[{"start":{"line":1134,"column":12},"end":{"line":1134,"column":12}},{"start":{"line":1134,"column":12},"end":{"line":1134,"column":12}}]},"73":{"line":1172,"type":"if","locations":[{"start":{"line":1172,"column":8},"end":{"line":1172,"column":8}},{"start":{"line":1172,"column":8},"end":{"line":1172,"column":8}}]},"74":{"line":1173,"type":"cond-expr","locations":[{"start":{"line":1173,"column":38},"end":{"line":1173,"column":50}},{"start":{"line":1173,"column":53},"end":{"line":1173,"column":70}}]},"75":{"line":1177,"type":"if","locations":[{"start":{"line":1177,"column":8},"end":{"line":1177,"column":8}},{"start":{"line":1177,"column":8},"end":{"line":1177,"column":8}}]},"76":{"line":1178,"type":"if","locations":[{"start":{"line":1178,"column":12},"end":{"line":1178,"column":12}},{"start":{"line":1178,"column":12},"end":{"line":1178,"column":12}}]},"77":{"line":1178,"type":"binary-expr","locations":[{"start":{"line":1178,"column":16},"end":{"line":1178,"column":17}},{"start":{"line":1178,"column":21},"end":{"line":1178,"column":34}}]},"78":{"line":1181,"type":"if","locations":[{"start":{"line":1181,"column":16},"end":{"line":1181,"column":16}},{"start":{"line":1181,"column":16},"end":{"line":1181,"column":16}}]},"79":{"line":1182,"type":"if","locations":[{"start":{"line":1182,"column":20},"end":{"line":1182,"column":20}},{"start":{"line":1182,"column":20},"end":{"line":1182,"column":20}}]},"80":{"line":1191,"type":"if","locations":[{"start":{"line":1191,"column":8},"end":{"line":1191,"column":8}},{"start":{"line":1191,"column":8},"end":{"line":1191,"column":8}}]},"81":{"line":1192,"type":"if","locations":[{"start":{"line":1192,"column":12},"end":{"line":1192,"column":12}},{"start":{"line":1192,"column":12},"end":{"line":1192,"column":12}}]},"82":{"line":1199,"type":"if","locations":[{"start":{"line":1199,"column":8},"end":{"line":1199,"column":8}},{"start":{"line":1199,"column":8},"end":{"line":1199,"column":8}}]},"83":{"line":1199,"type":"binary-expr","locations":[{"start":{"line":1199,"column":12},"end":{"line":1199,"column":26}},{"start":{"line":1199,"column":30},"end":{"line":1199,"column":39}}]},"84":{"line":1206,"type":"if","locations":[{"start":{"line":1206,"column":8},"end":{"line":1206,"column":8}},{"start":{"line":1206,"column":8},"end":{"line":1206,"column":8}}]},"85":{"line":1272,"type":"if","locations":[{"start":{"line":1272,"column":8},"end":{"line":1272,"column":8}},{"start":{"line":1272,"column":8},"end":{"line":1272,"column":8}}]},"86":{"line":1272,"type":"binary-expr","locations":[{"start":{"line":1272,"column":12},"end":{"line":1272,"column":24}},{"start":{"line":1272,"column":28},"end":{"line":1272,"column":43}}]},"87":{"line":1273,"type":"if","locations":[{"start":{"line":1273,"column":12},"end":{"line":1273,"column":12}},{"start":{"line":1273,"column":12},"end":{"line":1273,"column":12}}]},"88":{"line":1282,"type":"switch","locations":[{"start":{"line":1283,"column":12},"end":{"line":1285,"column":22}},{"start":{"line":1286,"column":12},"end":{"line":1288,"column":22}},{"start":{"line":1289,"column":12},"end":{"line":1296,"column":17}}]},"89":{"line":1287,"type":"binary-expr","locations":[{"start":{"line":1287,"column":38},"end":{"line":1287,"column":45}},{"start":{"line":1287,"column":49},"end":{"line":1287,"column":53}}]},"90":{"line":1290,"type":"if","locations":[{"start":{"line":1290,"column":16},"end":{"line":1290,"column":16}},{"start":{"line":1290,"column":16},"end":{"line":1290,"column":16}}]},"91":{"line":1290,"type":"binary-expr","locations":[{"start":{"line":1290,"column":20},"end":{"line":1290,"column":21}},{"start":{"line":1290,"column":25},"end":{"line":1290,"column":29}}]},"92":{"line":1291,"type":"binary-expr","locations":[{"start":{"line":1291,"column":27},"end":{"line":1291,"column":31}},{"start":{"line":1291,"column":35},"end":{"line":1291,"column":37}}]},"93":{"line":1292,"type":"cond-expr","locations":[{"start":{"line":1292,"column":30},"end":{"line":1292,"column":44}},{"start":{"line":1292,"column":47},"end":{"line":1292,"column":51}}]},"94":{"line":1299,"type":"if","locations":[{"start":{"line":1299,"column":8},"end":{"line":1299,"column":8}},{"start":{"line":1299,"column":8},"end":{"line":1299,"column":8}}]},"95":{"line":1316,"type":"if","locations":[{"start":{"line":1316,"column":8},"end":{"line":1316,"column":8}},{"start":{"line":1316,"column":8},"end":{"line":1316,"column":8}}]},"96":{"line":1317,"type":"cond-expr","locations":[{"start":{"line":1317,"column":33},"end":{"line":1317,"column":47}},{"start":{"line":1317,"column":50},"end":{"line":1317,"column":60}}]},"97":{"line":1321,"type":"if","locations":[{"start":{"line":1321,"column":8},"end":{"line":1321,"column":8}},{"start":{"line":1321,"column":8},"end":{"line":1321,"column":8}}]},"98":{"line":1321,"type":"binary-expr","locations":[{"start":{"line":1321,"column":12},"end":{"line":1321,"column":20}},{"start":{"line":1321,"column":24},"end":{"line":1321,"column":42}}]},"99":{"line":1345,"type":"if","locations":[{"start":{"line":1345,"column":8},"end":{"line":1345,"column":8}},{"start":{"line":1345,"column":8},"end":{"line":1345,"column":8}}]},"100":{"line":1346,"type":"binary-expr","locations":[{"start":{"line":1346,"column":21},"end":{"line":1346,"column":35}},{"start":{"line":1346,"column":40},"end":{"line":1346,"column":64}}]},"101":{"line":1385,"type":"binary-expr","locations":[{"start":{"line":1385,"column":15},"end":{"line":1385,"column":16}},{"start":{"line":1385,"column":20},"end":{"line":1385,"column":24}}]},"102":{"line":1386,"type":"if","locations":[{"start":{"line":1386,"column":8},"end":{"line":1386,"column":8}},{"start":{"line":1386,"column":8},"end":{"line":1386,"column":8}}]},"103":{"line":1388,"type":"binary-expr","locations":[{"start":{"line":1388,"column":29},"end":{"line":1388,"column":30}},{"start":{"line":1388,"column":34},"end":{"line":1388,"column":35}}]},"104":{"line":1400,"type":"if","locations":[{"start":{"line":1400,"column":8},"end":{"line":1400,"column":8}},{"start":{"line":1400,"column":8},"end":{"line":1400,"column":8}}]},"105":{"line":1401,"type":"if","locations":[{"start":{"line":1401,"column":12},"end":{"line":1401,"column":12}},{"start":{"line":1401,"column":12},"end":{"line":1401,"column":12}}]},"106":{"line":1471,"type":"if","locations":[{"start":{"line":1471,"column":8},"end":{"line":1471,"column":8}},{"start":{"line":1471,"column":8},"end":{"line":1471,"column":8}}]},"107":{"line":1471,"type":"binary-expr","locations":[{"start":{"line":1471,"column":12},"end":{"line":1471,"column":16}},{"start":{"line":1471,"column":20},"end":{"line":1471,"column":55}}]},"108":{"line":1489,"type":"if","locations":[{"start":{"line":1489,"column":8},"end":{"line":1489,"column":8}},{"start":{"line":1489,"column":8},"end":{"line":1489,"column":8}}]},"109":{"line":1495,"type":"if","locations":[{"start":{"line":1495,"column":8},"end":{"line":1495,"column":8}},{"start":{"line":1495,"column":8},"end":{"line":1495,"column":8}}]},"110":{"line":1502,"type":"if","locations":[{"start":{"line":1502,"column":8},"end":{"line":1502,"column":8}},{"start":{"line":1502,"column":8},"end":{"line":1502,"column":8}}]},"111":{"line":1505,"type":"if","locations":[{"start":{"line":1505,"column":12},"end":{"line":1505,"column":12}},{"start":{"line":1505,"column":12},"end":{"line":1505,"column":12}}]},"112":{"line":1511,"type":"cond-expr","locations":[{"start":{"line":1511,"column":40},"end":{"line":1511,"column":56}},{"start":{"line":1511,"column":59},"end":{"line":1511,"column":60}}]},"113":{"line":1519,"type":"if","locations":[{"start":{"line":1519,"column":8},"end":{"line":1519,"column":8}},{"start":{"line":1519,"column":8},"end":{"line":1519,"column":8}}]},"114":{"line":1533,"type":"if","locations":[{"start":{"line":1533,"column":8},"end":{"line":1533,"column":8}},{"start":{"line":1533,"column":8},"end":{"line":1533,"column":8}}]},"115":{"line":1536,"type":"if","locations":[{"start":{"line":1536,"column":12},"end":{"line":1536,"column":12}},{"start":{"line":1536,"column":12},"end":{"line":1536,"column":12}}]},"116":{"line":1540,"type":"if","locations":[{"start":{"line":1540,"column":12},"end":{"line":1540,"column":12}},{"start":{"line":1540,"column":12},"end":{"line":1540,"column":12}}]},"117":{"line":1565,"type":"if","locations":[{"start":{"line":1565,"column":12},"end":{"line":1565,"column":12}},{"start":{"line":1565,"column":12},"end":{"line":1565,"column":12}}]},"118":{"line":1587,"type":"if","locations":[{"start":{"line":1587,"column":12},"end":{"line":1587,"column":12}},{"start":{"line":1587,"column":12},"end":{"line":1587,"column":12}}]},"119":{"line":1611,"type":"binary-expr","locations":[{"start":{"line":1611,"column":32},"end":{"line":1611,"column":35}},{"start":{"line":1611,"column":39},"end":{"line":1611,"column":65}}]},"120":{"line":1657,"type":"if","locations":[{"start":{"line":1657,"column":8},"end":{"line":1657,"column":8}},{"start":{"line":1657,"column":8},"end":{"line":1657,"column":8}}]},"121":{"line":1659,"type":"if","locations":[{"start":{"line":1659,"column":12},"end":{"line":1659,"column":12}},{"start":{"line":1659,"column":12},"end":{"line":1659,"column":12}}]},"122":{"line":1668,"type":"if","locations":[{"start":{"line":1668,"column":12},"end":{"line":1668,"column":12}},{"start":{"line":1668,"column":12},"end":{"line":1668,"column":12}}]},"123":{"line":1677,"type":"if","locations":[{"start":{"line":1677,"column":16},"end":{"line":1677,"column":16}},{"start":{"line":1677,"column":16},"end":{"line":1677,"column":16}}]},"124":{"line":1678,"type":"binary-expr","locations":[{"start":{"line":1678,"column":24},"end":{"line":1678,"column":28}},{"start":{"line":1678,"column":33},"end":{"line":1678,"column":58}}]},"125":{"line":1678,"type":"cond-expr","locations":[{"start":{"line":1678,"column":53},"end":{"line":1678,"column":54}},{"start":{"line":1678,"column":57},"end":{"line":1678,"column":58}}]},"126":{"line":1679,"type":"binary-expr","locations":[{"start":{"line":1679,"column":24},"end":{"line":1679,"column":33}},{"start":{"line":1679,"column":37},"end":{"line":1679,"column":38}}]},"127":{"line":1682,"type":"cond-expr","locations":[{"start":{"line":1682,"column":35},"end":{"line":1682,"column":47}},{"start":{"line":1682,"column":50},"end":{"line":1682,"column":52}}]},"128":{"line":1684,"type":"cond-expr","locations":[{"start":{"line":1684,"column":42},"end":{"line":1684,"column":43}},{"start":{"line":1684,"column":46},"end":{"line":1684,"column":47}}]},"129":{"line":1692,"type":"cond-expr","locations":[{"start":{"line":1692,"column":36},"end":{"line":1692,"column":40}},{"start":{"line":1692,"column":43},"end":{"line":1692,"column":65}}]},"130":{"line":1700,"type":"if","locations":[{"start":{"line":1700,"column":8},"end":{"line":1700,"column":8}},{"start":{"line":1700,"column":8},"end":{"line":1700,"column":8}}]},"131":{"line":1700,"type":"binary-expr","locations":[{"start":{"line":1700,"column":12},"end":{"line":1700,"column":16}},{"start":{"line":1700,"column":20},"end":{"line":1700,"column":44}},{"start":{"line":1700,"column":49},"end":{"line":1700,"column":77}}]},"132":{"line":1708,"type":"if","locations":[{"start":{"line":1708,"column":8},"end":{"line":1708,"column":8}},{"start":{"line":1708,"column":8},"end":{"line":1708,"column":8}}]},"133":{"line":1714,"type":"if","locations":[{"start":{"line":1714,"column":12},"end":{"line":1714,"column":12}},{"start":{"line":1714,"column":12},"end":{"line":1714,"column":12}}]},"134":{"line":1717,"type":"if","locations":[{"start":{"line":1717,"column":16},"end":{"line":1717,"column":16}},{"start":{"line":1717,"column":16},"end":{"line":1717,"column":16}}]},"135":{"line":1719,"type":"if","locations":[{"start":{"line":1719,"column":23},"end":{"line":1719,"column":23}},{"start":{"line":1719,"column":23},"end":{"line":1719,"column":23}}]},"136":{"line":1726,"type":"if","locations":[{"start":{"line":1726,"column":16},"end":{"line":1726,"column":16}},{"start":{"line":1726,"column":16},"end":{"line":1726,"column":16}}]},"137":{"line":1732,"type":"if","locations":[{"start":{"line":1732,"column":12},"end":{"line":1732,"column":12}},{"start":{"line":1732,"column":12},"end":{"line":1732,"column":12}}]},"138":{"line":1734,"type":"if","locations":[{"start":{"line":1734,"column":19},"end":{"line":1734,"column":19}},{"start":{"line":1734,"column":19},"end":{"line":1734,"column":19}}]},"139":{"line":1734,"type":"binary-expr","locations":[{"start":{"line":1734,"column":24},"end":{"line":1734,"column":29}},{"start":{"line":1734,"column":34},"end":{"line":1734,"column":42}}]},"140":{"line":1740,"type":"if","locations":[{"start":{"line":1740,"column":8},"end":{"line":1740,"column":8}},{"start":{"line":1740,"column":8},"end":{"line":1740,"column":8}}]},"141":{"line":1741,"type":"binary-expr","locations":[{"start":{"line":1741,"column":17},"end":{"line":1741,"column":36}},{"start":{"line":1741,"column":40},"end":{"line":1741,"column":58}}]},"142":{"line":1742,"type":"cond-expr","locations":[{"start":{"line":1742,"column":66},"end":{"line":1742,"column":96}},{"start":{"line":1742,"column":99},"end":{"line":1742,"column":103}}]},"143":{"line":1742,"type":"cond-expr","locations":[{"start":{"line":1742,"column":115},"end":{"line":1742,"column":122}},{"start":{"line":1742,"column":125},"end":{"line":1742,"column":129}}]},"144":{"line":1745,"type":"if","locations":[{"start":{"line":1745,"column":12},"end":{"line":1745,"column":12}},{"start":{"line":1745,"column":12},"end":{"line":1745,"column":12}}]},"145":{"line":1750,"type":"if","locations":[{"start":{"line":1750,"column":8},"end":{"line":1750,"column":8}},{"start":{"line":1750,"column":8},"end":{"line":1750,"column":8}}]},"146":{"line":1751,"type":"binary-expr","locations":[{"start":{"line":1751,"column":36},"end":{"line":1751,"column":57}},{"start":{"line":1751,"column":61},"end":{"line":1751,"column":63}}]},"147":{"line":1752,"type":"binary-expr","locations":[{"start":{"line":1752,"column":42},"end":{"line":1752,"column":69}},{"start":{"line":1752,"column":73},"end":{"line":1752,"column":75}}]},"148":{"line":1756,"type":"cond-expr","locations":[{"start":{"line":1756,"column":32},"end":{"line":1756,"column":36}},{"start":{"line":1756,"column":39},"end":{"line":1756,"column":45}}]},"149":{"line":1790,"type":"binary-expr","locations":[{"start":{"line":1790,"column":21},"end":{"line":1790,"column":25}},{"start":{"line":1790,"column":30},"end":{"line":1790,"column":54}}]},"150":{"line":1793,"type":"if","locations":[{"start":{"line":1793,"column":8},"end":{"line":1793,"column":8}},{"start":{"line":1793,"column":8},"end":{"line":1793,"column":8}}]},"151":{"line":1793,"type":"binary-expr","locations":[{"start":{"line":1793,"column":12},"end":{"line":1793,"column":17}},{"start":{"line":1793,"column":22},"end":{"line":1793,"column":32}}]},"152":{"line":1795,"type":"if","locations":[{"start":{"line":1795,"column":16},"end":{"line":1795,"column":16}},{"start":{"line":1795,"column":16},"end":{"line":1795,"column":16}}]},"153":{"line":1799,"type":"if","locations":[{"start":{"line":1799,"column":12},"end":{"line":1799,"column":12}},{"start":{"line":1799,"column":12},"end":{"line":1799,"column":12}}]},"154":{"line":1807,"type":"cond-expr","locations":[{"start":{"line":1807,"column":44},"end":{"line":1807,"column":52}},{"start":{"line":1807,"column":55},"end":{"line":1807,"column":59}}]},"155":{"line":1808,"type":"cond-expr","locations":[{"start":{"line":1808,"column":30},"end":{"line":1808,"column":38}},{"start":{"line":1808,"column":41},"end":{"line":1808,"column":45}}]},"156":{"line":1814,"type":"if","locations":[{"start":{"line":1814,"column":12},"end":{"line":1814,"column":12}},{"start":{"line":1814,"column":12},"end":{"line":1814,"column":12}}]},"157":{"line":1817,"type":"if","locations":[{"start":{"line":1817,"column":20},"end":{"line":1817,"column":20}},{"start":{"line":1817,"column":20},"end":{"line":1817,"column":20}}]},"158":{"line":1817,"type":"binary-expr","locations":[{"start":{"line":1817,"column":24},"end":{"line":1817,"column":40}},{"start":{"line":1817,"column":44},"end":{"line":1817,"column":58}}]},"159":{"line":1824,"type":"if","locations":[{"start":{"line":1824,"column":8},"end":{"line":1824,"column":8}},{"start":{"line":1824,"column":8},"end":{"line":1824,"column":8}}]},"160":{"line":1828,"type":"cond-expr","locations":[{"start":{"line":1828,"column":36},"end":{"line":1828,"column":59}},{"start":{"line":1828,"column":62},"end":{"line":1828,"column":66}}]},"161":{"line":1830,"type":"if","locations":[{"start":{"line":1830,"column":12},"end":{"line":1830,"column":12}},{"start":{"line":1830,"column":12},"end":{"line":1830,"column":12}}]},"162":{"line":1831,"type":"if","locations":[{"start":{"line":1831,"column":16},"end":{"line":1831,"column":16}},{"start":{"line":1831,"column":16},"end":{"line":1831,"column":16}}]},"163":{"line":1835,"type":"if","locations":[{"start":{"line":1835,"column":24},"end":{"line":1835,"column":24}},{"start":{"line":1835,"column":24},"end":{"line":1835,"column":24}}]},"164":{"line":1845,"type":"if","locations":[{"start":{"line":1845,"column":15},"end":{"line":1845,"column":15}},{"start":{"line":1845,"column":15},"end":{"line":1845,"column":15}}]},"165":{"line":1845,"type":"binary-expr","locations":[{"start":{"line":1845,"column":19},"end":{"line":1845,"column":35}},{"start":{"line":1845,"column":39},"end":{"line":1845,"column":50}}]},"166":{"line":1849,"type":"if","locations":[{"start":{"line":1849,"column":15},"end":{"line":1849,"column":15}},{"start":{"line":1849,"column":15},"end":{"line":1849,"column":15}}]},"167":{"line":1849,"type":"binary-expr","locations":[{"start":{"line":1849,"column":19},"end":{"line":1849,"column":25}},{"start":{"line":1849,"column":31},"end":{"line":1849,"column":41}},{"start":{"line":1849,"column":47},"end":{"line":1849,"column":75}}]},"168":{"line":1859,"type":"if","locations":[{"start":{"line":1859,"column":8},"end":{"line":1859,"column":8}},{"start":{"line":1859,"column":8},"end":{"line":1859,"column":8}}]},"169":{"line":1862,"type":"if","locations":[{"start":{"line":1862,"column":12},"end":{"line":1862,"column":12}},{"start":{"line":1862,"column":12},"end":{"line":1862,"column":12}}]},"170":{"line":1862,"type":"binary-expr","locations":[{"start":{"line":1862,"column":16},"end":{"line":1862,"column":21}},{"start":{"line":1862,"column":25},"end":{"line":1862,"column":37}}]},"171":{"line":1866,"type":"if","locations":[{"start":{"line":1866,"column":19},"end":{"line":1866,"column":19}},{"start":{"line":1866,"column":19},"end":{"line":1866,"column":19}}]},"172":{"line":1866,"type":"binary-expr","locations":[{"start":{"line":1866,"column":23},"end":{"line":1866,"column":28}},{"start":{"line":1866,"column":33},"end":{"line":1866,"column":39}},{"start":{"line":1866,"column":43},"end":{"line":1866,"column":47}},{"start":{"line":1866,"column":52},"end":{"line":1866,"column":75}}]},"173":{"line":1875,"type":"if","locations":[{"start":{"line":1875,"column":8},"end":{"line":1875,"column":8}},{"start":{"line":1875,"column":8},"end":{"line":1875,"column":8}}]},"174":{"line":1987,"type":"if","locations":[{"start":{"line":1987,"column":8},"end":{"line":1987,"column":8}},{"start":{"line":1987,"column":8},"end":{"line":1987,"column":8}}]},"175":{"line":1988,"type":"if","locations":[{"start":{"line":1988,"column":12},"end":{"line":1988,"column":12}},{"start":{"line":1988,"column":12},"end":{"line":1988,"column":12}}]},"176":{"line":1996,"type":"if","locations":[{"start":{"line":1996,"column":16},"end":{"line":1996,"column":16}},{"start":{"line":1996,"column":16},"end":{"line":1996,"column":16}}]},"177":{"line":1999,"type":"binary-expr","locations":[{"start":{"line":1999,"column":52},"end":{"line":1999,"column":53}},{"start":{"line":1999,"column":57},"end":{"line":1999,"column":61}}]},"178":{"line":2024,"type":"if","locations":[{"start":{"line":2024,"column":8},"end":{"line":2024,"column":8}},{"start":{"line":2024,"column":8},"end":{"line":2024,"column":8}}]},"179":{"line":2056,"type":"if","locations":[{"start":{"line":2056,"column":8},"end":{"line":2056,"column":8}},{"start":{"line":2056,"column":8},"end":{"line":2056,"column":8}}]},"180":{"line":2056,"type":"binary-expr","locations":[{"start":{"line":2056,"column":13},"end":{"line":2056,"column":31}},{"start":{"line":2056,"column":35},"end":{"line":2056,"column":38}},{"start":{"line":2056,"column":44},"end":{"line":2056,"column":46}},{"start":{"line":2056,"column":50},"end":{"line":2056,"column":62}}]},"181":{"line":2062,"type":"if","locations":[{"start":{"line":2062,"column":8},"end":{"line":2062,"column":8}},{"start":{"line":2062,"column":8},"end":{"line":2062,"column":8}}]},"182":{"line":2066,"type":"if","locations":[{"start":{"line":2066,"column":12},"end":{"line":2066,"column":12}},{"start":{"line":2066,"column":12},"end":{"line":2066,"column":12}}]},"183":{"line":2072,"type":"if","locations":[{"start":{"line":2072,"column":8},"end":{"line":2072,"column":8}},{"start":{"line":2072,"column":8},"end":{"line":2072,"column":8}}]},"184":{"line":2099,"type":"if","locations":[{"start":{"line":2099,"column":8},"end":{"line":2099,"column":8}},{"start":{"line":2099,"column":8},"end":{"line":2099,"column":8}}]},"185":{"line":2100,"type":"if","locations":[{"start":{"line":2100,"column":12},"end":{"line":2100,"column":12}},{"start":{"line":2100,"column":12},"end":{"line":2100,"column":12}}]},"186":{"line":2108,"type":"if","locations":[{"start":{"line":2108,"column":12},"end":{"line":2108,"column":12}},{"start":{"line":2108,"column":12},"end":{"line":2108,"column":12}}]},"187":{"line":2108,"type":"binary-expr","locations":[{"start":{"line":2108,"column":17},"end":{"line":2108,"column":46}},{"start":{"line":2108,"column":51},"end":{"line":2108,"column":54}},{"start":{"line":2108,"column":58},"end":{"line":2108,"column":70}},{"start":{"line":2108,"column":77},"end":{"line":2108,"column":79}},{"start":{"line":2108,"column":83},"end":{"line":2108,"column":95}}]},"188":{"line":2156,"type":"if","locations":[{"start":{"line":2156,"column":8},"end":{"line":2156,"column":8}},{"start":{"line":2156,"column":8},"end":{"line":2156,"column":8}}]},"189":{"line":2156,"type":"binary-expr","locations":[{"start":{"line":2156,"column":12},"end":{"line":2156,"column":24}},{"start":{"line":2156,"column":28},"end":{"line":2156,"column":41}}]},"190":{"line":2160,"type":"if","locations":[{"start":{"line":2160,"column":12},"end":{"line":2160,"column":12}},{"start":{"line":2160,"column":12},"end":{"line":2160,"column":12}}]},"191":{"line":2167,"type":"cond-expr","locations":[{"start":{"line":2167,"column":65},"end":{"line":2167,"column":66}},{"start":{"line":2167,"column":69},"end":{"line":2167,"column":70}}]},"192":{"line":2170,"type":"if","locations":[{"start":{"line":2170,"column":8},"end":{"line":2170,"column":8}},{"start":{"line":2170,"column":8},"end":{"line":2170,"column":8}}]},"193":{"line":2171,"type":"binary-expr","locations":[{"start":{"line":2171,"column":17},"end":{"line":2171,"column":21}},{"start":{"line":2171,"column":25},"end":{"line":2171,"column":34}}]},"194":{"line":2174,"type":"if","locations":[{"start":{"line":2174,"column":8},"end":{"line":2174,"column":8}},{"start":{"line":2174,"column":8},"end":{"line":2174,"column":8}}]},"195":{"line":2180,"type":"if","locations":[{"start":{"line":2180,"column":8},"end":{"line":2180,"column":8}},{"start":{"line":2180,"column":8},"end":{"line":2180,"column":8}}]},"196":{"line":2183,"type":"if","locations":[{"start":{"line":2183,"column":12},"end":{"line":2183,"column":12}},{"start":{"line":2183,"column":12},"end":{"line":2183,"column":12}}]},"197":{"line":2183,"type":"binary-expr","locations":[{"start":{"line":2183,"column":16},"end":{"line":2183,"column":19}},{"start":{"line":2183,"column":23},"end":{"line":2183,"column":26}}]},"198":{"line":2189,"type":"if","locations":[{"start":{"line":2189,"column":8},"end":{"line":2189,"column":8}},{"start":{"line":2189,"column":8},"end":{"line":2189,"column":8}}]},"199":{"line":2189,"type":"binary-expr","locations":[{"start":{"line":2189,"column":13},"end":{"line":2189,"column":31}},{"start":{"line":2189,"column":36},"end":{"line":2189,"column":39}},{"start":{"line":2189,"column":43},"end":{"line":2189,"column":55}},{"start":{"line":2189,"column":62},"end":{"line":2189,"column":64}},{"start":{"line":2189,"column":68},"end":{"line":2189,"column":80}}]},"200":{"line":2190,"type":"binary-expr","locations":[{"start":{"line":2190,"column":35},"end":{"line":2190,"column":37}},{"start":{"line":2190,"column":41},"end":{"line":2190,"column":42}}]},"201":{"line":2196,"type":"if","locations":[{"start":{"line":2196,"column":8},"end":{"line":2196,"column":8}},{"start":{"line":2196,"column":8},"end":{"line":2196,"column":8}}]},"202":{"line":2197,"type":"if","locations":[{"start":{"line":2197,"column":12},"end":{"line":2197,"column":12}},{"start":{"line":2197,"column":12},"end":{"line":2197,"column":12}}]},"203":{"line":2205,"type":"if","locations":[{"start":{"line":2205,"column":12},"end":{"line":2205,"column":12}},{"start":{"line":2205,"column":12},"end":{"line":2205,"column":12}}]},"204":{"line":2212,"type":"cond-expr","locations":[{"start":{"line":2212,"column":32},"end":{"line":2212,"column":36}},{"start":{"line":2212,"column":39},"end":{"line":2212,"column":42}}]},"205":{"line":2219,"type":"if","locations":[{"start":{"line":2219,"column":8},"end":{"line":2219,"column":8}},{"start":{"line":2219,"column":8},"end":{"line":2219,"column":8}}]},"206":{"line":2222,"type":"if","locations":[{"start":{"line":2222,"column":12},"end":{"line":2222,"column":12}},{"start":{"line":2222,"column":12},"end":{"line":2222,"column":12}}]},"207":{"line":2243,"type":"if","locations":[{"start":{"line":2243,"column":8},"end":{"line":2243,"column":8}},{"start":{"line":2243,"column":8},"end":{"line":2243,"column":8}}]},"208":{"line":2245,"type":"cond-expr","locations":[{"start":{"line":2245,"column":27},"end":{"line":2245,"column":46}},{"start":{"line":2245,"column":49},"end":{"line":2245,"column":53}}]},"209":{"line":2248,"type":"binary-expr","locations":[{"start":{"line":2248,"column":15},"end":{"line":2248,"column":22}},{"start":{"line":2248,"column":26},"end":{"line":2248,"column":30}}]},"210":{"line":2269,"type":"switch","locations":[{"start":{"line":2270,"column":12},"end":{"line":2271,"column":57}},{"start":{"line":2272,"column":12},"end":{"line":2272,"column":25}},{"start":{"line":2277,"column":12},"end":{"line":2279,"column":22}},{"start":{"line":2280,"column":12},"end":{"line":2281,"column":43}}]},"211":{"line":2315,"type":"binary-expr","locations":[{"start":{"line":2315,"column":23},"end":{"line":2315,"column":43}},{"start":{"line":2315,"column":47},"end":{"line":2315,"column":55}}]}},"code":["(function () { YUI.add('event-custom-base', function (Y, NAME) {","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," */","","Y.Env.evt = {"," handles: {},"," plugins: {}","};","","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","/**"," * Allows for the insertion of methods that are executed before or after"," * a specified method"," * @class Do"," * @static"," */","","var DO_BEFORE = 0,"," DO_AFTER = 1,","","DO = {",""," /**"," * Cache of objects touched by the utility"," * @property objs"," * @static"," * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object"," * replaces the role of this property, but is considered to be private, and"," * is only mentioned to provide a migration path."," *"," * If you have a use case which warrants migration to the _yuiaop property,"," * please file a ticket to let us know what it's used for and we can see if"," * we need to expose hooks for that functionality more formally."," */"," objs: null,",""," /**"," * <p>Execute the supplied method before the specified function. Wrapping"," * function may optionally return an instance of the following classes to"," * further alter runtime behavior:</p>"," * <dl>"," * <dt></code>Y.Do.Halt(message, returnValue)</code></dt>"," * <dd>Immediatly stop execution and return"," * <code>returnValue</code>. No other wrapping functions will be"," * executed.</dd>"," * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt>"," * <dd>Replace the arguments that the original function will be"," * called with.</dd>"," * <dt></code>Y.Do.Prevent(message)</code></dt>"," * <dd>Don't execute the wrapped function. Other before phase"," * wrappers will be executed.</dd>"," * </dl>"," *"," * @method before"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @param arg* {mixed} 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {string} handle for the subscription"," * @static"," */"," before: function(fn, obj, sFn, c) {"," var f = fn, a;"," if (c) {"," a = [fn, c].concat(Y.Array(arguments, 4, true));"," f = Y.rbind.apply(Y, a);"," }",""," return this._inject(DO_BEFORE, f, obj, sFn);"," },",""," /**"," * <p>Execute the supplied method after the specified function. Wrapping"," * function may optionally return an instance of the following classes to"," * further alter runtime behavior:</p>"," * <dl>"," * <dt></code>Y.Do.Halt(message, returnValue)</code></dt>"," * <dd>Immediatly stop execution and return"," * <code>returnValue</code>. No other wrapping functions will be"," * executed.</dd>"," * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt>"," * <dd>Return <code>returnValue</code> instead of the wrapped"," * method's original return value. This can be further altered by"," * other after phase wrappers.</dd>"," * </dl>"," *"," * <p>The static properties <code>Y.Do.originalRetVal</code> and"," * <code>Y.Do.currentRetVal</code> will be populated for reference.</p>"," *"," * @method after"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @param arg* {mixed} 0..n additional arguments to supply to the subscriber"," * @return {string} handle for the subscription"," * @static"," */"," after: function(fn, obj, sFn, c) {"," var f = fn, a;"," if (c) {"," a = [fn, c].concat(Y.Array(arguments, 4, true));"," f = Y.rbind.apply(Y, a);"," }",""," return this._inject(DO_AFTER, f, obj, sFn);"," },",""," /**"," * Execute the supplied method before or after the specified function."," * Used by <code>before</code> and <code>after</code>."," *"," * @method _inject"," * @param when {string} before or after"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @return {string} handle for the subscription"," * @private"," * @static"," */"," _inject: function(when, fn, obj, sFn) {"," // object id"," var id = Y.stamp(obj), o, sid;",""," if (!obj._yuiaop) {"," // create a map entry for the obj if it doesn't exist, to hold overridden methods"," obj._yuiaop = {};"," }",""," o = obj._yuiaop;",""," if (!o[sFn]) {"," // create a map entry for the method if it doesn't exist"," o[sFn] = new Y.Do.Method(obj, sFn);",""," // re-route the method to our wrapper"," obj[sFn] = function() {"," return o[sFn].exec.apply(o[sFn], arguments);"," };"," }",""," // subscriber id"," sid = id + Y.stamp(fn) + sFn;",""," // register the callback"," o[sFn].register(sid, fn, when);",""," return new Y.EventHandle(o[sFn], sid);"," },",""," /**"," * Detach a before or after subscription."," *"," * @method detach"," * @param handle {string} the subscription handle"," * @static"," */"," detach: function(handle) {"," if (handle.detach) {"," handle.detach();"," }"," }","};","","Y.Do = DO;","","//////////////////////////////////////////////////////////////////////////","","/**"," * Contains the return value from the wrapped method, accessible"," * by 'after' event listeners."," *"," * @property originalRetVal"," * @static"," * @since 3.2.0"," */","","/**"," * Contains the current state of the return value, consumable by"," * 'after' event listeners, and updated if an after subscriber"," * changes the return value generated by the wrapped function."," *"," * @property currentRetVal"," * @static"," * @since 3.2.0"," */","","//////////////////////////////////////////////////////////////////////////","","/**"," * Wrapper for a displaced method with aop enabled"," * @class Do.Method"," * @constructor"," * @param obj The object to operate on"," * @param sFn The name of the method to displace"," */","DO.Method = function(obj, sFn) {"," this.obj = obj;"," this.methodName = sFn;"," this.method = obj[sFn];"," this.before = {};"," this.after = {};","};","","/**"," * Register a aop subscriber"," * @method register"," * @param sid {string} the subscriber id"," * @param fn {Function} the function to execute"," * @param when {string} when to execute the function"," */","DO.Method.prototype.register = function (sid, fn, when) {"," if (when) {"," this.after[sid] = fn;"," } else {"," this.before[sid] = fn;"," }","};","","/**"," * Unregister a aop subscriber"," * @method delete"," * @param sid {string} the subscriber id"," * @param fn {Function} the function to execute"," * @param when {string} when to execute the function"," */","DO.Method.prototype._delete = function (sid) {"," delete this.before[sid];"," delete this.after[sid];","};","","/**"," * <p>Execute the wrapped method. All arguments are passed into the wrapping"," * functions. If any of the before wrappers return an instance of"," * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped"," * function nor any after phase subscribers will be executed.</p>"," *"," * <p>The return value will be the return value of the wrapped function or one"," * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or"," * <code>Y.Do.AlterReturn</code>."," *"," * @method exec"," * @param arg* {any} Arguments are passed to the wrapping and wrapped functions"," * @return {any} Return value of wrapped function unless overwritten (see above)"," */","DO.Method.prototype.exec = function () {",""," var args = Y.Array(arguments, 0, true),"," i, ret, newRet,"," bf = this.before,"," af = this.after,"," prevented = false;",""," // execute before"," for (i in bf) {"," if (bf.hasOwnProperty(i)) {"," ret = bf[i].apply(this.obj, args);"," if (ret) {"," switch (ret.constructor) {"," case DO.Halt:"," return ret.retVal;"," case DO.AlterArgs:"," args = ret.newArgs;"," break;"," case DO.Prevent:"," prevented = true;"," break;"," default:"," }"," }"," }"," }",""," // execute method"," if (!prevented) {"," ret = this.method.apply(this.obj, args);"," }",""," DO.originalRetVal = ret;"," DO.currentRetVal = ret;",""," // execute after methods."," for (i in af) {"," if (af.hasOwnProperty(i)) {"," newRet = af[i].apply(this.obj, args);"," // Stop processing if a Halt object is returned"," if (newRet && newRet.constructor === DO.Halt) {"," return newRet.retVal;"," // Check for a new return value"," } else if (newRet && newRet.constructor === DO.AlterReturn) {"," ret = newRet.newRetVal;"," // Update the static retval state"," DO.currentRetVal = ret;"," }"," }"," }",""," return ret;","};","","//////////////////////////////////////////////////////////////////////////","","/**"," * Return an AlterArgs object when you want to change the arguments that"," * were passed into the function. Useful for Do.before subscribers. An"," * example would be a service that scrubs out illegal characters prior to"," * executing the core business logic."," * @class Do.AlterArgs"," * @constructor"," * @param msg {String} (optional) Explanation of the altered return value"," * @param newArgs {Array} Call parameters to be used for the original method"," * instead of the arguments originally passed in."," */","DO.AlterArgs = function(msg, newArgs) {"," this.msg = msg;"," this.newArgs = newArgs;","};","","/**"," * Return an AlterReturn object when you want to change the result returned"," * from the core method to the caller. Useful for Do.after subscribers."," * @class Do.AlterReturn"," * @constructor"," * @param msg {String} (optional) Explanation of the altered return value"," * @param newRetVal {any} Return value passed to code that invoked the wrapped"," * function."," */","DO.AlterReturn = function(msg, newRetVal) {"," this.msg = msg;"," this.newRetVal = newRetVal;","};","","/**"," * Return a Halt object when you want to terminate the execution"," * of all subsequent subscribers as well as the wrapped method"," * if it has not exectued yet. Useful for Do.before subscribers."," * @class Do.Halt"," * @constructor"," * @param msg {String} (optional) Explanation of why the termination was done"," * @param retVal {any} Return value passed to code that invoked the wrapped"," * function."," */","DO.Halt = function(msg, retVal) {"," this.msg = msg;"," this.retVal = retVal;","};","","/**"," * Return a Prevent object when you want to prevent the wrapped function"," * from executing, but want the remaining listeners to execute. Useful"," * for Do.before subscribers."," * @class Do.Prevent"," * @constructor"," * @param msg {String} (optional) Explanation of why the termination was done"," */","DO.Prevent = function(msg) {"," this.msg = msg;","};","","/**"," * Return an Error object when you want to terminate the execution"," * of all subsequent method calls."," * @class Do.Error"," * @constructor"," * @param msg {String} (optional) Explanation of the altered return value"," * @param retVal {any} Return value passed to code that invoked the wrapped"," * function."," * @deprecated use Y.Do.Halt or Y.Do.Prevent"," */","DO.Error = DO.Halt;","","","//////////////////////////////////////////////////////////////////////////","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","","// var onsubscribeType = \"_event:onsub\",","var YArray = Y.Array,",""," AFTER = 'after',"," CONFIGS = ["," 'broadcast',"," 'monitored',"," 'bubbles',"," 'context',"," 'contextFn',"," 'currentTarget',"," 'defaultFn',"," 'defaultTargetOnly',"," 'details',"," 'emitFacade',"," 'fireOnce',"," 'async',"," 'host',"," 'preventable',"," 'preventedFn',"," 'queuable',"," 'silent',"," 'stoppedFn',"," 'target',"," 'type'"," ],",""," CONFIGS_HASH = YArray.hash(CONFIGS),",""," nativeSlice = Array.prototype.slice,",""," YUI3_SIGNATURE = 9,"," YUI_LOG = 'yui:log',",""," mixConfigs = function(r, s, ov) {"," var p;",""," for (p in s) {"," if (CONFIGS_HASH[p] && (ov || !(p in r))) {"," r[p] = s[p];"," }"," }",""," return r;"," };","","/**"," * The CustomEvent class lets you define events for your application"," * that can be subscribed to by one or more independent component."," *"," * @param {String} type The type of event, which is passed to the callback"," * when the event fires."," * @param {object} defaults configuration object."," * @class CustomEvent"," * @constructor"," */",""," /**"," * The type of event, returned to subscribers when the event fires"," * @property type"," * @type string"," */","","/**"," * By default all custom events are logged in the debug build, set silent"," * to true to disable debug outpu for this event."," * @property silent"," * @type boolean"," */","","Y.CustomEvent = function(type, defaults) {",""," this._kds = Y.CustomEvent.keepDeprecatedSubs;",""," this.id = Y.guid();",""," this.type = type;"," this.silent = this.logSystem = (type === YUI_LOG);",""," if (this._kds) {"," /**"," * The subscribers to this event"," * @property subscribers"," * @type Subscriber {}"," * @deprecated"," */",""," /**"," * 'After' subscribers"," * @property afters"," * @type Subscriber {}"," * @deprecated"," */"," this.subscribers = {};"," this.afters = {};"," }",""," if (defaults) {"," mixConfigs(this, defaults, true);"," }","};","","/**"," * Static flag to enable population of the <a href=\"#property_subscribers\">`subscribers`</a>"," * and <a href=\"#property_subscribers\">`afters`</a> properties held on a `CustomEvent` instance."," *"," * These properties were changed to private properties (`_subscribers` and `_afters`), and"," * converted from objects to arrays for performance reasons."," *"," * Setting this property to true will populate the deprecated `subscribers` and `afters`"," * properties for people who may be using them (which is expected to be rare). There will"," * be a performance hit, compared to the new array based implementation."," *"," * If you are using these deprecated properties for a use case which the public API"," * does not support, please file an enhancement request, and we can provide an alternate"," * public implementation which doesn't have the performance cost required to maintiain the"," * properties as objects."," *"," * @property keepDeprecatedSubs"," * @static"," * @for CustomEvent"," * @type boolean"," * @default false"," * @deprecated"," */","Y.CustomEvent.keepDeprecatedSubs = false;","","Y.CustomEvent.mixConfigs = mixConfigs;","","Y.CustomEvent.prototype = {",""," constructor: Y.CustomEvent,",""," /**"," * Monitor when an event is attached or detached."," *"," * @property monitored"," * @type boolean"," */",""," /**"," * If 0, this event does not broadcast. If 1, the YUI instance is notified"," * every time this event fires. If 2, the YUI instance and the YUI global"," * (if event is enabled on the global) are notified every time this event"," * fires."," * @property broadcast"," * @type int"," */",""," /**"," * Specifies whether this event should be queued when the host is actively"," * processing an event. This will effect exectution order of the callbacks"," * for the various events."," * @property queuable"," * @type boolean"," * @default false"," */",""," /**"," * This event has fired if true"," *"," * @property fired"," * @type boolean"," * @default false;"," */",""," /**"," * An array containing the arguments the custom event"," * was last fired with."," * @property firedWith"," * @type Array"," */",""," /**"," * This event should only fire one time if true, and if"," * it has fired, any new subscribers should be notified"," * immediately."," *"," * @property fireOnce"," * @type boolean"," * @default false;"," */",""," /**"," * fireOnce listeners will fire syncronously unless async"," * is set to true"," * @property async"," * @type boolean"," * @default false"," */",""," /**"," * Flag for stopPropagation that is modified during fire()"," * 1 means to stop propagation to bubble targets. 2 means"," * to also stop additional subscribers on this target."," * @property stopped"," * @type int"," */",""," /**"," * Flag for preventDefault that is modified during fire()."," * if it is not 0, the default behavior for this event"," * @property prevented"," * @type int"," */",""," /**"," * Specifies the host for this custom event. This is used"," * to enable event bubbling"," * @property host"," * @type EventTarget"," */",""," /**"," * The default function to execute after event listeners"," * have fire, but only if the default action was not"," * prevented."," * @property defaultFn"," * @type Function"," */",""," /**"," * The function to execute if a subscriber calls"," * stopPropagation or stopImmediatePropagation"," * @property stoppedFn"," * @type Function"," */",""," /**"," * The function to execute if a subscriber calls"," * preventDefault"," * @property preventedFn"," * @type Function"," */",""," /**"," * The subscribers to this event"," * @property _subscribers"," * @type Subscriber []"," * @private"," */",""," /**"," * 'After' subscribers"," * @property _afters"," * @type Subscriber []"," * @private"," */",""," /**"," * If set to true, the custom event will deliver an EventFacade object"," * that is similar to a DOM event object."," * @property emitFacade"," * @type boolean"," * @default false"," */",""," /**"," * Supports multiple options for listener signatures in order to"," * port YUI 2 apps."," * @property signature"," * @type int"," * @default 9"," */"," signature : YUI3_SIGNATURE,",""," /**"," * The context the the event will fire from by default. Defaults to the YUI"," * instance."," * @property context"," * @type object"," */"," context : Y,",""," /**"," * Specifies whether or not this event's default function"," * can be cancelled by a subscriber by executing preventDefault()"," * on the event facade"," * @property preventable"," * @type boolean"," * @default true"," */"," preventable : true,",""," /**"," * Specifies whether or not a subscriber can stop the event propagation"," * via stopPropagation(), stopImmediatePropagation(), or halt()"," *"," * Events can only bubble if emitFacade is true."," *"," * @property bubbles"," * @type boolean"," * @default true"," */"," bubbles : true,",""," /**"," * Returns the number of subscribers for this event as the sum of the on()"," * subscribers and after() subscribers."," *"," * @method hasSubs"," * @return Number"," */"," hasSubs: function(when) {"," var s = 0,"," a = 0,"," subs = this._subscribers,"," afters = this._afters,"," sib = this.sibling;",""," if (subs) {"," s = subs.length;"," }",""," if (afters) {"," a = afters.length;"," }",""," if (sib) {"," subs = sib._subscribers;"," afters = sib._afters;",""," if (subs) {"," s += subs.length;"," }",""," if (afters) {"," a += afters.length;"," }"," }",""," if (when) {"," return (when === 'after') ? a : s;"," }",""," return (s + a);"," },",""," /**"," * Monitor the event state for the subscribed event. The first parameter"," * is what should be monitored, the rest are the normal parameters when"," * subscribing to an event."," * @method monitor"," * @param what {string} what to monitor ('detach', 'attach', 'publish')."," * @return {EventHandle} return value from the monitor event subscription."," */"," monitor: function(what) {"," this.monitored = true;"," var type = this.id + '|' + this.type + '_' + what,"," args = nativeSlice.call(arguments, 0);"," args[0] = type;"," return this.host.on.apply(this.host, args);"," },",""," /**"," * Get all of the subscribers to this event and any sibling event"," * @method getSubs"," * @return {Array} first item is the on subscribers, second the after."," */"," getSubs: function() {",""," var sibling = this.sibling,"," subs = this._subscribers,"," afters = this._afters,"," siblingSubs,"," siblingAfters;",""," if (sibling) {"," siblingSubs = sibling._subscribers;"," siblingAfters = sibling._afters;"," }",""," if (siblingSubs) {"," if (subs) {"," subs = subs.concat(siblingSubs);"," } else {"," subs = siblingSubs.concat();"," }"," } else {"," if (subs) {"," subs = subs.concat();"," } else {"," subs = [];"," }"," }",""," if (siblingAfters) {"," if (afters) {"," afters = afters.concat(siblingAfters);"," } else {"," afters = siblingAfters.concat();"," }"," } else {"," if (afters) {"," afters = afters.concat();"," } else {"," afters = [];"," }"," }",""," return [subs, afters];"," },",""," /**"," * Apply configuration properties. Only applies the CONFIG whitelist"," * @method applyConfig"," * @param o hash of properties to apply."," * @param force {boolean} if true, properties that exist on the event"," * will be overwritten."," */"," applyConfig: function(o, force) {"," mixConfigs(this, o, force);"," },",""," /**"," * Create the Subscription for subscribing function, context, and bound"," * arguments. If this is a fireOnce event, the subscriber is immediately"," * notified."," *"," * @method _on"," * @param fn {Function} Subscription callback"," * @param [context] {Object} Override `this` in the callback"," * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()"," * @param [when] {String} \"after\" to slot into after subscribers"," * @return {EventHandle}"," * @protected"," */"," _on: function(fn, context, args, when) {","",""," var s = new Y.Subscriber(fn, context, args, when);",""," if (this.fireOnce && this.fired) {"," if (this.async) {"," setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0);"," } else {"," this._notify(s, this.firedWith);"," }"," }",""," if (when === AFTER) {"," if (!this._afters) {"," this._afters = [];"," this._hasAfters = true;"," }"," this._afters.push(s);"," } else {"," if (!this._subscribers) {"," this._subscribers = [];"," this._hasSubs = true;"," }"," this._subscribers.push(s);"," }",""," if (this._kds) {"," if (when === AFTER) {"," this.afters[s.id] = s;"," } else {"," this.subscribers[s.id] = s;"," }"," }",""," return new Y.EventHandle(this, s);"," },",""," /**"," * Listen for this event"," * @method subscribe"," * @param {Function} fn The function to execute."," * @return {EventHandle} Unsubscribe handle."," * @deprecated use on."," */"," subscribe: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;"," return this._on(fn, context, a, true);"," },",""," /**"," * Listen for this event"," * @method on"," * @param {Function} fn The function to execute."," * @param {object} context optional execution context."," * @param {mixed} arg* 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {EventHandle} An object with a detach method to detch the handler(s)."," */"," on: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;",""," if (this.monitored && this.host) {"," this.host._monitor('attach', this, {"," args: arguments"," });"," }"," return this._on(fn, context, a, true);"," },",""," /**"," * Listen for this event after the normal subscribers have been notified and"," * the default behavior has been applied. If a normal subscriber prevents the"," * default behavior, it also prevents after listeners from firing."," * @method after"," * @param {Function} fn The function to execute."," * @param {object} context optional execution context."," * @param {mixed} arg* 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {EventHandle} handle Unsubscribe handle."," */"," after: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;"," return this._on(fn, context, a, AFTER);"," },",""," /**"," * Detach listeners."," * @method detach"," * @param {Function} fn The subscribed function to remove, if not supplied"," * all will be removed."," * @param {Object} context The context object passed to subscribe."," * @return {int} returns the number of subscribers unsubscribed."," */"," detach: function(fn, context) {"," // unsubscribe handle"," if (fn && fn.detach) {"," return fn.detach();"," }",""," var i, s,"," found = 0,"," subs = this._subscribers,"," afters = this._afters;",""," if (subs) {"," for (i = subs.length; i >= 0; i--) {"," s = subs[i];"," if (s && (!fn || fn === s.fn)) {"," this._delete(s, subs, i);"," found++;"," }"," }"," }",""," if (afters) {"," for (i = afters.length; i >= 0; i--) {"," s = afters[i];"," if (s && (!fn || fn === s.fn)) {"," this._delete(s, afters, i);"," found++;"," }"," }"," }",""," return found;"," },",""," /**"," * Detach listeners."," * @method unsubscribe"," * @param {Function} fn The subscribed function to remove, if not supplied"," * all will be removed."," * @param {Object} context The context object passed to subscribe."," * @return {int|undefined} returns the number of subscribers unsubscribed."," * @deprecated use detach."," */"," unsubscribe: function() {"," return this.detach.apply(this, arguments);"," },",""," /**"," * Notify a single subscriber"," * @method _notify"," * @param {Subscriber} s the subscriber."," * @param {Array} args the arguments array to apply to the listener."," * @protected"," */"," _notify: function(s, args, ef) {","",""," var ret;",""," ret = s.notify(args, this);",""," if (false === ret || this.stopped > 1) {"," return false;"," }",""," return true;"," },",""," /**"," * Logger abstraction to centralize the application of the silent flag"," * @method log"," * @param {string} msg message to log."," * @param {string} cat log category."," */"," log: function(msg, cat) {"," },",""," /**"," * Notifies the subscribers. The callback functions will be executed"," * from the context specified when the event was created, and with the"," * following parameters:"," * <ul>"," * <li>The type of event</li>"," * <li>All of the arguments fire() was executed with as an array</li>"," * <li>The custom object (if any) that was passed into the subscribe()"," * method</li>"," * </ul>"," * @method fire"," * @param {Object*} arguments an arbitrary set of parameters to pass to"," * the handler."," * @return {boolean} false if one of the subscribers returned false,"," * true otherwise."," *"," */"," fire: function() {",""," // push is the fastest way to go from arguments to arrays"," // for most browsers currently"," // http://jsperf.com/push-vs-concat-vs-slice/2",""," var args = [];"," args.push.apply(args, arguments);",""," return this._fire(args);"," },",""," /**"," * Private internal implementation for `fire`, which is can be used directly by"," * `EventTarget` and other event module classes which have already converted from"," * an `arguments` list to an array, to avoid the repeated overhead."," *"," * @method _fire"," * @private"," * @param {Array} args The array of arguments passed to be passed to handlers."," * @return {boolean} false if one of the subscribers returned false, true otherwise."," */"," _fire: function(args) {",""," if (this.fireOnce && this.fired) {"," return true;"," } else {",""," // this doesn't happen if the event isn't published"," // this.host._monitor('fire', this.type, args);",""," this.fired = true;",""," if (this.fireOnce) {"," this.firedWith = args;"," }",""," if (this.emitFacade) {"," return this.fireComplex(args);"," } else {"," return this.fireSimple(args);"," }"," }"," },",""," /**"," * Set up for notifying subscribers of non-emitFacade events."," *"," * @method fireSimple"," * @param args {Array} Arguments passed to fire()"," * @return Boolean false if a subscriber returned false"," * @protected"," */"," fireSimple: function(args) {"," this.stopped = 0;"," this.prevented = 0;"," if (this.hasSubs()) {"," var subs = this.getSubs();"," this._procSubs(subs[0], args);"," this._procSubs(subs[1], args);"," }"," if (this.broadcast) {"," this._broadcast(args);"," }"," return this.stopped ? false : true;"," },",""," // Requires the event-custom-complex module for full funcitonality."," fireComplex: function(args) {"," args[0] = args[0] || {};"," return this.fireSimple(args);"," },",""," /**"," * Notifies a list of subscribers."," *"," * @method _procSubs"," * @param subs {Array} List of subscribers"," * @param args {Array} Arguments passed to fire()"," * @param ef {}"," * @return Boolean false if a subscriber returns false or stops the event"," * propagation via e.stopPropagation(),"," * e.stopImmediatePropagation(), or e.halt()"," * @private"," */"," _procSubs: function(subs, args, ef) {"," var s, i, l;",""," for (i = 0, l = subs.length; i < l; i++) {"," s = subs[i];"," if (s && s.fn) {"," if (false === this._notify(s, args, ef)) {"," this.stopped = 2;"," }"," if (this.stopped === 2) {"," return false;"," }"," }"," }",""," return true;"," },",""," /**"," * Notifies the YUI instance if the event is configured with broadcast = 1,"," * and both the YUI instance and Y.Global if configured with broadcast = 2."," *"," * @method _broadcast"," * @param args {Array} Arguments sent to fire()"," * @private"," */"," _broadcast: function(args) {"," if (!this.stopped && this.broadcast) {",""," var a = args.concat();"," a.unshift(this.type);",""," if (this.host !== Y) {"," Y.fire.apply(Y, a);"," }",""," if (this.broadcast === 2) {"," Y.Global.fire.apply(Y.Global, a);"," }"," }"," },",""," /**"," * Removes all listeners"," * @method unsubscribeAll"," * @return {int} The number of listeners unsubscribed."," * @deprecated use detachAll."," */"," unsubscribeAll: function() {"," return this.detachAll.apply(this, arguments);"," },",""," /**"," * Removes all listeners"," * @method detachAll"," * @return {int} The number of listeners unsubscribed."," */"," detachAll: function() {"," return this.detach();"," },",""," /**"," * Deletes the subscriber from the internal store of on() and after()"," * subscribers."," *"," * @method _delete"," * @param s subscriber object."," * @param subs (optional) on or after subscriber array"," * @param index (optional) The index found."," * @private"," */"," _delete: function(s, subs, i) {"," var when = s._when;",""," if (!subs) {"," subs = (when === AFTER) ? this._afters : this._subscribers;"," i = YArray.indexOf(subs, s, 0);"," }",""," if (subs) {"," if (s && subs[i] === s) {"," subs.splice(i, 1);",""," if (subs.length === 0) {"," if (when === AFTER) {"," this._hasAfters = false;"," } else {"," this._hasSubs = false;"," }"," }"," }"," }",""," if (this._kds) {"," if (when === AFTER) {"," delete this.afters[s.id];"," } else {"," delete this.subscribers[s.id];"," }"," }",""," if (this.monitored && this.host) {"," this.host._monitor('detach', this, {"," ce: this,"," sub: s"," });"," }",""," if (s) {"," s.deleted = true;"," }"," }","};","/**"," * Stores the subscriber information to be used when the event fires."," * @param {Function} fn The wrapped function to execute."," * @param {Object} context The value of the keyword 'this' in the listener."," * @param {Array} args* 0..n additional arguments to supply the listener."," *"," * @class Subscriber"," * @constructor"," */","Y.Subscriber = function(fn, context, args, when) {",""," /**"," * The callback that will be execute when the event fires"," * This is wrapped by Y.rbind if obj was supplied."," * @property fn"," * @type Function"," */"," this.fn = fn;",""," /**"," * Optional 'this' keyword for the listener"," * @property context"," * @type Object"," */"," this.context = context;",""," /**"," * Unique subscriber id"," * @property id"," * @type String"," */"," this.id = Y.guid();",""," /**"," * Additional arguments to propagate to the subscriber"," * @property args"," * @type Array"," */"," this.args = args;",""," this._when = when;",""," /**"," * Custom events for a given fire transaction."," * @property events"," * @type {EventTarget}"," */"," // this.events = null;",""," /**"," * This listener only reacts to the event once"," * @property once"," */"," // this.once = false;","","};","","Y.Subscriber.prototype = {"," constructor: Y.Subscriber,",""," _notify: function(c, args, ce) {"," if (this.deleted && !this.postponed) {"," if (this.postponed) {"," delete this.fn;"," delete this.context;"," } else {"," delete this.postponed;"," return null;"," }"," }"," var a = this.args, ret;"," switch (ce.signature) {"," case 0:"," ret = this.fn.call(c, ce.type, args, c);"," break;"," case 1:"," ret = this.fn.call(c, args[0] || null, c);"," break;"," default:"," if (a || args) {"," args = args || [];"," a = (a) ? args.concat(a) : args;"," ret = this.fn.apply(c, a);"," } else {"," ret = this.fn.call(c);"," }"," }",""," if (this.once) {"," ce._delete(this);"," }",""," return ret;"," },",""," /**"," * Executes the subscriber."," * @method notify"," * @param args {Array} Arguments array for the subscriber."," * @param ce {CustomEvent} The custom event that sent the notification."," */"," notify: function(args, ce) {"," var c = this.context,"," ret = true;",""," if (!c) {"," c = (ce.contextFn) ? ce.contextFn() : ce.context;"," }",""," // only catch errors if we will not re-throw them."," if (Y.config && Y.config.throwFail) {"," ret = this._notify(c, args, ce);"," } else {"," try {"," ret = this._notify(c, args, ce);"," } catch (e) {"," Y.error(this + ' failed: ' + e.message, e);"," }"," }",""," return ret;"," },",""," /**"," * Returns true if the fn and obj match this objects properties."," * Used by the unsubscribe method to match the right subscriber."," *"," * @method contains"," * @param {Function} fn the function to execute."," * @param {Object} context optional 'this' keyword for the listener."," * @return {boolean} true if the supplied arguments match this"," * subscriber's signature."," */"," contains: function(fn, context) {"," if (context) {"," return ((this.fn === fn) && this.context === context);"," } else {"," return (this.fn === fn);"," }"," },",""," valueOf : function() {"," return this.id;"," }","","};","/**"," * Return value from all subscribe operations"," * @class EventHandle"," * @constructor"," * @param {CustomEvent} evt the custom event."," * @param {Subscriber} sub the subscriber."," */","Y.EventHandle = function(evt, sub) {",""," /**"," * The custom event"," *"," * @property evt"," * @type CustomEvent"," */"," this.evt = evt;",""," /**"," * The subscriber object"," *"," * @property sub"," * @type Subscriber"," */"," this.sub = sub;","};","","Y.EventHandle.prototype = {"," batch: function(f, c) {"," f.call(c || this, this);"," if (Y.Lang.isArray(this.evt)) {"," Y.Array.each(this.evt, function(h) {"," h.batch.call(c || h, f);"," });"," }"," },",""," /**"," * Detaches this subscriber"," * @method detach"," * @return {int} the number of detached listeners"," */"," detach: function() {"," var evt = this.evt, detached = 0, i;"," if (evt) {"," if (Y.Lang.isArray(evt)) {"," for (i = 0; i < evt.length; i++) {"," detached += evt[i].detach();"," }"," } else {"," evt._delete(this.sub);"," detached = 1;"," }",""," }",""," return detached;"," },",""," /**"," * Monitor the event state for the subscribed event. The first parameter"," * is what should be monitored, the rest are the normal parameters when"," * subscribing to an event."," * @method monitor"," * @param what {string} what to monitor ('attach', 'detach', 'publish')."," * @return {EventHandle} return value from the monitor event subscription."," */"," monitor: function(what) {"," return this.evt.monitor.apply(this.evt, arguments);"," }","};","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","/**"," * EventTarget provides the implementation for any object to"," * publish, subscribe and fire to custom events, and also"," * alows other EventTargets to target the object with events"," * sourced from the other object."," * EventTarget is designed to be used with Y.augment to wrap"," * EventCustom in an interface that allows events to be listened to"," * and fired by name. This makes it possible for implementing code to"," * subscribe to an event that either has not been created yet, or will"," * not be created at all."," * @class EventTarget"," * @param opts a configuration object"," * @config emitFacade {boolean} if true, all events will emit event"," * facade payloads by default (default false)"," * @config prefix {String} the prefix to apply to non-prefixed event names"," */","","var L = Y.Lang,"," PREFIX_DELIMITER = ':',"," CATEGORY_DELIMITER = '|',"," AFTER_PREFIX = '~AFTER~',"," WILD_TYPE_RE = /(.*?)(:)(.*?)/,",""," _wildType = Y.cached(function(type) {"," return type.replace(WILD_TYPE_RE, \"*$2$3\");"," }),",""," /**"," * If the instance has a prefix attribute and the"," * event type is not prefixed, the instance prefix is"," * applied to the supplied type."," * @method _getType"," * @private"," */"," _getType = function(type, pre) {",""," if (!pre || type.indexOf(PREFIX_DELIMITER) > -1) {"," return type;"," }",""," return pre + PREFIX_DELIMITER + type;"," },",""," /**"," * Returns an array with the detach key (if provided),"," * and the prefixed event name from _getType"," * Y.on('detachcategory| menu:click', fn)"," * @method _parseType"," * @private"," */"," _parseType = Y.cached(function(type, pre) {",""," var t = type, detachcategory, after, i;",""," if (!L.isString(t)) {"," return t;"," }",""," i = t.indexOf(AFTER_PREFIX);",""," if (i > -1) {"," after = true;"," t = t.substr(AFTER_PREFIX.length);"," }",""," i = t.indexOf(CATEGORY_DELIMITER);",""," if (i > -1) {"," detachcategory = t.substr(0, (i));"," t = t.substr(i+1);"," if (t === '*') {"," t = null;"," }"," }",""," // detach category, full type with instance prefix, is this an after listener, short type"," return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];"," }),",""," ET = function(opts) {",""," var etState = this._yuievt,"," etConfig;",""," if (!etState) {"," etState = this._yuievt = {"," events: {}, // PERF: Not much point instantiating lazily. We're bound to have events"," targets: null, // PERF: Instantiate lazily, if user actually adds target,"," config: {"," host: this,"," context: this"," },"," chain: Y.config.chain"," };"," }",""," etConfig = etState.config;",""," if (opts) {"," mixConfigs(etConfig, opts, true);",""," if (opts.chain !== undefined) {"," etState.chain = opts.chain;"," }",""," if (opts.prefix) {"," etConfig.prefix = opts.prefix;"," }"," }"," };","","ET.prototype = {",""," constructor: ET,",""," /**"," * Listen to a custom event hosted by this object one time."," * This is the equivalent to <code>on</code> except the"," * listener is immediatelly detached when it is executed."," * @method once"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching the"," * subscription"," */"," once: function() {"," var handle = this.on.apply(this, arguments);"," handle.batch(function(hand) {"," if (hand.sub) {"," hand.sub.once = true;"," }"," });"," return handle;"," },",""," /**"," * Listen to a custom event hosted by this object one time."," * This is the equivalent to <code>after</code> except the"," * listener is immediatelly detached when it is executed."," * @method onceAfter"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching that"," * subscription"," */"," onceAfter: function() {"," var handle = this.after.apply(this, arguments);"," handle.batch(function(hand) {"," if (hand.sub) {"," hand.sub.once = true;"," }"," });"," return handle;"," },",""," /**"," * Takes the type parameter passed to 'on' and parses out the"," * various pieces that could be included in the type. If the"," * event type is passed without a prefix, it will be expanded"," * to include the prefix one is supplied or the event target"," * is configured with a default prefix."," * @method parseType"," * @param {String} type the type"," * @param {String} [pre=this._yuievt.config.prefix] the prefix"," * @since 3.3.0"," * @return {Array} an array containing:"," * * the detach category, if supplied,"," * * the prefixed event type,"," * * whether or not this is an after listener,"," * * the supplied event type"," */"," parseType: function(type, pre) {"," return _parseType(type, pre || this._yuievt.config.prefix);"," },",""," /**"," * Subscribe a callback function to a custom event fired by this object or"," * from an object that bubbles its events to this object."," *"," * Callback functions for events published with `emitFacade = true` will"," * receive an `EventFacade` as the first argument (typically named \"e\")."," * These callbacks can then call `e.preventDefault()` to disable the"," * behavior published to that event's `defaultFn`. See the `EventFacade`"," * API for all available properties and methods. Subscribers to"," * non-`emitFacade` events will receive the arguments passed to `fire()`"," * after the event name."," *"," * To subscribe to multiple events at once, pass an object as the first"," * argument, where the key:value pairs correspond to the eventName:callback,"," * or pass an array of event names as the first argument to subscribe to"," * all listed events with the same callback."," *"," * Returning `false` from a callback is supported as an alternative to"," * calling `e.preventDefault(); e.stopPropagation();`. However, it is"," * recommended to use the event methods whenever possible."," *"," * @method on"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching that"," * subscription"," */"," on: function(type, fn, context) {",""," var yuievt = this._yuievt,"," parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce,"," detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,"," Node = Y.Node, n, domevent, isArr;",""," // full name, args, detachcategory, after"," this._monitor('attach', parts[1], {"," args: arguments,"," category: parts[0],"," after: parts[2]"," });",""," if (L.isObject(type)) {",""," if (L.isFunction(type)) {"," return Y.Do.before.apply(Y.Do, arguments);"," }",""," f = fn;"," c = context;"," args = nativeSlice.call(arguments, 0);"," ret = [];",""," if (L.isArray(type)) {"," isArr = true;"," }",""," after = type._after;"," delete type._after;",""," Y.each(type, function(v, k) {",""," if (L.isObject(v)) {"," f = v.fn || ((L.isFunction(v)) ? v : f);"," c = v.context || c;"," }",""," var nv = (after) ? AFTER_PREFIX : '';",""," args[0] = nv + ((isArr) ? v : k);"," args[1] = f;"," args[2] = c;",""," ret.push(this.on.apply(this, args));",""," }, this);",""," return (yuievt.chain) ? this : new Y.EventHandle(ret);"," }",""," detachcategory = parts[0];"," after = parts[2];"," shorttype = parts[3];",""," // extra redirection so we catch adaptor events too. take a look at this."," if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {"," args = nativeSlice.call(arguments, 0);"," args.splice(2, 0, Node.getDOMNode(this));"," return Y.on.apply(Y, args);"," }",""," type = parts[1];",""," if (Y.instanceOf(this, YUI)) {",""," adapt = Y.Env.evt.plugins[type];"," args = nativeSlice.call(arguments, 0);"," args[0] = shorttype;",""," if (Node) {"," n = args[2];",""," if (Y.instanceOf(n, Y.NodeList)) {"," n = Y.NodeList.getDOMNodes(n);"," } else if (Y.instanceOf(n, Node)) {"," n = Node.getDOMNode(n);"," }",""," domevent = (shorttype in Node.DOM_EVENTS);",""," // Captures both DOM events and event plugins."," if (domevent) {"," args[2] = n;"," }"," }",""," // check for the existance of an event adaptor"," if (adapt) {"," handle = adapt.on.apply(Y, args);"," } else if ((!type) || domevent) {"," handle = Y.Event._attach(args);"," }",""," }",""," if (!handle) {"," ce = yuievt.events[type] || this.publish(type);"," handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true);",""," // TODO: More robust regex, accounting for category"," if (type.indexOf(\"*:\") !== -1) {"," this._hasSiblings = true;"," }"," }",""," if (detachcategory) {"," store[detachcategory] = store[detachcategory] || {};"," store[detachcategory][type] = store[detachcategory][type] || [];"," store[detachcategory][type].push(handle);"," }",""," return (yuievt.chain) ? this : handle;",""," },",""," /**"," * subscribe to an event"," * @method subscribe"," * @deprecated use on"," */"," subscribe: function() {"," return this.on.apply(this, arguments);"," },",""," /**"," * Detach one or more listeners the from the specified event"," * @method detach"," * @param type {string|Object} Either the handle to the subscriber or the"," * type of event. If the type"," * is not specified, it will attempt to remove"," * the listener from all hosted events."," * @param fn {Function} The subscribed function to unsubscribe, if not"," * supplied, all subscribers will be removed."," * @param context {Object} The custom object passed to subscribe. This is"," * optional, but if supplied will be used to"," * disambiguate multiple listeners that are the same"," * (e.g., you subscribe many object using a function"," * that lives on the prototype)"," * @return {EventTarget} the host"," */"," detach: function(type, fn, context) {",""," var evts = this._yuievt.events,"," i,"," Node = Y.Node,"," isNode = Node && (Y.instanceOf(this, Node));",""," // detachAll disabled on the Y instance."," if (!type && (this !== Y)) {"," for (i in evts) {"," if (evts.hasOwnProperty(i)) {"," evts[i].detach(fn, context);"," }"," }"," if (isNode) {"," Y.Event.purgeElement(Node.getDOMNode(this));"," }",""," return this;"," }",""," var parts = _parseType(type, this._yuievt.config.prefix),"," detachcategory = L.isArray(parts) ? parts[0] : null,"," shorttype = (parts) ? parts[3] : null,"," adapt, store = Y.Env.evt.handles, detachhost, cat, args,"," ce,",""," keyDetacher = function(lcat, ltype, host) {"," var handles = lcat[ltype], ce, i;"," if (handles) {"," for (i = handles.length - 1; i >= 0; --i) {"," ce = handles[i].evt;"," if (ce.host === host || ce.el === host) {"," handles[i].detach();"," }"," }"," }"," };",""," if (detachcategory) {",""," cat = store[detachcategory];"," type = parts[1];"," detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;",""," if (cat) {"," if (type) {"," keyDetacher(cat, type, detachhost);"," } else {"," for (i in cat) {"," if (cat.hasOwnProperty(i)) {"," keyDetacher(cat, i, detachhost);"," }"," }"," }",""," return this;"," }",""," // If this is an event handle, use it to detach"," } else if (L.isObject(type) && type.detach) {"," type.detach();"," return this;"," // extra redirection so we catch adaptor events too. take a look at this."," } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {"," args = nativeSlice.call(arguments, 0);"," args[2] = Node.getDOMNode(this);"," Y.detach.apply(Y, args);"," return this;"," }",""," adapt = Y.Env.evt.plugins[shorttype];",""," // The YUI instance handles DOM events and adaptors"," if (Y.instanceOf(this, YUI)) {"," args = nativeSlice.call(arguments, 0);"," // use the adaptor specific detach code if"," if (adapt && adapt.detach) {"," adapt.detach.apply(Y, args);"," return this;"," // DOM event fork"," } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {"," args[0] = type;"," Y.Event.detach.apply(Y.Event, args);"," return this;"," }"," }",""," // ce = evts[type];"," ce = evts[parts[1]];"," if (ce) {"," ce.detach(fn, context);"," }",""," return this;"," },",""," /**"," * detach a listener"," * @method unsubscribe"," * @deprecated use detach"," */"," unsubscribe: function() {"," return this.detach.apply(this, arguments);"," },",""," /**"," * Removes all listeners from the specified event. If the event type"," * is not specified, all listeners from all hosted custom events will"," * be removed."," * @method detachAll"," * @param type {String} The type, or name of the event"," */"," detachAll: function(type) {"," return this.detach(type);"," },",""," /**"," * Removes all listeners from the specified event. If the event type"," * is not specified, all listeners from all hosted custom events will"," * be removed."," * @method unsubscribeAll"," * @param type {String} The type, or name of the event"," * @deprecated use detachAll"," */"," unsubscribeAll: function() {"," return this.detachAll.apply(this, arguments);"," },",""," /**"," * Creates a new custom event of the specified type. If a custom event"," * by that name already exists, it will not be re-created. In either"," * case the custom event is returned."," *"," * @method publish"," *"," * @param type {String} the type, or name of the event"," * @param opts {object} optional config params. Valid properties are:"," *"," * <ul>"," * <li>"," * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)"," * </li>"," * <li>"," * 'bubbles': whether or not this event bubbles (true)"," * Events can only bubble if emitFacade is true."," * </li>"," * <li>"," * 'context': the default execution context for the listeners (this)"," * </li>"," * <li>"," * 'defaultFn': the default function to execute when this event fires if preventDefault was not called"," * </li>"," * <li>"," * 'emitFacade': whether or not this event emits a facade (false)"," * </li>"," * <li>"," * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'"," * </li>"," * <li>"," * 'fireOnce': if an event is configured to fire once, new subscribers after"," * the fire will be notified immediately."," * </li>"," * <li>"," * 'async': fireOnce event listeners will fire synchronously if the event has already"," * fired unless async is true."," * </li>"," * <li>"," * 'preventable': whether or not preventDefault() has an effect (true)"," * </li>"," * <li>"," * 'preventedFn': a function that is executed when preventDefault is called"," * </li>"," * <li>"," * 'queuable': whether or not this event can be queued during bubbling (false)"," * </li>"," * <li>"," * 'silent': if silent is true, debug messages are not provided for this event."," * </li>"," * <li>"," * 'stoppedFn': a function that is executed when stopPropagation is called"," * </li>"," *"," * <li>"," * 'monitored': specifies whether or not this event should send notifications about"," * when the event has been attached, detached, or published."," * </li>"," * <li>"," * 'type': the event type (valid option if not provided as the first parameter to publish)"," * </li>"," * </ul>"," *"," * @return {CustomEvent} the custom event"," *"," */"," publish: function(type, opts) {",""," var ret,"," etState = this._yuievt,"," etConfig = etState.config,"," pre = etConfig.prefix;",""," if (typeof type === \"string\") {"," if (pre) {"," type = _getType(type, pre);"," }"," ret = this._publish(type, etConfig, opts);"," } else {"," ret = {};",""," Y.each(type, function(v, k) {"," if (pre) {"," k = _getType(k, pre);"," }"," ret[k] = this._publish(k, etConfig, v || opts);"," }, this);",""," }",""," return ret;"," },",""," /**"," * Returns the fully qualified type, given a short type string."," * That is, returns \"foo:bar\" when given \"bar\" if \"foo\" is the configured prefix."," *"," * NOTE: This method, unlike _getType, does no checking of the value passed in, and"," * is designed to be used with the low level _publish() method, for critical path"," * implementations which need to fast-track publish for performance reasons."," *"," * @method _getFullType"," * @private"," * @param {String} type The short type to prefix"," * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in"," */"," _getFullType : function(type) {",""," var pre = this._yuievt.config.prefix;",""," if (pre) {"," return pre + PREFIX_DELIMITER + type;"," } else {"," return type;"," }"," },",""," /**"," * The low level event publish implementation. It expects all the massaging to have been done"," * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast"," * path publish, which can be used by critical code paths to improve performance."," *"," * @method _publish"," * @private"," * @param {String} fullType The prefixed type of the event to publish."," * @param {Object} etOpts The EventTarget specific configuration to mix into the published event."," * @param {Object} ceOpts The publish specific configuration to mix into the published event."," * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will"," * be the default `CustomEvent` instance, and can be configured independently."," */"," _publish : function(fullType, etOpts, ceOpts) {",""," var ce,"," etState = this._yuievt,"," etConfig = etState.config,"," host = etConfig.host,"," context = etConfig.context,"," events = etState.events;",""," ce = events[fullType];",""," // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight."," if ((etConfig.monitored && !ce) || (ce && ce.monitored)) {"," this._monitor('publish', fullType, {"," args: arguments"," });"," }",""," if (!ce) {"," // Publish event"," ce = events[fullType] = new Y.CustomEvent(fullType, etOpts);",""," if (!etOpts) {"," ce.host = host;"," ce.context = context;"," }"," }",""," if (ceOpts) {"," mixConfigs(ce, ceOpts, true);"," }",""," return ce;"," },",""," /**"," * This is the entry point for the event monitoring system."," * You can monitor 'attach', 'detach', 'fire', and 'publish'."," * When configured, these events generate an event. click ->"," * click_attach, click_detach, click_publish -- these can"," * be subscribed to like other events to monitor the event"," * system. Inividual published events can have monitoring"," * turned on or off (publish can't be turned off before it"," * it published) by setting the events 'monitor' config."," *"," * @method _monitor"," * @param what {String} 'attach', 'detach', 'fire', or 'publish'"," * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object."," * @param o {Object} Information about the event interaction, such as"," * fire() args, subscription category, publish config"," * @private"," */"," _monitor: function(what, eventType, o) {"," var monitorevt, ce, type;",""," if (eventType) {"," if (typeof eventType === \"string\") {"," type = eventType;"," ce = this.getEvent(eventType, true);"," } else {"," ce = eventType;"," type = eventType.type;"," }",""," if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {"," monitorevt = type + '_' + what;"," o.monitored = what;"," this.fire.call(this, monitorevt, o);"," }"," }"," },",""," /**"," * Fire a custom event by name. The callback functions will be executed"," * from the context specified when the event was created, and with the"," * following parameters."," *"," * If the custom event object hasn't been created, then the event hasn't"," * been published and it has no subscribers. For performance sake, we"," * immediate exit in this case. This means the event won't bubble, so"," * if the intention is that a bubble target be notified, the event must"," * be published on this object first."," *"," * The first argument is the event type, and any additional arguments are"," * passed to the listeners as parameters. If the first of these is an"," * object literal, and the event is configured to emit an event facade,"," * that object is mixed into the event facade and the facade is provided"," * in place of the original object."," *"," * @method fire"," * @param type {String|Object} The type of the event, or an object that contains"," * a 'type' property."," * @param arguments {Object*} an arbitrary set of parameters to pass to"," * the handler. If the first of these is an object literal and the event is"," * configured to emit an event facade, the event facade will replace that"," * parameter after the properties the object literal contains are copied to"," * the event facade."," * @return {EventTarget} the event host"," */"," fire: function(type) {",""," var typeIncluded = (typeof type === \"string\"),"," argCount = arguments.length,"," t = type,"," yuievt = this._yuievt,"," etConfig = yuievt.config,"," pre = etConfig.prefix,"," ret,"," ce,"," ce2,"," args;",""," if (typeIncluded && argCount <= 2) {",""," // PERF: Try to avoid slice/iteration for the common signatures",""," if (argCount === 2) {"," args = [arguments[1]]; // fire(\"foo\", {})"," } else {"," args = []; // fire(\"foo\")"," }",""," } else {"," args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0));"," }",""," if (!typeIncluded) {"," t = (type && type.type);"," }",""," if (pre) {"," t = _getType(t, pre);"," }",""," ce = yuievt.events[t];",""," if (this._hasSiblings) {"," ce2 = this.getSibling(t, ce);",""," if (ce2 && !ce) {"," ce = this.publish(t);"," }"," }",""," // PERF: trying to avoid function call, since this is a critical path"," if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {"," this._monitor('fire', (ce || t), {"," args: args"," });"," }",""," // this event has not been published or subscribed to"," if (!ce) {"," if (yuievt.hasTargets) {"," return this.bubble({ type: t }, args, this);"," }",""," // otherwise there is nothing to be done"," ret = true;"," } else {",""," if (ce2) {"," ce.sibling = ce2;"," }",""," ret = ce._fire(args);"," }",""," return (yuievt.chain) ? this : ret;"," },",""," getSibling: function(type, ce) {"," var ce2;",""," // delegate to *:type events if there are subscribers"," if (type.indexOf(PREFIX_DELIMITER) > -1) {"," type = _wildType(type);"," ce2 = this.getEvent(type, true);"," if (ce2) {"," ce2.applyConfig(ce);"," ce2.bubbles = false;"," ce2.broadcast = 0;"," }"," }",""," return ce2;"," },",""," /**"," * Returns the custom event of the provided type has been created, a"," * falsy value otherwise"," * @method getEvent"," * @param type {String} the type, or name of the event"," * @param prefixed {String} if true, the type is prefixed already"," * @return {CustomEvent} the custom event or null"," */"," getEvent: function(type, prefixed) {"," var pre, e;",""," if (!prefixed) {"," pre = this._yuievt.config.prefix;"," type = (pre) ? _getType(type, pre) : type;"," }"," e = this._yuievt.events;"," return e[type] || null;"," },",""," /**"," * Subscribe to a custom event hosted by this object. The"," * supplied callback will execute after any listeners add"," * via the subscribe method, and after the default function,"," * if configured for the event, has executed."," *"," * @method after"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching the"," * subscription"," */"," after: function(type, fn) {",""," var a = nativeSlice.call(arguments, 0);",""," switch (L.type(type)) {"," case 'function':"," return Y.Do.after.apply(Y.Do, arguments);"," case 'array':"," // YArray.each(a[0], function(v) {"," // v = AFTER_PREFIX + v;"," // });"," // break;"," case 'object':"," a[0]._after = true;"," break;"," default:"," a[0] = AFTER_PREFIX + type;"," }",""," return this.on.apply(this, a);",""," },",""," /**"," * Executes the callback before a DOM event, custom event"," * or method. If the first argument is a function, it"," * is assumed the target is a method. For DOM and custom"," * events, this is an alias for Y.on."," *"," * For DOM and custom events:"," * type, callback, context, 0-n arguments"," *"," * For methods:"," * callback, object (method host), methodName, context, 0-n arguments"," *"," * @method before"," * @return detach handle"," */"," before: function() {"," return this.on.apply(this, arguments);"," }","","};","","Y.EventTarget = ET;","","// make Y an event target","Y.mix(Y, ET.prototype);","ET.call(Y, { bubbles: false });","","YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();","","/**"," * Hosts YUI page level events. This is where events bubble to"," * when the broadcast config is set to 2. This property is"," * only available if the custom event module is loaded."," * @property Global"," * @type EventTarget"," * @for YUI"," */","Y.Global = YUI.Env.globalEvents;","","// @TODO implement a global namespace function on Y.Global?","","/**","`Y.on()` can do many things:","","<ul>"," <li>Subscribe to custom events `publish`ed and `fire`d from Y</li>"," <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and"," `fire`d from any object in the YUI instance sandbox</li>"," <li>Subscribe to DOM events</li>"," <li>Subscribe to the execution of a method on any object, effectively"," treating that method as an event</li>","</ul>","","For custom event subscriptions, pass the custom event name as the first argument","and callback as the second. The `this` object in the callback will be `Y` unless","an override is passed as the third argument.",""," Y.on('io:complete', function () {"," Y.MyApp.updateStatus('Transaction complete');"," });","","To subscribe to DOM events, pass the name of a DOM event as the first argument","and a CSS selector string as the third argument after the callback function.","Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,","array, or simply omitted (the default is the `window` object).",""," Y.on('click', function (e) {"," e.preventDefault();",""," // proceed with ajax form submission"," var url = this.get('action');"," ..."," }, '#my-form');","","The `this` object in DOM event callbacks will be the `Node` targeted by the CSS","selector or other identifier.","","`on()` subscribers for DOM events or custom events `publish`ed with a","`defaultFn` can prevent the default behavior with `e.preventDefault()` from the","event object passed as the first parameter to the subscription callback.","","To subscribe to the execution of an object method, pass arguments corresponding to the call signature for","<a href=\"../classes/Do.html#methods_before\">`Y.Do.before(...)`</a>.","","NOTE: The formal parameter list below is for events, not for function","injection. See `Y.Do.before` for that signature.","","@method on","@param {String} type DOM or custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@see Do.before","@for YUI","**/","","/**","Listen for an event one time. Equivalent to `on()`, except that","the listener is immediately detached when executed.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","@see on","@method once","@param {String} type DOM or custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","/**","Listen for an event one time. Equivalent to `once()`, except, like `after()`,","the subscription callback executes after all `on()` subscribers and the event's","`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase","subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`","subscribers will execute.","","The listener is immediately detached when executed.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","@see once","@method onceAfter","@param {String} type The custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","/**","Like `on()`, this method creates a subscription to a custom event or to the","execution of a method on an object.","","For events, `after()` subscribers are executed after the event's","`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","NOTE: The subscription signature shown is for events, not for function","injection. See <a href=\"../classes/Do.html#methods_after\">`Y.Do.after`</a>","for that signature.","","@see on","@see Do.after","@method after","@param {String} type The custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [args*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","","}, '@VERSION@', {\"requires\": [\"oop\"]});","","}());"]}; } var __cov_0ShtDtxkEapLmfzOgrY8Kw = __coverage__['build/event-custom-base/event-custom-base.js']; __cov_0ShtDtxkEapLmfzOgrY8Kw.s['1']++;YUI.add('event-custom-base',function(Y,NAME){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['1']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['2']++;Y.Env.evt={handles:{},plugins:{}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['3']++;var DO_BEFORE=0,DO_AFTER=1,DO={objs:null,before:function(fn,obj,sFn,c){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['2']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['4']++;var f=fn,a;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['5']++;if(c){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['1'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['6']++;a=[fn,c].concat(Y.Array(arguments,4,true));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['7']++;f=Y.rbind.apply(Y,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['1'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['8']++;return this._inject(DO_BEFORE,f,obj,sFn);},after:function(fn,obj,sFn,c){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['3']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['9']++;var f=fn,a;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['10']++;if(c){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['2'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['11']++;a=[fn,c].concat(Y.Array(arguments,4,true));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['12']++;f=Y.rbind.apply(Y,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['2'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['13']++;return this._inject(DO_AFTER,f,obj,sFn);},_inject:function(when,fn,obj,sFn){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['4']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['14']++;var id=Y.stamp(obj),o,sid;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['15']++;if(!obj._yuiaop){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['3'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['16']++;obj._yuiaop={};}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['3'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['17']++;o=obj._yuiaop;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['18']++;if(!o[sFn]){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['4'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['19']++;o[sFn]=new Y.Do.Method(obj,sFn);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['20']++;obj[sFn]=function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['5']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['21']++;return o[sFn].exec.apply(o[sFn],arguments);};}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['4'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['22']++;sid=id+Y.stamp(fn)+sFn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['23']++;o[sFn].register(sid,fn,when);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['24']++;return new Y.EventHandle(o[sFn],sid);},detach:function(handle){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['6']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['25']++;if(handle.detach){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['5'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['26']++;handle.detach();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['5'][1]++;}}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['27']++;Y.Do=DO;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['28']++;DO.Method=function(obj,sFn){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['7']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['29']++;this.obj=obj;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['30']++;this.methodName=sFn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['31']++;this.method=obj[sFn];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['32']++;this.before={};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['33']++;this.after={};};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['34']++;DO.Method.prototype.register=function(sid,fn,when){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['8']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['35']++;if(when){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['6'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['36']++;this.after[sid]=fn;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['6'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['37']++;this.before[sid]=fn;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['38']++;DO.Method.prototype._delete=function(sid){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['9']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['39']++;delete this.before[sid];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['40']++;delete this.after[sid];};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['41']++;DO.Method.prototype.exec=function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['10']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['42']++;var args=Y.Array(arguments,0,true),i,ret,newRet,bf=this.before,af=this.after,prevented=false;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['43']++;for(i in bf){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['44']++;if(bf.hasOwnProperty(i)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['7'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['45']++;ret=bf[i].apply(this.obj,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['46']++;if(ret){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['8'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['47']++;switch(ret.constructor){case DO.Halt:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['9'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['48']++;return ret.retVal;case DO.AlterArgs:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['9'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['49']++;args=ret.newArgs;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['50']++;break;case DO.Prevent:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['9'][2]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['51']++;prevented=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['52']++;break;default:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['9'][3]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['8'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['7'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['53']++;if(!prevented){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['10'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['54']++;ret=this.method.apply(this.obj,args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['10'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['55']++;DO.originalRetVal=ret;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['56']++;DO.currentRetVal=ret;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['57']++;for(i in af){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['58']++;if(af.hasOwnProperty(i)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['11'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['59']++;newRet=af[i].apply(this.obj,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['60']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['13'][0]++,newRet)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['13'][1]++,newRet.constructor===DO.Halt)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['12'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['61']++;return newRet.retVal;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['12'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['62']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['15'][0]++,newRet)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['15'][1]++,newRet.constructor===DO.AlterReturn)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['14'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['63']++;ret=newRet.newRetVal;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['64']++;DO.currentRetVal=ret;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['14'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['11'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['65']++;return ret;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['66']++;DO.AlterArgs=function(msg,newArgs){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['11']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['67']++;this.msg=msg;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['68']++;this.newArgs=newArgs;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['69']++;DO.AlterReturn=function(msg,newRetVal){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['12']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['70']++;this.msg=msg;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['71']++;this.newRetVal=newRetVal;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['72']++;DO.Halt=function(msg,retVal){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['13']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['73']++;this.msg=msg;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['74']++;this.retVal=retVal;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['75']++;DO.Prevent=function(msg){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['14']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['76']++;this.msg=msg;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['77']++;DO.Error=DO.Halt;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['78']++;var YArray=Y.Array,AFTER='after',CONFIGS=['broadcast','monitored','bubbles','context','contextFn','currentTarget','defaultFn','defaultTargetOnly','details','emitFacade','fireOnce','async','host','preventable','preventedFn','queuable','silent','stoppedFn','target','type'],CONFIGS_HASH=YArray.hash(CONFIGS),nativeSlice=Array.prototype.slice,YUI3_SIGNATURE=9,YUI_LOG='yui:log',mixConfigs=function(r,s,ov){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['15']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['79']++;var p;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['80']++;for(p in s){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['81']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['17'][0]++,CONFIGS_HASH[p])&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['17'][1]++,ov)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['17'][2]++,!(p in r)))){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['16'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['82']++;r[p]=s[p];}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['16'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['83']++;return r;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['84']++;Y.CustomEvent=function(type,defaults){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['16']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['85']++;this._kds=Y.CustomEvent.keepDeprecatedSubs;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['86']++;this.id=Y.guid();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['87']++;this.type=type;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['88']++;this.silent=this.logSystem=type===YUI_LOG;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['89']++;if(this._kds){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['18'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['90']++;this.subscribers={};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['91']++;this.afters={};}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['18'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['92']++;if(defaults){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['19'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['93']++;mixConfigs(this,defaults,true);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['19'][1]++;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['94']++;Y.CustomEvent.keepDeprecatedSubs=false;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['95']++;Y.CustomEvent.mixConfigs=mixConfigs;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['96']++;Y.CustomEvent.prototype={constructor:Y.CustomEvent,signature:YUI3_SIGNATURE,context:Y,preventable:true,bubbles:true,hasSubs:function(when){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['17']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['97']++;var s=0,a=0,subs=this._subscribers,afters=this._afters,sib=this.sibling;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['98']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['20'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['99']++;s=subs.length;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['20'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['100']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['21'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['101']++;a=afters.length;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['21'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['102']++;if(sib){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['22'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['103']++;subs=sib._subscribers;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['104']++;afters=sib._afters;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['105']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['23'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['106']++;s+=subs.length;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['23'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['107']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['24'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['108']++;a+=afters.length;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['24'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['22'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['109']++;if(when){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['25'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['110']++;return when==='after'?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['26'][0]++,a):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['26'][1]++,s);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['25'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['111']++;return s+a;},monitor:function(what){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['18']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['112']++;this.monitored=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['113']++;var type=this.id+'|'+this.type+'_'+what,args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['114']++;args[0]=type;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['115']++;return this.host.on.apply(this.host,args);},getSubs:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['19']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['116']++;var sibling=this.sibling,subs=this._subscribers,afters=this._afters,siblingSubs,siblingAfters;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['117']++;if(sibling){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['27'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['118']++;siblingSubs=sibling._subscribers;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['119']++;siblingAfters=sibling._afters;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['27'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['120']++;if(siblingSubs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['28'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['121']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['29'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['122']++;subs=subs.concat(siblingSubs);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['29'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['123']++;subs=siblingSubs.concat();}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['28'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['124']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['30'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['125']++;subs=subs.concat();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['30'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['126']++;subs=[];}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['127']++;if(siblingAfters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['31'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['128']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['32'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['129']++;afters=afters.concat(siblingAfters);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['32'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['130']++;afters=siblingAfters.concat();}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['31'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['131']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['33'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['132']++;afters=afters.concat();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['33'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['133']++;afters=[];}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['134']++;return[subs,afters];},applyConfig:function(o,force){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['20']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['135']++;mixConfigs(this,o,force);},_on:function(fn,context,args,when){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['21']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['136']++;var s=new Y.Subscriber(fn,context,args,when);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['137']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['35'][0]++,this.fireOnce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['35'][1]++,this.fired)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['34'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['138']++;if(this.async){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['36'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['139']++;setTimeout(Y.bind(this._notify,this,s,this.firedWith),0);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['36'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['140']++;this._notify(s,this.firedWith);}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['34'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['141']++;if(when===AFTER){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['37'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['142']++;if(!this._afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['38'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['143']++;this._afters=[];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['144']++;this._hasAfters=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['38'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['145']++;this._afters.push(s);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['37'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['146']++;if(!this._subscribers){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['39'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['147']++;this._subscribers=[];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['148']++;this._hasSubs=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['39'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['149']++;this._subscribers.push(s);}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['150']++;if(this._kds){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['40'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['151']++;if(when===AFTER){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['41'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['152']++;this.afters[s.id]=s;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['41'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['153']++;this.subscribers[s.id]=s;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['40'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['154']++;return new Y.EventHandle(this,s);},subscribe:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['22']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['155']++;var a=arguments.length>2?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['42'][0]++,nativeSlice.call(arguments,2)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['42'][1]++,null);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['156']++;return this._on(fn,context,a,true);},on:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['23']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['157']++;var a=arguments.length>2?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['43'][0]++,nativeSlice.call(arguments,2)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['43'][1]++,null);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['158']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['45'][0]++,this.monitored)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['45'][1]++,this.host)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['44'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['159']++;this.host._monitor('attach',this,{args:arguments});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['44'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['160']++;return this._on(fn,context,a,true);},after:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['24']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['161']++;var a=arguments.length>2?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['46'][0]++,nativeSlice.call(arguments,2)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['46'][1]++,null);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['162']++;return this._on(fn,context,a,AFTER);},detach:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['25']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['163']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['48'][0]++,fn)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['48'][1]++,fn.detach)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['47'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['164']++;return fn.detach();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['47'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['165']++;var i,s,found=0,subs=this._subscribers,afters=this._afters;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['166']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['49'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['167']++;for(i=subs.length;i>=0;i--){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['168']++;s=subs[i];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['169']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['51'][0]++,s)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['51'][1]++,!fn)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['51'][2]++,fn===s.fn))){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['50'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['170']++;this._delete(s,subs,i);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['171']++;found++;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['50'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['49'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['172']++;if(afters){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['52'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['173']++;for(i=afters.length;i>=0;i--){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['174']++;s=afters[i];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['175']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['54'][0]++,s)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['54'][1]++,!fn)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['54'][2]++,fn===s.fn))){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['53'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['176']++;this._delete(s,afters,i);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['177']++;found++;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['53'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['52'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['178']++;return found;},unsubscribe:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['26']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['179']++;return this.detach.apply(this,arguments);},_notify:function(s,args,ef){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['27']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['180']++;var ret;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['181']++;ret=s.notify(args,this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['182']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['56'][0]++,false===ret)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['56'][1]++,this.stopped>1)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['55'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['183']++;return false;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['55'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['184']++;return true;},log:function(msg,cat){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['28']++;},fire:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['29']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['185']++;var args=[];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['186']++;args.push.apply(args,arguments);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['187']++;return this._fire(args);},_fire:function(args){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['30']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['188']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['58'][0]++,this.fireOnce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['58'][1]++,this.fired)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['57'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['189']++;return true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['57'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['190']++;this.fired=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['191']++;if(this.fireOnce){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['59'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['192']++;this.firedWith=args;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['59'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['193']++;if(this.emitFacade){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['60'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['194']++;return this.fireComplex(args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['60'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['195']++;return this.fireSimple(args);}}},fireSimple:function(args){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['31']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['196']++;this.stopped=0;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['197']++;this.prevented=0;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['198']++;if(this.hasSubs()){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['61'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['199']++;var subs=this.getSubs();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['200']++;this._procSubs(subs[0],args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['201']++;this._procSubs(subs[1],args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['61'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['202']++;if(this.broadcast){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['62'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['203']++;this._broadcast(args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['62'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['204']++;return this.stopped?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['63'][0]++,false):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['63'][1]++,true);},fireComplex:function(args){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['32']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['205']++;args[0]=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['64'][0]++,args[0])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['64'][1]++,{});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['206']++;return this.fireSimple(args);},_procSubs:function(subs,args,ef){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['33']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['207']++;var s,i,l;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['208']++;for(i=0,l=subs.length;i<l;i++){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['209']++;s=subs[i];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['210']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['66'][0]++,s)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['66'][1]++,s.fn)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['65'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['211']++;if(false===this._notify(s,args,ef)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['67'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['212']++;this.stopped=2;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['67'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['213']++;if(this.stopped===2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['68'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['214']++;return false;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['68'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['65'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['215']++;return true;},_broadcast:function(args){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['34']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['216']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['70'][0]++,!this.stopped)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['70'][1]++,this.broadcast)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['69'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['217']++;var a=args.concat();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['218']++;a.unshift(this.type);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['219']++;if(this.host!==Y){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['71'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['220']++;Y.fire.apply(Y,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['71'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['221']++;if(this.broadcast===2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['72'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['222']++;Y.Global.fire.apply(Y.Global,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['72'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['69'][1]++;}},unsubscribeAll:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['35']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['223']++;return this.detachAll.apply(this,arguments);},detachAll:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['36']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['224']++;return this.detach();},_delete:function(s,subs,i){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['37']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['225']++;var when=s._when;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['226']++;if(!subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['73'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['227']++;subs=when===AFTER?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['74'][0]++,this._afters):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['74'][1]++,this._subscribers);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['228']++;i=YArray.indexOf(subs,s,0);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['73'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['229']++;if(subs){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['75'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['230']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['77'][0]++,s)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['77'][1]++,subs[i]===s)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['76'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['231']++;subs.splice(i,1);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['232']++;if(subs.length===0){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['78'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['233']++;if(when===AFTER){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['79'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['234']++;this._hasAfters=false;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['79'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['235']++;this._hasSubs=false;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['78'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['76'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['75'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['236']++;if(this._kds){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['80'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['237']++;if(when===AFTER){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['81'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['238']++;delete this.afters[s.id];}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['81'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['239']++;delete this.subscribers[s.id];}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['80'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['240']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['83'][0]++,this.monitored)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['83'][1]++,this.host)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['82'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['241']++;this.host._monitor('detach',this,{ce:this,sub:s});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['82'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['242']++;if(s){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['84'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['243']++;s.deleted=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['84'][1]++;}}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['244']++;Y.Subscriber=function(fn,context,args,when){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['38']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['245']++;this.fn=fn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['246']++;this.context=context;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['247']++;this.id=Y.guid();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['248']++;this.args=args;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['249']++;this._when=when;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['250']++;Y.Subscriber.prototype={constructor:Y.Subscriber,_notify:function(c,args,ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['39']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['251']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['86'][0]++,this.deleted)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['86'][1]++,!this.postponed)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['85'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['252']++;if(this.postponed){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['87'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['253']++;delete this.fn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['254']++;delete this.context;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['87'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['255']++;delete this.postponed;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['256']++;return null;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['85'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['257']++;var a=this.args,ret;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['258']++;switch(ce.signature){case 0:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['88'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['259']++;ret=this.fn.call(c,ce.type,args,c);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['260']++;break;case 1:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['88'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['261']++;ret=this.fn.call(c,(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['89'][0]++,args[0])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['89'][1]++,null),c);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['262']++;break;default:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['88'][2]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['263']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['91'][0]++,a)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['91'][1]++,args)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['90'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['264']++;args=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['92'][0]++,args)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['92'][1]++,[]);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['265']++;a=a?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['93'][0]++,args.concat(a)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['93'][1]++,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['266']++;ret=this.fn.apply(c,a);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['90'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['267']++;ret=this.fn.call(c);}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['268']++;if(this.once){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['94'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['269']++;ce._delete(this);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['94'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['270']++;return ret;},notify:function(args,ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['40']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['271']++;var c=this.context,ret=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['272']++;if(!c){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['95'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['273']++;c=ce.contextFn?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['96'][0]++,ce.contextFn()):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['96'][1]++,ce.context);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['95'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['274']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['98'][0]++,Y.config)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['98'][1]++,Y.config.throwFail)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['97'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['275']++;ret=this._notify(c,args,ce);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['97'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['276']++;try{__cov_0ShtDtxkEapLmfzOgrY8Kw.s['277']++;ret=this._notify(c,args,ce);}catch(e){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['278']++;Y.error(this+' failed: '+e.message,e);}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['279']++;return ret;},contains:function(fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['41']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['280']++;if(context){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['99'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['281']++;return(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['100'][0]++,this.fn===fn)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['100'][1]++,this.context===context);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['99'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['282']++;return this.fn===fn;}},valueOf:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['42']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['283']++;return this.id;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['284']++;Y.EventHandle=function(evt,sub){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['43']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['285']++;this.evt=evt;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['286']++;this.sub=sub;};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['287']++;Y.EventHandle.prototype={batch:function(f,c){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['44']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['288']++;f.call((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['101'][0]++,c)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['101'][1]++,this),this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['289']++;if(Y.Lang.isArray(this.evt)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['102'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['290']++;Y.Array.each(this.evt,function(h){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['45']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['291']++;h.batch.call((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['103'][0]++,c)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['103'][1]++,h),f);});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['102'][1]++;}},detach:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['46']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['292']++;var evt=this.evt,detached=0,i;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['293']++;if(evt){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['104'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['294']++;if(Y.Lang.isArray(evt)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['105'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['295']++;for(i=0;i<evt.length;i++){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['296']++;detached+=evt[i].detach();}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['105'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['297']++;evt._delete(this.sub);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['298']++;detached=1;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['104'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['299']++;return detached;},monitor:function(what){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['47']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['300']++;return this.evt.monitor.apply(this.evt,arguments);}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['301']++;var L=Y.Lang,PREFIX_DELIMITER=':',CATEGORY_DELIMITER='|',AFTER_PREFIX='~AFTER~',WILD_TYPE_RE=/(.*?)(:)(.*?)/,_wildType=Y.cached(function(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['48']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['302']++;return type.replace(WILD_TYPE_RE,'*$2$3');}),_getType=function(type,pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['49']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['303']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['107'][0]++,!pre)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['107'][1]++,type.indexOf(PREFIX_DELIMITER)>-1)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['106'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['304']++;return type;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['106'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['305']++;return pre+PREFIX_DELIMITER+type;},_parseType=Y.cached(function(type,pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['50']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['306']++;var t=type,detachcategory,after,i;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['307']++;if(!L.isString(t)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['108'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['308']++;return t;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['108'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['309']++;i=t.indexOf(AFTER_PREFIX);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['310']++;if(i>-1){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['109'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['311']++;after=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['312']++;t=t.substr(AFTER_PREFIX.length);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['109'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['313']++;i=t.indexOf(CATEGORY_DELIMITER);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['314']++;if(i>-1){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['110'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['315']++;detachcategory=t.substr(0,i);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['316']++;t=t.substr(i+1);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['317']++;if(t==='*'){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['111'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['318']++;t=null;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['111'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['110'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['319']++;return[detachcategory,pre?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['112'][0]++,_getType(t,pre)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['112'][1]++,t),after,t];}),ET=function(opts){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['51']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['320']++;var etState=this._yuievt,etConfig;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['321']++;if(!etState){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['113'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['322']++;etState=this._yuievt={events:{},targets:null,config:{host:this,context:this},chain:Y.config.chain};}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['113'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['323']++;etConfig=etState.config;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['324']++;if(opts){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['114'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['325']++;mixConfigs(etConfig,opts,true);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['326']++;if(opts.chain!==undefined){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['115'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['327']++;etState.chain=opts.chain;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['115'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['328']++;if(opts.prefix){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['116'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['329']++;etConfig.prefix=opts.prefix;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['116'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['114'][1]++;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['330']++;ET.prototype={constructor:ET,once:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['52']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['331']++;var handle=this.on.apply(this,arguments);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['332']++;handle.batch(function(hand){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['53']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['333']++;if(hand.sub){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['117'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['334']++;hand.sub.once=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['117'][1]++;}});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['335']++;return handle;},onceAfter:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['54']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['336']++;var handle=this.after.apply(this,arguments);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['337']++;handle.batch(function(hand){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['55']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['338']++;if(hand.sub){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['118'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['339']++;hand.sub.once=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['118'][1]++;}});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['340']++;return handle;},parseType:function(type,pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['56']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['341']++;return _parseType(type,(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['119'][0]++,pre)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['119'][1]++,this._yuievt.config.prefix));},on:function(type,fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['57']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['342']++;var yuievt=this._yuievt,parts=_parseType(type,yuievt.config.prefix),f,c,args,ret,ce,detachcategory,handle,store=Y.Env.evt.handles,after,adapt,shorttype,Node=Y.Node,n,domevent,isArr;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['343']++;this._monitor('attach',parts[1],{args:arguments,category:parts[0],after:parts[2]});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['344']++;if(L.isObject(type)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['120'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['345']++;if(L.isFunction(type)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['121'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['346']++;return Y.Do.before.apply(Y.Do,arguments);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['121'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['347']++;f=fn;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['348']++;c=context;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['349']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['350']++;ret=[];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['351']++;if(L.isArray(type)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['122'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['352']++;isArr=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['122'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['353']++;after=type._after;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['354']++;delete type._after;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['355']++;Y.each(type,function(v,k){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['58']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['356']++;if(L.isObject(v)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['123'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['357']++;f=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['124'][0]++,v.fn)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['124'][1]++,L.isFunction(v)?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['125'][0]++,v):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['125'][1]++,f));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['358']++;c=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['126'][0]++,v.context)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['126'][1]++,c);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['123'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['359']++;var nv=after?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['127'][0]++,AFTER_PREFIX):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['127'][1]++,'');__cov_0ShtDtxkEapLmfzOgrY8Kw.s['360']++;args[0]=nv+(isArr?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['128'][0]++,v):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['128'][1]++,k));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['361']++;args[1]=f;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['362']++;args[2]=c;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['363']++;ret.push(this.on.apply(this,args));},this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['364']++;return yuievt.chain?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['129'][0]++,this):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['129'][1]++,new Y.EventHandle(ret));}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['120'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['365']++;detachcategory=parts[0];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['366']++;after=parts[2];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['367']++;shorttype=parts[3];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['368']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['131'][0]++,Node)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['131'][1]++,Y.instanceOf(this,Node))&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['131'][2]++,shorttype in Node.DOM_EVENTS)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['130'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['369']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['370']++;args.splice(2,0,Node.getDOMNode(this));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['371']++;return Y.on.apply(Y,args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['130'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['372']++;type=parts[1];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['373']++;if(Y.instanceOf(this,YUI)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['132'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['374']++;adapt=Y.Env.evt.plugins[type];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['375']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['376']++;args[0]=shorttype;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['377']++;if(Node){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['133'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['378']++;n=args[2];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['379']++;if(Y.instanceOf(n,Y.NodeList)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['134'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['380']++;n=Y.NodeList.getDOMNodes(n);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['134'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['381']++;if(Y.instanceOf(n,Node)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['135'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['382']++;n=Node.getDOMNode(n);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['135'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['383']++;domevent=shorttype in Node.DOM_EVENTS;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['384']++;if(domevent){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['136'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['385']++;args[2]=n;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['136'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['133'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['386']++;if(adapt){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['137'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['387']++;handle=adapt.on.apply(Y,args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['137'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['388']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['139'][0]++,!type)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['139'][1]++,domevent)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['138'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['389']++;handle=Y.Event._attach(args);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['138'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['132'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['390']++;if(!handle){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['140'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['391']++;ce=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['141'][0]++,yuievt.events[type])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['141'][1]++,this.publish(type));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['392']++;handle=ce._on(fn,context,arguments.length>3?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['142'][0]++,nativeSlice.call(arguments,3)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['142'][1]++,null),after?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['143'][0]++,'after'):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['143'][1]++,true));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['393']++;if(type.indexOf('*:')!==-1){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['144'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['394']++;this._hasSiblings=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['144'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['140'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['395']++;if(detachcategory){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['145'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['396']++;store[detachcategory]=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['146'][0]++,store[detachcategory])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['146'][1]++,{});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['397']++;store[detachcategory][type]=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['147'][0]++,store[detachcategory][type])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['147'][1]++,[]);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['398']++;store[detachcategory][type].push(handle);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['145'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['399']++;return yuievt.chain?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['148'][0]++,this):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['148'][1]++,handle);},subscribe:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['59']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['400']++;return this.on.apply(this,arguments);},detach:function(type,fn,context){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['60']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['401']++;var evts=this._yuievt.events,i,Node=Y.Node,isNode=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['149'][0]++,Node)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['149'][1]++,Y.instanceOf(this,Node));__cov_0ShtDtxkEapLmfzOgrY8Kw.s['402']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['151'][0]++,!type)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['151'][1]++,this!==Y)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['150'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['403']++;for(i in evts){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['404']++;if(evts.hasOwnProperty(i)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['152'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['405']++;evts[i].detach(fn,context);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['152'][1]++;}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['406']++;if(isNode){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['153'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['407']++;Y.Event.purgeElement(Node.getDOMNode(this));}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['153'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['408']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['150'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['409']++;var parts=_parseType(type,this._yuievt.config.prefix),detachcategory=L.isArray(parts)?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['154'][0]++,parts[0]):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['154'][1]++,null),shorttype=parts?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['155'][0]++,parts[3]):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['155'][1]++,null),adapt,store=Y.Env.evt.handles,detachhost,cat,args,ce,keyDetacher=function(lcat,ltype,host){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['61']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['410']++;var handles=lcat[ltype],ce,i;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['411']++;if(handles){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['156'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['412']++;for(i=handles.length-1;i>=0;--i){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['413']++;ce=handles[i].evt;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['414']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['158'][0]++,ce.host===host)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['158'][1]++,ce.el===host)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['157'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['415']++;handles[i].detach();}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['157'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['156'][1]++;}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['416']++;if(detachcategory){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['159'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['417']++;cat=store[detachcategory];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['418']++;type=parts[1];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['419']++;detachhost=isNode?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['160'][0]++,Y.Node.getDOMNode(this)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['160'][1]++,this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['420']++;if(cat){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['161'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['421']++;if(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['162'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['422']++;keyDetacher(cat,type,detachhost);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['162'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['423']++;for(i in cat){__cov_0ShtDtxkEapLmfzOgrY8Kw.s['424']++;if(cat.hasOwnProperty(i)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['163'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['425']++;keyDetacher(cat,i,detachhost);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['163'][1]++;}}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['426']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['161'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['159'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['427']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['165'][0]++,L.isObject(type))&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['165'][1]++,type.detach)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['164'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['428']++;type.detach();__cov_0ShtDtxkEapLmfzOgrY8Kw.s['429']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['164'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['430']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['167'][0]++,isNode)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['167'][1]++,!shorttype)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['167'][2]++,shorttype in Node.DOM_EVENTS))){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['166'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['431']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['432']++;args[2]=Node.getDOMNode(this);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['433']++;Y.detach.apply(Y,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['434']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['166'][1]++;}}}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['435']++;adapt=Y.Env.evt.plugins[shorttype];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['436']++;if(Y.instanceOf(this,YUI)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['168'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['437']++;args=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['438']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['170'][0]++,adapt)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['170'][1]++,adapt.detach)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['169'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['439']++;adapt.detach.apply(Y,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['440']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['169'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['441']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['172'][0]++,!type)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['172'][1]++,!adapt)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['172'][2]++,Node)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['172'][3]++,type in Node.DOM_EVENTS)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['171'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['442']++;args[0]=type;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['443']++;Y.Event.detach.apply(Y.Event,args);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['444']++;return this;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['171'][1]++;}}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['168'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['445']++;ce=evts[parts[1]];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['446']++;if(ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['173'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['447']++;ce.detach(fn,context);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['173'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['448']++;return this;},unsubscribe:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['62']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['449']++;return this.detach.apply(this,arguments);},detachAll:function(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['63']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['450']++;return this.detach(type);},unsubscribeAll:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['64']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['451']++;return this.detachAll.apply(this,arguments);},publish:function(type,opts){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['65']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['452']++;var ret,etState=this._yuievt,etConfig=etState.config,pre=etConfig.prefix;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['453']++;if(typeof type==='string'){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['174'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['454']++;if(pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['175'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['455']++;type=_getType(type,pre);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['175'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['456']++;ret=this._publish(type,etConfig,opts);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['174'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['457']++;ret={};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['458']++;Y.each(type,function(v,k){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['66']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['459']++;if(pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['176'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['460']++;k=_getType(k,pre);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['176'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['461']++;ret[k]=this._publish(k,etConfig,(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['177'][0]++,v)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['177'][1]++,opts));},this);}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['462']++;return ret;},_getFullType:function(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['67']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['463']++;var pre=this._yuievt.config.prefix;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['464']++;if(pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['178'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['465']++;return pre+PREFIX_DELIMITER+type;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['178'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['466']++;return type;}},_publish:function(fullType,etOpts,ceOpts){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['68']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['467']++;var ce,etState=this._yuievt,etConfig=etState.config,host=etConfig.host,context=etConfig.context,events=etState.events;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['468']++;ce=events[fullType];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['469']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['180'][0]++,etConfig.monitored)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['180'][1]++,!ce)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['180'][2]++,ce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['180'][3]++,ce.monitored)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['179'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['470']++;this._monitor('publish',fullType,{args:arguments});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['179'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['471']++;if(!ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['181'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['472']++;ce=events[fullType]=new Y.CustomEvent(fullType,etOpts);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['473']++;if(!etOpts){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['182'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['474']++;ce.host=host;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['475']++;ce.context=context;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['182'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['181'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['476']++;if(ceOpts){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['183'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['477']++;mixConfigs(ce,ceOpts,true);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['183'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['478']++;return ce;},_monitor:function(what,eventType,o){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['69']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['479']++;var monitorevt,ce,type;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['480']++;if(eventType){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['184'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['481']++;if(typeof eventType==='string'){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['185'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['482']++;type=eventType;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['483']++;ce=this.getEvent(eventType,true);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['185'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['484']++;ce=eventType;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['485']++;type=eventType.type;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['486']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][0]++,this._yuievt.config.monitored)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][1]++,!ce)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][2]++,ce.monitored))||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][3]++,ce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['187'][4]++,ce.monitored)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['186'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['487']++;monitorevt=type+'_'+what;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['488']++;o.monitored=what;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['489']++;this.fire.call(this,monitorevt,o);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['186'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['184'][1]++;}},fire:function(type){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['70']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['490']++;var typeIncluded=typeof type==='string',argCount=arguments.length,t=type,yuievt=this._yuievt,etConfig=yuievt.config,pre=etConfig.prefix,ret,ce,ce2,args;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['491']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['189'][0]++,typeIncluded)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['189'][1]++,argCount<=2)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['188'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['492']++;if(argCount===2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['190'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['493']++;args=[arguments[1]];}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['190'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['494']++;args=[];}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['188'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['495']++;args=nativeSlice.call(arguments,typeIncluded?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['191'][0]++,1):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['191'][1]++,0));}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['496']++;if(!typeIncluded){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['192'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['497']++;t=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['193'][0]++,type)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['193'][1]++,type.type);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['192'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['498']++;if(pre){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['194'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['499']++;t=_getType(t,pre);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['194'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['500']++;ce=yuievt.events[t];__cov_0ShtDtxkEapLmfzOgrY8Kw.s['501']++;if(this._hasSiblings){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['195'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['502']++;ce2=this.getSibling(t,ce);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['503']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['197'][0]++,ce2)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['197'][1]++,!ce)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['196'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['504']++;ce=this.publish(t);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['196'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['195'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['505']++;if((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['199'][0]++,etConfig.monitored)&&((__cov_0ShtDtxkEapLmfzOgrY8Kw.b['199'][1]++,!ce)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['199'][2]++,ce.monitored))||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['199'][3]++,ce)&&(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['199'][4]++,ce.monitored)){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['198'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['506']++;this._monitor('fire',(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['200'][0]++,ce)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['200'][1]++,t),{args:args});}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['198'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['507']++;if(!ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['201'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['508']++;if(yuievt.hasTargets){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['202'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['509']++;return this.bubble({type:t},args,this);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['202'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['510']++;ret=true;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['201'][1]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['511']++;if(ce2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['203'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['512']++;ce.sibling=ce2;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['203'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['513']++;ret=ce._fire(args);}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['514']++;return yuievt.chain?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['204'][0]++,this):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['204'][1]++,ret);},getSibling:function(type,ce){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['71']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['515']++;var ce2;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['516']++;if(type.indexOf(PREFIX_DELIMITER)>-1){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['205'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['517']++;type=_wildType(type);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['518']++;ce2=this.getEvent(type,true);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['519']++;if(ce2){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['206'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['520']++;ce2.applyConfig(ce);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['521']++;ce2.bubbles=false;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['522']++;ce2.broadcast=0;}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['206'][1]++;}}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['205'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['523']++;return ce2;},getEvent:function(type,prefixed){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['72']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['524']++;var pre,e;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['525']++;if(!prefixed){__cov_0ShtDtxkEapLmfzOgrY8Kw.b['207'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['526']++;pre=this._yuievt.config.prefix;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['527']++;type=pre?(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['208'][0]++,_getType(type,pre)):(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['208'][1]++,type);}else{__cov_0ShtDtxkEapLmfzOgrY8Kw.b['207'][1]++;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['528']++;e=this._yuievt.events;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['529']++;return(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['209'][0]++,e[type])||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['209'][1]++,null);},after:function(type,fn){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['73']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['530']++;var a=nativeSlice.call(arguments,0);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['531']++;switch(L.type(type)){case'function':__cov_0ShtDtxkEapLmfzOgrY8Kw.b['210'][0]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['532']++;return Y.Do.after.apply(Y.Do,arguments);case'array':__cov_0ShtDtxkEapLmfzOgrY8Kw.b['210'][1]++;case'object':__cov_0ShtDtxkEapLmfzOgrY8Kw.b['210'][2]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['533']++;a[0]._after=true;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['534']++;break;default:__cov_0ShtDtxkEapLmfzOgrY8Kw.b['210'][3]++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['535']++;a[0]=AFTER_PREFIX+type;}__cov_0ShtDtxkEapLmfzOgrY8Kw.s['536']++;return this.on.apply(this,a);},before:function(){__cov_0ShtDtxkEapLmfzOgrY8Kw.f['74']++;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['537']++;return this.on.apply(this,arguments);}};__cov_0ShtDtxkEapLmfzOgrY8Kw.s['538']++;Y.EventTarget=ET;__cov_0ShtDtxkEapLmfzOgrY8Kw.s['539']++;Y.mix(Y,ET.prototype);__cov_0ShtDtxkEapLmfzOgrY8Kw.s['540']++;ET.call(Y,{bubbles:false});__cov_0ShtDtxkEapLmfzOgrY8Kw.s['541']++;YUI.Env.globalEvents=(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['211'][0]++,YUI.Env.globalEvents)||(__cov_0ShtDtxkEapLmfzOgrY8Kw.b['211'][1]++,new ET());__cov_0ShtDtxkEapLmfzOgrY8Kw.s['542']++;Y.Global=YUI.Env.globalEvents;},'@VERSION@',{'requires':['oop']});
source/demo/NavLink.js
cesarandreu/react-virtualized
/** @flow */ import React from 'react' import { Link } from 'react-router' import Icon from './Icon' import styles from './NavLink.css' export default function NavLink ({ children, href, iconType, to }) { let link let icon if (iconType) { icon = ( <Icon className={styles.Icon} type={iconType} /> ) } if (to) { link = ( <Link activeClassName={styles.ActiveNavLink} className={styles.NavLink} to={to} > {icon} {children} </Link> ) } else { link = ( <a className={styles.NavLink} href={href} > {icon} {children} </a> ) } return ( <li className={styles.NavListItem}> {link} </li> ) }
ajax/libs/ionic/0.9.25/js/ionic.js
gasolin/cdnjs
/*! * Copyright 2014 Drifty Co. * http://drifty.com/ * * Ionic, v0.9.25 * A powerful HTML5 mobile app framework. * http://ionicframework.com/ * * By @maxlynch, @helloimben, @adamdbradley <3 * * Licensed under the MIT license. Please see LICENSE for more information. * */ ; // Create namespaces window.ionic = { controllers: {}, views: {}, version: '0.9.25' }; ; (function(ionic) { var bezierCoord = function (x,y) { if(!x) x=0; if(!y) y=0; return {x: x, y: y}; }; function B1(t) { return t*t*t; } function B2(t) { return 3*t*t*(1-t); } function B3(t) { return 3*t*(1-t)*(1-t); } function B4(t) { return (1-t)*(1-t)*(1-t); } ionic.Animator = { // Quadratic bezier solver getQuadraticBezier: function(percent,C1,C2,C3,C4) { var pos = new bezierCoord(); pos.x = C1.x*B1(percent) + C2.x*B2(percent) + C3.x*B3(percent) + C4.x*B4(percent); pos.y = C1.y*B1(percent) + C2.y*B2(percent) + C3.y*B3(percent) + C4.y*B4(percent); return pos; }, // Cubic bezier solver from https://github.com/arian/cubic-bezier (MIT) getCubicBezier: function(x1, y1, x2, y2, duration) { // Precision epsilon = (1000 / 60 / duration) / 4; var curveX = function(t){ var v = 1 - t; return 3 * v * v * t * x1 + 3 * v * t * t * x2 + t * t * t; }; var curveY = function(t){ var v = 1 - t; return 3 * v * v * t * y1 + 3 * v * t * t * y2 + t * t * t; }; var derivativeCurveX = function(t){ var v = 1 - t; return 3 * (2 * (t - 1) * t + v * v) * x1 + 3 * (- t * t * t + 2 * v * t) * x2; }; return function(t) { var x = t, t0, t1, t2, x2, d2, i; // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; i++){ x2 = curveX(t2) - x; if (Math.abs(x2) < epsilon) return curveY(t2); d2 = derivativeCurveX(t2); if (Math.abs(d2) < 1e-6) break; t2 = t2 - x2 / d2; } t0 = 0, t1 = 1, t2 = x; if (t2 < t0) return curveY(t0); if (t2 > t1) return curveY(t1); // Fallback to the bisection method for reliability. while (t0 < t1){ x2 = curveX(t2); if (Math.abs(x2 - x) < epsilon) return curveY(t2); if (x > x2) t0 = t2; else t1 = t2; t2 = (t1 - t0) * 0.5 + t0; } // Failure return curveY(t2); }; }, animate: function(element, className, fn) { return { leave: function() { var endFunc = function() { element.classList.remove('leave'); element.classList.remove('leave-active'); element.removeEventListener('webkitTransitionEnd', endFunc); element.removeEventListener('transitionEnd', endFunc); }; element.addEventListener('webkitTransitionEnd', endFunc); element.addEventListener('transitionEnd', endFunc); element.classList.add('leave'); element.classList.add('leave-active'); return this; }, enter: function() { var endFunc = function() { element.classList.remove('enter'); element.classList.remove('enter-active'); element.removeEventListener('webkitTransitionEnd', endFunc); element.removeEventListener('transitionEnd', endFunc); }; element.addEventListener('webkitTransitionEnd', endFunc); element.addEventListener('transitionEnd', endFunc); element.classList.add('enter'); element.classList.add('enter-active'); return this; } }; } }; })(ionic); ; (function(ionic) { var readyCallbacks = [], domReady = function() { for(var x=0; x<readyCallbacks.length; x++) { ionic.requestAnimationFrame(readyCallbacks[x]); } readyCallbacks = []; document.removeEventListener('DOMContentLoaded', domReady); }; document.addEventListener('DOMContentLoaded', domReady); // From the man himself, Mr. Paul Irish. // The requestAnimationFrame polyfill // Put it on window just to preserve its context // without having to use .call window._rAF = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 16); }; })(); ionic.DomUtil = { //Call with proper context requestAnimationFrame: function(cb) { window._rAF(cb); }, /* * When given a callback, if that callback is called 100 times between * animation frames, Throttle will make it only call the last of 100tha call * * It returns a function, which will then call the passed in callback. The * passed in callback will receive the context the returned function is called with. * * @example * this.setTranslateX = ionic.animationFrameThrottle(function(x) { * this.el.style.webkitTransform = 'translate3d(' + x + 'px, 0, 0)'; * }) */ animationFrameThrottle: function(cb) { var args, isQueued, context; return function() { args = arguments; context = this; if (!isQueued) { isQueued = true; ionic.requestAnimationFrame(function() { cb.apply(context, args); isQueued = false; }); } }; }, /* * Find an element's offset, then add it to the offset of the parent * until we are at the direct child of parentEl * use-case: find scroll offset of any element within a scroll container */ getPositionInParent: function(el) { return { left: el.offsetLeft, top: el.offsetTop }; }, ready: function(cb) { if(document.readyState === "complete") { ionic.requestAnimationFrame(cb); } else { readyCallbacks.push(cb); } }, getTextBounds: function(textNode) { if(document.createRange) { var range = document.createRange(); range.selectNodeContents(textNode); if(range.getBoundingClientRect) { var rect = range.getBoundingClientRect(); if(rect) { var sx = window.scrollX; var sy = window.scrollY; return { top: rect.top + sy, left: rect.left + sx, right: rect.left + sx + rect.width, bottom: rect.top + sy + rect.height, width: rect.width, height: rect.height }; } } } return null; }, getChildIndex: function(element, type) { if(type) { var ch = element.parentNode.children; var c; for(var i = 0, k = 0, j = ch.length; i < j; i++) { c = ch[i]; if(c.nodeName && c.nodeName.toLowerCase() == type) { if(c == element) { return k; } k++; } } } return Array.prototype.slice.call(element.parentNode.children).indexOf(element); }, swapNodes: function(src, dest) { dest.parentNode.insertBefore(src, dest); }, /** * {returns} the closest parent matching the className */ getParentWithClass: function(e, className) { while(e.parentNode) { if(e.parentNode.classList && e.parentNode.classList.contains(className)) { return e.parentNode; } e = e.parentNode; } return null; }, /** * {returns} the closest parent or self matching the className */ getParentOrSelfWithClass: function(e, className) { while(e) { if(e.classList && e.classList.contains(className)) { return e; } e = e.parentNode; } return null; }, rectContains: function(x, y, x1, y1, x2, y2) { if(x < x1 || x > x2) return false; if(y < y1 || y > y2) return false; return true; } }; //Shortcuts ionic.requestAnimationFrame = ionic.DomUtil.requestAnimationFrame; ionic.animationFrameThrottle = ionic.DomUtil.animationFrameThrottle; })(window.ionic); ; /** * ion-events.js * * Author: Max Lynch <[email protected]> * * Framework events handles various mobile browser events, and * detects special events like tap/swipe/etc. and emits them * as custom events that can be used in an app. * * Portions lovingly adapted from github.com/maker/ratchet and github.com/alexgibson/tap.js - thanks guys! */ (function(ionic) { // Custom event polyfill if(!window.CustomEvent) { (function() { var CustomEvent; CustomEvent = function(event, params) { var evt; params = params || { bubbles: false, cancelable: false, detail: undefined }; try { evt = document.createEvent("CustomEvent"); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); } catch (error) { // fallback for browsers that don't support createEvent('CustomEvent') evt = document.createEvent("Event"); for (var param in params) { evt[param] = params[param]; } evt.initEvent(event, params.bubbles, params.cancelable); } return evt; }; CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent; })(); } ionic.EventController = { VIRTUALIZED_EVENTS: ['tap', 'swipe', 'swiperight', 'swipeleft', 'drag', 'hold', 'release'], // Trigger a new event trigger: function(eventType, data, bubbles, cancelable) { var event = new CustomEvent(eventType, { detail: data, bubbles: !!bubbles, cancelable: !!cancelable }); // Make sure to trigger the event on the given target, or dispatch it from // the window if we don't have an event target data && data.target && data.target.dispatchEvent(event) || window.dispatchEvent(event); }, // Bind an event on: function(type, callback, element) { var e = element || window; // Bind a gesture if it's a virtual event for(var i = 0, j = this.VIRTUALIZED_EVENTS.length; i < j; i++) { if(type == this.VIRTUALIZED_EVENTS[i]) { var gesture = new ionic.Gesture(element); gesture.on(type, callback); return gesture; } } // Otherwise bind a normal event e.addEventListener(type, callback); }, off: function(type, callback, element) { element.removeEventListener(type, callback); }, // Register for a new gesture event on the given element onGesture: function(type, callback, element) { var gesture = new ionic.Gesture(element); gesture.on(type, callback); return gesture; }, // Unregister a previous gesture event offGesture: function(gesture, type, callback) { gesture.off(type, callback); }, handlePopState: function(event) { }, }; // Map some convenient top-level functions for event handling ionic.on = function() { ionic.EventController.on.apply(ionic.EventController, arguments); }; ionic.off = function() { ionic.EventController.off.apply(ionic.EventController, arguments); }; ionic.trigger = ionic.EventController.trigger;//function() { ionic.EventController.trigger.apply(ionic.EventController.trigger, arguments); }; ionic.onGesture = function() { return ionic.EventController.onGesture.apply(ionic.EventController.onGesture, arguments); }; ionic.offGesture = function() { return ionic.EventController.offGesture.apply(ionic.EventController.offGesture, arguments); }; })(window.ionic); ; /** * Simple gesture controllers with some common gestures that emit * gesture events. * * Ported from github.com/EightMedia/hammer.js Gestures - thanks! */ (function(ionic) { /** * ionic.Gestures * use this to create instances * @param {HTMLElement} element * @param {Object} options * @returns {ionic.Gestures.Instance} * @constructor */ ionic.Gesture = function(element, options) { return new ionic.Gestures.Instance(element, options || {}); }; ionic.Gestures = {}; // default settings ionic.Gestures.defaults = { // add styles and attributes to the element to prevent the browser from doing // its native behavior. this doesnt prevent the scrolling, but cancels // the contextmenu, tap highlighting etc // set to false to disable this stop_browser_behavior: { // this also triggers onselectstart=false for IE userSelect: 'none', // this makes the element blocking in IE10 >, you could experiment with the value // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241 touchAction: 'none', touchCallout: 'none', contentZooming: 'none', userDrag: 'none', tapHighlightColor: 'rgba(0,0,0,0)' } // more settings are defined per gesture at gestures.js }; // detect touchevents ionic.Gestures.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled; ionic.Gestures.HAS_TOUCHEVENTS = ('ontouchstart' in window); // dont use mouseevents on mobile devices ionic.Gestures.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i; ionic.Gestures.NO_MOUSEEVENTS = ionic.Gestures.HAS_TOUCHEVENTS && window.navigator.userAgent.match(ionic.Gestures.MOBILE_REGEX); // eventtypes per touchevent (start, move, end) // are filled by ionic.Gestures.event.determineEventTypes on setup ionic.Gestures.EVENT_TYPES = {}; // direction defines ionic.Gestures.DIRECTION_DOWN = 'down'; ionic.Gestures.DIRECTION_LEFT = 'left'; ionic.Gestures.DIRECTION_UP = 'up'; ionic.Gestures.DIRECTION_RIGHT = 'right'; // pointer type ionic.Gestures.POINTER_MOUSE = 'mouse'; ionic.Gestures.POINTER_TOUCH = 'touch'; ionic.Gestures.POINTER_PEN = 'pen'; // touch event defines ionic.Gestures.EVENT_START = 'start'; ionic.Gestures.EVENT_MOVE = 'move'; ionic.Gestures.EVENT_END = 'end'; // hammer document where the base events are added at ionic.Gestures.DOCUMENT = window.document; // plugins namespace ionic.Gestures.plugins = {}; // if the window events are set... ionic.Gestures.READY = false; /** * setup events to detect gestures on the document */ function setup() { if(ionic.Gestures.READY) { return; } // find what eventtypes we add listeners to ionic.Gestures.event.determineEventTypes(); // Register all gestures inside ionic.Gestures.gestures for(var name in ionic.Gestures.gestures) { if(ionic.Gestures.gestures.hasOwnProperty(name)) { ionic.Gestures.detection.register(ionic.Gestures.gestures[name]); } } // Add touch events on the document ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_MOVE, ionic.Gestures.detection.detect); ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_END, ionic.Gestures.detection.detect); // ionic.Gestures is ready...! ionic.Gestures.READY = true; } /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * @param {HTMLElement} element * @param {Object} [options={}] * @returns {ionic.Gestures.Instance} * @name Gesture.Instance * @constructor */ ionic.Gestures.Instance = function(element, options) { var self = this; // A null element was passed into the instance, which means // whatever lookup was done to find this element failed to find it // so we can't listen for events on it. if(element === null) { console.error('Null element passed to gesture (element does not exist). Not listening for gesture'); return; } // setup ionic.GesturesJS window events and register all gestures // this also sets up the default options setup(); this.element = element; // start/stop detection option this.enabled = true; // merge options this.options = ionic.Gestures.utils.extend( ionic.Gestures.utils.extend({}, ionic.Gestures.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.stop_browser_behavior) { ionic.Gestures.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior); } // start detection on touchstart ionic.Gestures.event.onTouch(element, ionic.Gestures.EVENT_START, function(ev) { if(self.enabled) { ionic.Gestures.detection.startDetect(self, ev); } }); // return instance return this; }; ionic.Gestures.Instance.prototype = { /** * bind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ on: function onEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.addEventListener(gestures[t], handler, false); } return this; }, /** * unbind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ off: function offEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.removeEventListener(gestures[t], handler, false); } return this; }, /** * trigger gesture event * @param {String} gesture * @param {Object} eventData * @returns {ionic.Gestures.Instance} */ trigger: function triggerEvent(gesture, eventData){ // create DOM event var event = ionic.Gestures.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(ionic.Gestures.utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @param {Boolean} state * @returns {ionic.Gestures.Instance} */ enable: function enable(state) { this.enabled = state; return this; } }; /** * this holds the last move event, * used to fix empty touchend issue * see the onTouch event for an explanation * @type {Object} */ var last_move_event = null; /** * when the mouse is hold down, this is true * @type {Boolean} */ var enable_detect = false; /** * when touch events have been fired, this is true * @type {Boolean} */ var touch_triggered = false; ionic.Gestures.event = { /** * simple addEventListener * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ bindDom: function(element, type, handler) { var types = type.split(' '); for(var t=0; t<types.length; t++) { element.addEventListener(types[t], handler, false); } }, /** * touch events with mouse fallback * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Function} handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; this.bindDom(element, ionic.Gestures.EVENT_TYPES[eventType], function bindDomOnTouch(ev) { var sourceEventType = ev.type.toLowerCase(); // onmouseup, but when touchend has been fired we do nothing. // this is for touchdevices which also fire a mouseup on touchend if(sourceEventType.match(/mouse/) && touch_triggered) { return; } // mousebutton must be down or a touch event else if( sourceEventType.match(/touch/) || // touch events are always on screen sourceEventType.match(/pointerdown/) || // pointerevents touch (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed ){ enable_detect = true; } // mouse isn't pressed else if(sourceEventType.match(/mouse/) && ev.which !== 1) { enable_detect = false; } // we are in a touch event, set the touch triggered bool to true, // this for the conflicts that may occur on ios and android if(sourceEventType.match(/touch|pointer/)) { touch_triggered = true; } // count the total touches on the screen var count_touches = 0; // when touch has been triggered in this detection session // and we are now handling a mouse event, we stop that to prevent conflicts if(enable_detect) { // update pointerevent if(ionic.Gestures.HAS_POINTEREVENTS && eventType != ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } // touch else if(sourceEventType.match(/touch/)) { count_touches = ev.touches.length; } // mouse else if(!touch_triggered) { count_touches = sourceEventType.match(/up/) ? 0 : 1; } // if we are in a end event, but when we remove one touch and // we still have enough, set eventType to move if(count_touches > 0 && eventType == ionic.Gestures.EVENT_END) { eventType = ionic.Gestures.EVENT_MOVE; } // no touches, force the end event else if(!count_touches) { eventType = ionic.Gestures.EVENT_END; } // store the last move event if(count_touches || last_move_event === null) { last_move_event = ev; } // trigger the handler handler.call(ionic.Gestures.detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev)); // remove pointerevent from list if(ionic.Gestures.HAS_POINTEREVENTS && eventType == ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } } //debug(sourceEventType +" "+ eventType); // on the end we reset everything if(!count_touches) { last_move_event = null; enable_detect = false; touch_triggered = false; ionic.Gestures.PointerEvent.reset(); } }); }, /** * we have different events for each device/browser * determine what we need and set them in the ionic.Gestures.EVENT_TYPES constant */ determineEventTypes: function determineEventTypes() { // determine the eventtype we want to set var types; // pointerEvents magic if(ionic.Gestures.HAS_POINTEREVENTS) { types = ionic.Gestures.PointerEvent.getEvents(); } // on Android, iOS, blackberry, windows mobile we dont want any mouseevents else if(ionic.Gestures.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel']; } // for non pointer events browsers and mixed browsers, // like chrome on windows8 touch laptop else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup']; } ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_START] = types[0]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_MOVE] = types[1]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_END] = types[2]; }, /** * create touchlist depending on the event * @param {Object} ev * @param {String} eventType used by the fakemultitouch plugin */ getTouchList: function getTouchList(ev/*, eventType*/) { // get the fake pointerEvent touchlist if(ionic.Gestures.HAS_POINTEREVENTS) { return ionic.Gestures.PointerEvent.getTouchList(); } // get the touchlist else if(ev.touches) { return ev.touches; } // make fake touchlist from mouse position else { ev.indentifier = 1; return [ev]; } }, /** * collect event data for ionic.Gestures js * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Object} eventData */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = ionic.Gestures.POINTER_TOUCH; if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) { pointerType = ionic.Gestures.POINTER_MOUSE; } return { center : ionic.Gestures.utils.getCenter(touches), timeStamp : new Date().getTime(), 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() { if(this.srcEvent.preventManipulation) { this.srcEvent.preventManipulation(); } if(this.srcEvent.preventDefault) { //this.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 ionic.Gestures.detection.stopDetect(); } }; } }; ionic.Gestures.PointerEvent = { /** * holds all pointers * @type {Object} */ pointers: {}, /** * get a list of pointers * @returns {Array} touchlist */ getTouchList: function() { var self = this; var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Object.keys(self.pointers).sort().forEach(function(id) { touchlist.push(self.pointers[id]); }); return touchlist; }, /** * update the position of a pointer * @param {String} type ionic.Gestures.EVENT_END * @param {Object} pointerEvent */ updatePointer: function(type, pointerEvent) { if(type == ionic.Gestures.EVENT_END) { this.pointers = {}; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } return Object.keys(this.pointers).length; }, /** * check if ev matches pointertype * @param {String} pointerType ionic.Gestures.POINTER_MOUSE * @param {PointerEvent} ev */ matchType: function(pointerType, ev) { if(!ev.pointerType) { return false; } var types = {}; types[ionic.Gestures.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == ionic.Gestures.POINTER_MOUSE); types[ionic.Gestures.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == ionic.Gestures.POINTER_TOUCH); types[ionic.Gestures.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == ionic.Gestures.POINTER_PEN); return types[pointerType]; }, /** * get events */ getEvents: function() { return [ 'pointerdown MSPointerDown', 'pointermove MSPointerMove', 'pointerup pointercancel MSPointerUp MSPointerCancel' ]; }, /** * reset the list */ reset: function() { this.pointers = {}; } }; ionic.Gestures.utils = { /** * extend method, * also used for cloning when dest is an empty object * @param {Object} dest * @param {Object} src * @parm {Boolean} merge do a merge * @returns {Object} dest */ extend: function extend(dest, src, merge) { for (var key in src) { if(dest[key] !== undefined && merge) { continue; } dest[key] = src[key]; } return dest; }, /** * find if a node is in the given parent * used for event delegation tricks * @param {HTMLElement} node * @param {HTMLElement} parent * @returns {boolean} has_parent */ hasParent: function(node, parent) { while(node){ if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @param {Array} touches * @returns {Object} center */ getCenter: function getCenter(touches) { var valuesX = [], valuesY = []; for(var t= 0,len=touches.length; t<len; t++) { valuesX.push(touches[t].pageX); valuesY.push(touches[t].pageY); } return { pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2), pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2) }; }, /** * calculate the velocity between two points * @param {Number} delta_time * @param {Number} delta_x * @param {Number} delta_y * @returns {Object} velocity */ getVelocity: function getVelocity(delta_time, delta_x, delta_y) { return { x: Math.abs(delta_x / delta_time) || 0, y: Math.abs(delta_y / delta_time) || 0 }; }, /** * calculate the angle between two coordinates * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} angle */ getAngle: function getAngle(touch1, touch2) { var y = touch2.pageY - touch1.pageY, x = touch2.pageX - touch1.pageX; return Math.atan2(y, x) * 180 / Math.PI; }, /** * angle to direction define * @param {Touch} touch1 * @param {Touch} touch2 * @returns {String} direction constant, like ionic.Gestures.DIRECTION_LEFT */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.pageX - touch2.pageX), y = Math.abs(touch1.pageY - touch2.pageY); if(x >= y) { return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } else { return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } }, /** * calculate the distance between two touches * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.pageX - touch1.pageX, y = touch2.pageY - touch1.pageY; return Math.sqrt((x*x) + (y*y)); }, /** * calculate the scale factor between two touchLists (fingers) * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start * @param {Array} end * @returns {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 (fingers) * @param {Array} start * @param {Array} end * @returns {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; }, /** * boolean if the direction is vertical * @param {String} direction * @returns {Boolean} is_vertical */ isVertical: function isVertical(direction) { return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN); }, /** * stop browser default behavior with css props * @param {HtmlElement} element * @param {Object} css_props */ stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) { var prop, vendors = ['webkit','khtml','moz','Moz','ms','o','']; if(!css_props || !element.style) { return; } // with css properties for modern browsers for(var i = 0; i < vendors.length; i++) { for(var p in css_props) { if(css_props.hasOwnProperty(p)) { prop = p; // vender prefix at the property if(vendors[i]) { prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1); } // set the style element.style[prop] = css_props[p]; } } } // also the disable onselectstart if(css_props.userSelect == 'none') { element.onselectstart = function() { return false; }; } } }; ionic.Gestures.detection = { // contains all registred ionic.Gestures.gestures in the correct order gestures: [], // data of the current ionic.Gestures.gesture detection session current: null, // the previous ionic.Gestures.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 ionic.Gestures.gesture detection * @param {ionic.Gestures.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a ionic.Gestures.gesture detection on an element if(this.current) { return; } this.stopped = false; this.current = { inst : inst, // reference to ionic.GesturesInstance we're working for startEvent : ionic.Gestures.utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent : false, // last eventData name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * ionic.Gestures.gesture detection * @param {Object} eventData */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // instance options var inst_options = this.current.inst.options; // call ionic.Gestures.gesture handlers for(var g=0,len=this.gestures.length; g<len; g++) { var gesture = this.gestures[g]; // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, this.current.inst) === false) { this.stopDetect(); break; } } } // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // endevent, but not the last touch, so dont stop if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length-1) { this.stopDetect(); } return eventData; }, /** * clear the ionic.Gestures.gesture vars * this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected * to stop other ionic.Gestures.gestures from being fired */ 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 = ionic.Gestures.utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }, /** * extend eventData for ionic.Gestures.gestures * @param {Object} ev * @returns {Object} ev */ extendEventData: function extendEventData(ev) { var startEv = this.current.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; for(var i=0,len=ev.touches.length; i<len; i++) { startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i])); } } var delta_time = ev.timeStamp - startEv.timeStamp, delta_x = ev.center.pageX - startEv.center.pageX, delta_y = ev.center.pageY - startEv.center.pageY, velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y); ionic.Gestures.utils.extend(ev, { deltaTime : delta_time, deltaX : delta_x, deltaY : delta_y, velocityX : velocity.x, velocityY : velocity.y, distance : ionic.Gestures.utils.getDistance(startEv.center, ev.center), angle : ionic.Gestures.utils.getAngle(startEv.center, ev.center), direction : ionic.Gestures.utils.getDirection(startEv.center, ev.center), scale : ionic.Gestures.utils.getScale(startEv.touches, ev.touches), rotation : ionic.Gestures.utils.getRotation(startEv.touches, ev.touches), startEvent : startEv }); return ev; }, /** * register new gesture * @param {Object} gesture object, see gestures.js for documentation * @returns {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 ionic.Gestures default options with the ionic.Gestures.gesture options ionic.Gestures.utils.extend(ionic.Gestures.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add ionic.Gestures.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; } }; ionic.Gestures.gestures = ionic.Gestures.gestures || {}; /** * Custom gestures * ============================== * * Gesture object * -------------------- * The object structure of a gesture: * * { name: 'mygesture', * index: 1337, * defaults: { * mygesture_option: true * } * handler: function(type, ev, inst) { * // trigger gesture event * inst.trigger(this.name, ev); * } * } * @param {String} name * this should be the name of the gesture, lowercase * it is also being used to disable/enable the gesture per instance config. * * @param {Number} [index=1000] * the index of the gesture, where it is going to be in the stack of gestures detection * like when you build an gesture that depends on the drag gesture, it is a good * idea to place it after the index of the drag gesture. * * @param {Object} [defaults={}] * the default settings of the gesture. these are added to the instance settings, * and can be overruled per instance. you can also add the name of the gesture, * but this is also added by default (and set to true). * * @param {Function} handler * this handles the gesture detection of your custom gesture and receives the * following arguments: * * @param {Object} eventData * event data containing the following properties: * timeStamp {Number} time the event occurred * target {HTMLElement} target element * touches {Array} touches (fingers, pointers, mouse) on the screen * pointerType {String} kind of pointer that was used. matches ionic.Gestures.POINTER_MOUSE|TOUCH * center {Object} center position of the touches. contains pageX and pageY * deltaTime {Number} the total time of the touches in the screen * deltaX {Number} the delta on x axis we haved moved * deltaY {Number} the delta on y axis we haved moved * velocityX {Number} the velocity on the x * velocityY {Number} the velocity on y * angle {Number} the angle we are moving * direction {String} the direction we are moving. matches ionic.Gestures.DIRECTION_UP|DOWN|LEFT|RIGHT * distance {Number} the distance we haved moved * scale {Number} scaling of the touches, needs 2 touches * rotation {Number} rotation of the touches, needs 2 touches * * eventType {String} matches ionic.Gestures.EVENT_START|MOVE|END * srcEvent {Object} the source event, like TouchStart or MouseDown * * startEvent {Object} contains the same properties as above, * but from the first touch. this is used to calculate * distances, deltaTime, scaling etc * * @param {ionic.Gestures.Instance} inst * the instance we are doing the detection for. you can get the options from * the inst.options object and trigger the gesture event by calling inst.trigger * * * Handle gestures * -------------------- * inside the handler you can get/set ionic.Gestures.detectionic.current. This is the current * detection sessionic. It has the following properties * @param {String} name * contains the name of the gesture we have detected. it has not a real function, * only to check in other gestures if something is detected. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can * check if the current gesture is 'drag' by accessing ionic.Gestures.detectionic.current.name * * @readonly * @param {ionic.Gestures.Instance} inst * the instance we do the detection for * * @readonly * @param {Object} startEvent * contains the properties of the first gesture detection in this sessionic. * Used for calculations about timing, distance, etc. * * @readonly * @param {Object} lastEvent * contains all the properties of the last gesture detect in this sessionic. * * after the gesture detection session has been completed (user has released the screen) * the ionic.Gestures.detectionic.current object is copied into ionic.Gestures.detectionic.previous, * this is usefull for gestures like doubletap, where you need to know if the * previous gesture was a tap * * options that have been set by the instance can be received by calling inst.options * * You can trigger a gesture event by calling inst.trigger("mygesture", event). * The first param is the name of your gesture, the second the event argument * * * Register gestures * -------------------- * When an gesture is added to the ionic.Gestures.gestures object, it is auto registered * at the setup of the first ionic.Gestures instance. You can also call ionic.Gestures.detectionic.register * manually and pass your gesture object as a param * */ /** * Hold * Touch stays at the same place for x time * @events hold */ ionic.Gestures.gestures.Hold = { name: 'hold', index: 10, defaults: { hold_timeout : 500, hold_threshold : 1 }, timer: null, handler: function holdGesture(ev, inst) { switch(ev.eventType) { case ionic.Gestures.EVENT_START: // clear any running timers clearTimeout(this.timer); // set the gesture so we can check in the timeout if it still is ionic.Gestures.detection.current.name = this.name; // set timer and if after the timeout it still is hold, // we trigger the hold event this.timer = setTimeout(function() { if(ionic.Gestures.detection.current.name == 'hold') { inst.trigger('hold', ev); } }, inst.options.hold_timeout); break; // when you move or end we clear the timer case ionic.Gestures.EVENT_MOVE: if(ev.distance > inst.options.hold_threshold) { clearTimeout(this.timer); } break; case ionic.Gestures.EVENT_END: clearTimeout(this.timer); break; } } }; /** * Tap/DoubleTap * Quick touch at a place or double at the same place * @events tap, doubletap */ ionic.Gestures.gestures.Tap = { name: 'tap', index: 100, defaults: { tap_max_touchtime : 250, tap_max_distance : 10, tap_always : true, doubletap_distance : 20, doubletap_interval : 300 }, handler: function tapGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { // previous gesture, for the double tap since these are two different gesture detections var prev = ionic.Gestures.detection.previous, did_doubletap = false; // when the touchtime is higher then the max touch time // or when the moving distance is too much if(ev.deltaTime > inst.options.tap_max_touchtime || ev.distance > inst.options.tap_max_distance) { return; } // check if double tap if(prev && prev.name == 'tap' && (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval && ev.distance < inst.options.doubletap_distance) { inst.trigger('doubletap', ev); did_doubletap = true; } // do a single tap if(!did_doubletap || inst.options.tap_always) { ionic.Gestures.detection.current.name = 'tap'; inst.trigger(ionic.Gestures.detection.current.name, ev); } } } }; /** * Swipe * triggers swipe events when the end velocity is above the threshold * @events swipe, swipeleft, swiperight, swipeup, swipedown */ ionic.Gestures.gestures.Swipe = { name: 'swipe', index: 40, defaults: { // set 0 for unlimited, but this can conflict with transform swipe_max_touches : 1, swipe_velocity : 0.7 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { // max touches if(inst.options.swipe_max_touches > 0 && ev.touches.length > inst.options.swipe_max_touches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > inst.options.swipe_velocity || ev.velocityY > inst.options.swipe_velocity) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * Drag * Move with x fingers (default 1) around on the page. Blocking the scrolling when * moving left and right is a good practice. When all the drag events are blocking * you disable scrolling on that area. * @events drag, drapleft, dragright, dragup, dragdown */ ionic.Gestures.gestures.Drag = { name: 'drag', index: 50, defaults: { drag_min_distance : 10, // Set correct_for_drag_min_distance 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. correct_for_drag_min_distance : true, // set 0 for unlimited, but this can conflict with transform drag_max_touches : 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 drag_block_horizontal : true, drag_block_vertical : true, // drag_lock_to_axis keeps the drag gesture on the axis that it started on, // It disallows vertical directions if the initial direction was horizontal, and vice versa. drag_lock_to_axis : false, // drag lock only kicks in when distance > drag_lock_min_distance // This way, locking occurs only when the distance has become large enough to reliably determine the direction drag_lock_min_distance : 25 }, triggered: false, handler: function dragGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // max touches if(inst.options.drag_max_touches > 0 && ev.touches.length > inst.options.drag_max_touches) { return; } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.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.drag_min_distance && ionic.Gestures.detection.current.name != this.name) { return; } // we are dragging! if(ionic.Gestures.detection.current.name != this.name) { ionic.Gestures.detection.current.name = this.name; if (inst.options.correct_for_drag_min_distance) { // When a drag is triggered, set the event center to drag_min_distance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.drag_min_distance/ev.distance); ionic.Gestures.detection.current.startEvent.center.pageX += ev.deltaX * factor; ionic.Gestures.detection.current.startEvent.center.pageY += ev.deltaY * factor; // recalculate event data using new start point ev = ionic.Gestures.detection.extendEventData(ev); } } // lock drag to axis? if(ionic.Gestures.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) { ev.drag_locked_to_axis = true; } var last_direction = ionic.Gestures.detection.current.lastEvent.direction; if(ev.drag_locked_to_axis && last_direction !== ev.direction) { // keep direction on the axis that the drag gesture started on if(ionic.Gestures.utils.isVertical(last_direction)) { ev.direction = (ev.deltaY < 0) ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } // trigger normal event inst.trigger(this.name, ev); // direction event, like dragdown inst.trigger(this.name + ev.direction, ev); // block the browser events if( (inst.options.drag_block_vertical && ionic.Gestures.utils.isVertical(ev.direction)) || (inst.options.drag_block_horizontal && !ionic.Gestures.utils.isVertical(ev.direction))) { ev.preventDefault(); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Transform * User want to scale or rotate with 2 fingers * @events transform, pinch, pinchin, pinchout, rotate */ ionic.Gestures.gestures.Transform = { name: 'transform', index: 45, defaults: { // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 transform_min_scale : 0.01, // rotation in degrees transform_min_rotation : 1, // prevent default browser behavior when two touches are on the screen // but it makes the element a blocking element // when you are using the transform gesture, it is a good practice to set this true transform_always_block : false }, triggered: false, handler: function transformGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // atleast multitouch if(ev.touches.length < 2) { return; } // prevent default when two fingers are on the screen if(inst.options.transform_always_block) { ev.preventDefault(); } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.EVENT_MOVE: var scale_threshold = Math.abs(1-ev.scale); var rotation_threshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scale_threshold < inst.options.transform_min_scale && rotation_threshold < inst.options.transform_min_rotation) { return; } // we are transforming! ionic.Gestures.detection.current.name = this.name; // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } inst.trigger(this.name, ev); // basic transform event // trigger rotate event if(rotation_threshold > inst.options.transform_min_rotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scale_threshold > inst.options.transform_min_scale) { inst.trigger('pinch', ev); inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Touch * Called as first, tells the user has touched the screen * @events touch */ ionic.Gestures.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 prevent_default: false, // disable mouse events, so only touch (or pen!) input triggers events prevent_mouseevents: false }, handler: function touchGesture(ev, inst) { if(inst.options.prevent_mouseevents && ev.pointerType == ionic.Gestures.POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.prevent_default) { ev.preventDefault(); } if(ev.eventType == ionic.Gestures.EVENT_START) { inst.trigger(this.name, ev); } } }; /** * Release * Called as last, tells the user has released the screen * @events release */ ionic.Gestures.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { inst.trigger(this.name, ev); } } }; })(window.ionic); ; (function(ionic) { ionic.Platform = { isReady: false, isFullScreen: false, platforms: null, ready: function(cb) { // run through tasks to complete now that the device is ready if(this.isReady) { cb(); } else { // the platform isn't ready yet, add it to this array // which will be called once the platform is ready readyCallbacks.push(cb); } }, detect: function() { ionic.Platform._checkPlatforms(); if(this.platforms.length) { // only change the body class if we got platform info var i, bodyClass = document.body.className; for(i = 0; i < this.platforms.length; i++) { bodyClass += ' platform-' + this.platforms[i]; } document.body.className = bodyClass; } }, device: function() { if(window.device) return window.device; if(this.isCordova()) console.error('device plugin required'); return {}; }, _checkPlatforms: function(platforms) { this.platforms = []; var v = this.version().toString().replace('.', '_'); if(this.isCordova()) { this.platforms.push('cordova'); } if(this.isIOS()) { this.platforms.push('ios'); this.platforms.push('ios' + v.split('_')[0]); this.platforms.push('ios' + v); } if(this.isIPad()) { this.platforms.push('ipad'); } if(this.isAndroid()) { this.platforms.push('android'); this.platforms.push('android' + v.split('_')[0]); this.platforms.push('android' + v); } }, // Check if we are running in Cordova isCordova: function() { return !(!window.cordova && !window.PhoneGap && !window.phonegap); }, isIPad: function() { return navigator.userAgent.toLowerCase().indexOf('ipad') >= 0; }, isIOS: function() { return this.is('ios'); }, isAndroid: function() { return this.is('android'); }, platform: function() { // singleton to get the platform name if(!platformName) this.setPlatform(this.device().platform); return platformName; }, setPlatform: function(n) { platformName = n; }, version: function() { // singleton to get the platform version if(!platformVersion) this.setVersion(this.device().version); return platformVersion; }, setVersion: function(v) { if(v) { v = v.split('.'); platformVersion = parseFloat(v[0] + '.' + (v.length > 1 ? v[1] : 0)); } else { platformVersion = 0; } }, // Check if the platform is the one detected by cordova is: function(type) { var pName = this.platform(); if(pName) { return pName.toLowerCase() === type.toLowerCase(); } // A quick hack for return navigator.userAgent.toLowerCase().indexOf(type.toLowerCase()) >= 0; }, exitApp: function() { this.ready(function(){ navigator.app && navigator.app.exitApp && navigator.app.exitApp(); }); }, showStatusBar: function(val) { // Only useful when run within cordova this.showStatusBar = val; this.ready(function(){ // run this only when or if the platform (cordova) is ready if(ionic.Platform.showStatusBar) { // they do not want it to be full screen StatusBar.show(); document.body.classList.remove('status-bar-hide'); } else { // it should be full screen StatusBar.hide(); document.body.classList.add('status-bar-hide'); } }); }, fullScreen: function(showFullScreen, showStatusBar) { // fullScreen( [showFullScreen[, showStatusBar] ] ) // showFullScreen: default is true if no param provided this.isFullScreen = (showFullScreen !== false); // add/remove the fullscreen classname to the body ionic.DomUtil.ready(function(){ // run this only when or if the DOM is ready if(ionic.Platform.isFullScreen) { document.body.classList.add('fullscreen'); } else { document.body.classList.remove('fullscreen'); } }); // showStatusBar: default is false if no param provided this.showStatusBar( (showStatusBar === true) ); } }; var platformName, // just the name, like iOS or Android platformVersion, // a float of the major and minor, like 7.1 readyCallbacks = []; // setup listeners to know when the device is ready to go function onWindowLoad() { if(ionic.Platform.isCordova()) { // the window and scripts are fully loaded, and a cordova/phonegap // object exists then let's listen for the deviceready document.addEventListener("deviceready", onPlatformReady, false); } else { // the window and scripts are fully loaded, but the window object doesn't have the // cordova/phonegap object, so its just a browser, not a webview wrapped w/ cordova onPlatformReady(); } window.removeEventListener("load", onWindowLoad, false); } window.addEventListener("load", onWindowLoad, false); function onPlatformReady() { // the device is all set to go, init our own stuff then fire off our event ionic.Platform.isReady = true; ionic.Platform.detect(); for(var x=0; x<readyCallbacks.length; x++) { // fire off all the callbacks that were added before the platform was ready readyCallbacks[x](); } readyCallbacks = []; ionic.trigger('platformready', { target: document }); document.removeEventListener("deviceready", onPlatformReady, false); } })(window.ionic); ; (function(window, document, ionic) { 'use strict'; // Ionic CSS polyfills ionic.CSS = {}; (function() { var d = document.createElement('div'); var keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform', '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform']; for(var i = 0; i < keys.length; i++) { if(d.style[keys[i]] !== undefined) { ionic.CSS.TRANSFORM = keys[i]; break; } } })(); // classList polyfill for them older Androids // https://gist.github.com/devongovett/1381839 if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') { Object.defineProperty(HTMLElement.prototype, 'classList', { get: function() { var self = this; function update(fn) { return function() { var x, classes = self.className.split(/\s+/); for(x=0; x<arguments.length; x++) { fn(classes, classes.indexOf(arguments[x]), arguments[x]); } self.className = classes.join(" "); }; } return { add: update(function(classes, index, value) { ~index || classes.push(value); }), remove: update(function(classes, index) { ~index && classes.splice(index, 1); }), toggle: update(function(classes, index, value) { ~index ? classes.splice(index, 1) : classes.push(value); }), contains: function(value) { return !!~self.className.split(/\s+/).indexOf(value); }, item: function(i) { return self.className.split(/\s+/)[i] || null; } }; } }); } // polyfill use to simulate native "tap" ionic.tapElement = function(target, e) { // simulate a normal click by running the element's click method then focus on it var ele = target.control || target; if(ele.disabled) return; console.debug('tapElement', ele.tagName, ele.className); var c = getCoordinates(e); // using initMouseEvent instead of MouseEvent for our Android friends var clickEvent = document.createEvent("MouseEvents"); clickEvent.initMouseEvent('click', true, true, window, 1, 0, 0, c.x, c.y, false, false, false, false, 0, null); ele.dispatchEvent(clickEvent); if(ele.tagName === 'INPUT' || ele.tagName === 'TEXTAREA' || ele.tagName === 'SELECT') { ele.focus(); e.preventDefault(); } else { blurActive(); } // remember the coordinates of this tap so if it happens again we can ignore it // but only if the coordinates are not already being actively disabled if( !isRecentTap(e) ) { recordCoordinates(e); } if(target.control) { console.debug('tapElement, target.control, stop'); return stopEvent(e); } }; function tapPolyfill(orgEvent) { // if the source event wasn't from a touch event then don't use this polyfill if(!orgEvent.gesture || !orgEvent.gesture.srcEvent) return; var e = orgEvent.gesture.srcEvent; // evaluate the actual source event, not the created event by gestures.js var ele = e.target; if( isRecentTap(e) ) { // if a tap in the same area just happened, don't continue console.debug('tapPolyfill', 'isRecentTap', ele.tagName); return stopEvent(e); } while(ele) { // climb up the DOM looking to see if the tapped element is, or has a parent, of one of these if( ele.tagName === "INPUT" || ele.tagName === "A" || ele.tagName === "BUTTON" || ele.tagName === "LABEL" || ele.tagName === "TEXTAREA" || ele.tagName === "SELECT" ) { return ionic.tapElement(ele, e); } ele = ele.parentElement; } // they didn't tap one of the above elements // if the currently active element is an input, and they tapped outside // of the current input, then unset its focus (blur) so the keyboard goes away blurActive(); } function preventGhostClick(e) { if(e.target.control) { // this is a label that has an associated input // the native layer will send the actual event, so stop this one console.debug('preventGhostClick', 'label'); return stopEvent(e); } if( isRecentTap(e) ) { // a tap has already happened at these coordinates recently, ignore this event console.debug('preventGhostClick', 'isRecentTap', e.target.tagName); return stopEvent(e); } // remember the coordinates of this click so if a tap or click in the // same area quickly happened again we can ignore it recordCoordinates(e); } function isRecentTap(event) { // loop through the tap coordinates and see if the same area has been tapped recently var tapId, existingCoordinates, currentCoordinates; for(tapId in tapCoordinates) { existingCoordinates = tapCoordinates[tapId]; if(!currentCoordinates) currentCoordinates = getCoordinates(event); // lazy load it when needed if(currentCoordinates.x > existingCoordinates.x - HIT_RADIUS && currentCoordinates.x < existingCoordinates.x + HIT_RADIUS && currentCoordinates.y > existingCoordinates.y - HIT_RADIUS && currentCoordinates.y < existingCoordinates.y + HIT_RADIUS) { // the current tap coordinates are in the same area as a recent tap return existingCoordinates; } } } function recordCoordinates(event) { var c = getCoordinates(event); if(c.x && c.y) { var tapId = Date.now(); // only record tap coordinates if we have valid ones tapCoordinates[tapId] = { x: c.x, y: c.y, id: tapId }; setTimeout(function() { // delete the tap coordinates after X milliseconds, basically allowing // it so a tap can happen again in the same area in the future delete tapCoordinates[tapId]; }, CLICK_PREVENT_DURATION); } } function getCoordinates(event) { // This method can get coordinates for both a mouse click // or a touch depending on the given event var gesture = (event.gesture ? event.gesture : event); if(gesture) { var touches = gesture.touches && gesture.touches.length ? gesture.touches : [gesture]; var e = (gesture.changedTouches && gesture.changedTouches[0]) || (gesture.originalEvent && gesture.originalEvent.changedTouches && gesture.originalEvent.changedTouches[0]) || touches[0].originalEvent || touches[0]; if(e) return { x: e.clientX, y: e.clientY }; } return { x:0, y:0 }; } function removeClickPrevent(e) { setTimeout(function(){ var tap = isRecentTap(e); if(tap) delete tapCoordinates[tap.id]; }, REMOVE_PREVENT_DELAY); } function stopEvent(e){ e.stopPropagation(); e.preventDefault(); return false; } function blurActive() { var ele = document.activeElement; if(ele && (ele.tagName === "INPUT" || ele.tagName === "TEXTAREA" || ele.tagName === "SELECT")) { // using a timeout to prevent funky scrolling while a keyboard hides setTimeout(function(){ ele.blur(); }, 400); } } var tapCoordinates = {}; // used to remember coordinates to ignore if they happen again quickly var CLICK_PREVENT_DURATION = 1500; // max milliseconds ghostclicks in the same area should be prevented var REMOVE_PREVENT_DELAY = 325; // delay after a touchend/mouseup before removing the ghostclick prevent var HIT_RADIUS = 15; // set global click handler and check if the event should stop or not document.addEventListener('click', preventGhostClick, true); // global tap event listener polyfill for HTML elements that were "tapped" by the user ionic.on("tap", tapPolyfill, document); // listeners used to remove ghostclick prevention document.addEventListener('touchend', removeClickPrevent, false); document.addEventListener('mouseup', removeClickPrevent, false); })(this, document, ionic); ; (function(ionic) { /* for nextUid() function below */ var uid = ['0','0','0']; /** * Various utilities used throughout Ionic * * Some of these are adopted from underscore.js and backbone.js, both also MIT licensed. */ ionic.Utils = { arrayMove: function (arr, old_index, new_index) { if (new_index >= arr.length) { var k = new_index - arr.length; while ((k--) + 1) { arr.push(undefined); } } arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); return arr; }, /** * Return a function that will be called with the given context */ proxy: function(func, context) { var args = Array.prototype.slice.call(arguments, 2); return function() { return func.apply(context, args.concat(Array.prototype.slice.call(arguments))); }; }, /** * Only call a function once in the given interval. * * @param func {Function} the function to call * @param wait {int} how long to wait before/after to allow function calls * @param immediate {boolean} whether to call immediately or after the wait interval */ debounce: function(func, wait, immediate) { var timeout, args, context, timestamp, result; return function() { context = this; args = arguments; timestamp = new Date(); var later = function() { var last = (new Date()) - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) result = func.apply(context, args); return result; }; }, /** * Throttle the given fun, only allowing it to be * called at most every `wait` ms. */ throttle: function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : Date.now(); timeout = null; result = func.apply(context, args); }; return function() { var now = Date.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }, // Borrowed from Backbone.js's extend // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. inherit: function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && protoProps.hasOwnProperty('constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. ionic.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) ionic.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }, // Extend adapted from Underscore.js extend: function(obj) { var args = Array.prototype.slice.call(arguments, 1); for(var i = 0; i < args.length; i++) { var source = args[i]; if (source) { for (var prop in source) { obj[prop] = source[prop]; } } } return obj; }, /** * 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 nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ nextUid: function() { 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(''); } }; // Bind a few of the most useful functions to the ionic scope ionic.inherit = ionic.Utils.inherit; ionic.extend = ionic.Utils.extend; ionic.throttle = ionic.Utils.throttle; ionic.proxy = ionic.Utils.proxy; ionic.debounce = ionic.Utils.debounce; })(window.ionic); ; (function(ionic) { ionic.Platform.ready(function() { if (ionic.Platform.is('android')) { androidKeyboardFix(); } }); function androidKeyboardFix() { var rememberedDeviceWidth = window.innerWidth; var rememberedDeviceHeight = window.innerHeight; var keyboardHeight; window.addEventListener('resize', resize); function resize() { //If the width of the window changes, we have an orientation change if (rememberedDeviceWidth !== window.innerWidth) { rememberedDeviceWidth = window.innerWidth; rememberedDeviceHeight = window.innerHeight; console.info('orientation change. deviceWidth =', rememberedDeviceWidth, ', deviceHeight =', rememberedDeviceHeight); //If the height changes, and it's less than before, we have a keyboard open } else if (rememberedDeviceHeight !== window.innerHeight && window.innerHeight < rememberedDeviceHeight) { document.body.classList.add('hide-footer'); //Wait for next frame so document.activeElement is set ionic.requestAnimationFrame(handleKeyboardChange); } else { //Otherwise we have a keyboard close or a *really* weird resize document.body.classList.remove('hide-footer'); } function handleKeyboardChange() { //keyboard opens keyboardHeight = rememberedDeviceHeight - window.innerHeight; var activeEl = document.activeElement; if (activeEl) { //This event is caught by the nearest parent scrollView //of the activeElement ionic.trigger('scrollChildIntoView', { target: activeEl }, true); } } } } })(window.ionic); ; (function(ionic) { 'use strict'; ionic.views.View = function() { this.initialize.apply(this, arguments); }; ionic.views.View.inherit = ionic.inherit; ionic.extend(ionic.views.View.prototype, { initialize: function() {} }); })(window.ionic); ; var IS_INPUT_LIKE_REGEX = /input|textarea|select/i; /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ /** * Generic animation class with support for dropped frames both optional easing and duration. * * Optional duration is useful when the lifetime is defined by another condition than time * e.g. speed of an animating object, etc. * * Dropped frame logic allows to keep using the same updater logic independent from the actual * rendering. This eases a lot of cases where it might be pretty complex to break down a state * based on the pure time difference. */ (function(global) { var time = Date.now || function() { return +new Date(); }; var desiredFrames = 60; var millisecondsPerSecond = 1000; var running = {}; var counter = 1; // Create namespaces if (!global.core) { global.core = { effect : {} }; } else if (!core.effect) { core.effect = {}; } core.effect.Animate = { /** * A requestAnimationFrame wrapper / polyfill. * * @param callback {Function} The callback to be invoked before the next repaint. * @param root {HTMLElement} The root element for the repaint */ requestAnimationFrame: (function() { // Check for request animation Frame support var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame; var isNative = !!requestFrame; if (requestFrame && !/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(requestFrame.toString())) { isNative = false; } if (isNative) { return function(callback, root) { requestFrame(callback, root) }; } var TARGET_FPS = 60; var requests = {}; var requestCount = 0; var rafHandle = 1; var intervalHandle = null; var lastActive = +new Date(); return function(callback, root) { var callbackHandle = rafHandle++; // Store callback requests[callbackHandle] = callback; requestCount++; // Create timeout at first request if (intervalHandle === null) { intervalHandle = setInterval(function() { var time = +new Date(); var currentRequests = requests; // Reset data structure before executing callbacks requests = {}; requestCount = 0; for(var key in currentRequests) { if (currentRequests.hasOwnProperty(key)) { currentRequests[key](time); lastActive = time; } } // Disable the timeout when nothing happens for a certain // period of time if (time - lastActive > 2500) { clearInterval(intervalHandle); intervalHandle = null; } }, 1000 / TARGET_FPS); } return callbackHandle; }; })(), /** * Stops the given animation. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation was stopped (aka, was running before) */ stop: function(id) { var cleared = running[id] != null; if (cleared) { running[id] = null; } return cleared; }, /** * Whether the given animation is still running. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation is still running */ isRunning: function(id) { return running[id] != null; }, /** * Start the animation. * * @param stepCallback {Function} Pointer to function which is executed on every step. * Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }` * @param verifyCallback {Function} Executed before every animation step. * Signature of the method should be `function() { return continueWithAnimation; }` * @param completedCallback {Function} * Signature of the method should be `function(droppedFrames, finishedAnimation) {}` * @param duration {Integer} Milliseconds to run the animation * @param easingMethod {Function} Pointer to easing function * Signature of the method should be `function(percent) { return modifiedValue; }` * @param root {Element} Render root, when available. Used for internal * usage of requestAnimationFrame. * @return {Integer} Identifier of animation. Can be used to stop it any time. */ start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) { var start = time(); var lastFrame = start; var percent = 0; var dropCounter = 0; var id = counter++; if (!root) { root = document.body; } // Compacting running db automatically every few new animations if (id % 20 === 0) { var newRunning = {}; for (var usedId in running) { newRunning[usedId] = true; } running = newRunning; } // This is the internal step method which is called every few milliseconds var step = function(virtual) { // Normalize virtual value var render = virtual !== true; // Get current time var now = time(); // Verification is executed before next animation step if (!running[id] || (verifyCallback && !verifyCallback(id))) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false); return; } // For the current rendering to apply let's update omitted steps in memory. // This is important to bring internal state variables up-to-date with progress in time. if (render) { var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1; for (var j = 0; j < Math.min(droppedFrames, 4); j++) { step(true); dropCounter++; } } // Compute percent value if (duration) { percent = (now - start) / duration; if (percent > 1) { percent = 1; } } // Execute step callback, then... var value = easingMethod ? easingMethod(percent) : percent; if ((stepCallback(value, now, render) === false || percent === 1) && render) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null); } else if (render) { lastFrame = now; core.effect.Animate.requestAnimationFrame(step, root); } }; // Mark as running running[id] = true; // Init first step core.effect.Animate.requestAnimationFrame(step, root); // Return unique animation ID return id; } }; })(this); /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ var Scroller; (function(ionic) { var NOOP = function(){}; // Easing Equations (c) 2003 Robert Penner, all rights reserved. // Open source under the BSD License. /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeOutCubic = function(pos) { return (Math.pow((pos - 1), 3) + 1); }; /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeInOutCubic = function(pos) { if ((pos /= 0.5) < 1) { return 0.5 * Math.pow(pos, 3); } return 0.5 * (Math.pow((pos - 2), 3) + 2); }; /** * ionic.views.Scroll * A powerful scroll view with support for bouncing, pull to refresh, and paging. * @param {Object} options options for the scroll view * @class A scroll view system * @memberof ionic.views */ ionic.views.Scroll = ionic.views.View.inherit({ initialize: function(options) { var self = this; this.__container = options.el; this.__content = options.el.firstElementChild; //Remove any scrollTop attached to these elements; they are virtual scroll now //This also stops on-load-scroll-to-window.location.hash that the browser does setTimeout(function() { if (self.__container && self.__content) { self.__container.scrollTop = 0; self.__content.scrollTop = 0; } }); this.options = { /** Disable scrolling on x-axis by default */ scrollingX: false, scrollbarX: true, /** Enable scrolling on y-axis */ scrollingY: true, scrollbarY: true, startX: 0, startY: 0, /** The minimum size the scrollbars scale to while scrolling */ minScrollbarSizeX: 5, minScrollbarSizeY: 5, /** Scrollbar fading after scrolling */ scrollbarsFade: true, scrollbarFadeDelay: 300, /** The initial fade delay when the pane is resized or initialized */ scrollbarResizeFadeDelay: 1000, /** Enable animations for deceleration, snap back, zooming and scrolling */ animating: true, /** duration for animations triggered by scrollTo/zoomTo */ animationDuration: 250, /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */ bouncing: true, /** Enable locking to the main axis if user moves only slightly on one of them at start */ locking: true, /** Enable pagination mode (switching between full page content panes) */ paging: false, /** Enable snapping of content to a configured pixel grid */ snapping: false, /** Enable zooming of content via API, fingers and mouse wheel */ zooming: false, /** Minimum zoom level */ minZoom: 0.5, /** Maximum zoom level */ maxZoom: 3, /** Multiply or decrease scrolling speed **/ speedMultiplier: 1, /** Callback that is fired on the later of touch end or deceleration end, provided that another scrolling action has not begun. Used to know when to fade out a scrollbar. */ scrollingComplete: NOOP, /** This configures the amount of change applied to deceleration when reaching boundaries **/ penetrationDeceleration : 0.03, /** This configures the amount of change applied to acceleration when reaching boundaries **/ penetrationAcceleration : 0.08, // The ms interval for triggering scroll events scrollEventInterval: 50 }; for (var key in options) { this.options[key] = options[key]; } this.hintResize = ionic.debounce(function() { self.resize(); }, 1000, true); this.triggerScrollEvent = ionic.throttle(function() { ionic.trigger('scroll', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }, this.options.scrollEventInterval); this.triggerScrollEndEvent = function() { ionic.trigger('scrollend', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }; this.__scrollLeft = this.options.startX; this.__scrollTop = this.options.startY; // Get the render update function, initialize event handlers, // and calculate the size of the scroll container this.__callback = this.getRenderFn(); this.__initEventHandlers(); this.__createScrollbars(); }, run: function() { this.resize(); // Fade them out this.__fadeScrollbars('out', this.options.scrollbarResizeFadeDelay); }, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: STATUS --------------------------------------------------------------------------- */ /** Whether only a single finger is used in touch handling */ __isSingleTouch: false, /** Whether a touch event sequence is in progress */ __isTracking: false, /** Whether a deceleration animation went to completion. */ __didDecelerationComplete: false, /** * Whether a gesture zoom/rotate event is in progress. Activates when * a gesturestart event happens. This has higher priority than dragging. */ __isGesturing: false, /** * Whether the user has moved by such a distance that we have enabled * dragging mode. Hint: It's only enabled after some pixels of movement to * not interrupt with clicks etc. */ __isDragging: false, /** * Not touching and dragging anymore, and smoothly animating the * touch sequence using deceleration. */ __isDecelerating: false, /** * Smoothly animating the currently configured change */ __isAnimating: false, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DIMENSIONS --------------------------------------------------------------------------- */ /** Available outer left position (from document perspective) */ __clientLeft: 0, /** Available outer top position (from document perspective) */ __clientTop: 0, /** Available outer width */ __clientWidth: 0, /** Available outer height */ __clientHeight: 0, /** Outer width of content */ __contentWidth: 0, /** Outer height of content */ __contentHeight: 0, /** Snapping width for content */ __snapWidth: 100, /** Snapping height for content */ __snapHeight: 100, /** Height to assign to refresh area */ __refreshHeight: null, /** Whether the refresh process is enabled when the event is released now */ __refreshActive: false, /** Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */ __refreshActivate: null, /** Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */ __refreshDeactivate: null, /** Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */ __refreshStart: null, /** Zoom level */ __zoomLevel: 1, /** Scroll position on x-axis */ __scrollLeft: 0, /** Scroll position on y-axis */ __scrollTop: 0, /** Maximum allowed scroll position on x-axis */ __maxScrollLeft: 0, /** Maximum allowed scroll position on y-axis */ __maxScrollTop: 0, /* Scheduled left position (final position when animating) */ __scheduledLeft: 0, /* Scheduled top position (final position when animating) */ __scheduledTop: 0, /* Scheduled zoom level (final scale when animating) */ __scheduledZoom: 0, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: LAST POSITIONS --------------------------------------------------------------------------- */ /** Left position of finger at start */ __lastTouchLeft: null, /** Top position of finger at start */ __lastTouchTop: null, /** Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */ __lastTouchMove: null, /** List of positions, uses three indexes for each state: left, top, timestamp */ __positions: null, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DECELERATION SUPPORT --------------------------------------------------------------------------- */ /** Minimum left scroll position during deceleration */ __minDecelerationScrollLeft: null, /** Minimum top scroll position during deceleration */ __minDecelerationScrollTop: null, /** Maximum left scroll position during deceleration */ __maxDecelerationScrollLeft: null, /** Maximum top scroll position during deceleration */ __maxDecelerationScrollTop: null, /** Current factor to modify horizontal scroll position with on every step */ __decelerationVelocityX: null, /** Current factor to modify vertical scroll position with on every step */ __decelerationVelocityY: null, /** the browser-specific property to use for transforms */ __transformProperty: null, __perspectiveProperty: null, /** scrollbar indicators */ __indicatorX: null, __indicatorY: null, /** Timeout for scrollbar fading */ __scrollbarFadeTimeout: null, /** whether we've tried to wait for size already */ __didWaitForSize: null, __sizerTimeout: null, __initEventHandlers: function() { var self = this; // Event Handler var container = this.__container; //Broadcasted when keyboard is shown on some platforms. //See js/utils/keyboard.js container.addEventListener('scrollChildIntoView', function(e) { var deviceHeight = window.innerHeight; var element = e.target; var elementHeight = e.target.offsetHeight; //getBoundingClientRect() will actually give us position relative to the viewport var elementDeviceTop = element.getBoundingClientRect().top; var elementScrollTop = ionic.DomUtil.getPositionInParent(element, container).top; //If the element is positioned under the keyboard... if (elementDeviceTop + elementHeight > deviceHeight) { //Put element in middle of visible screen self.scrollTo(0, elementScrollTop + elementHeight - (deviceHeight * 0.5), true); } //Only the first scrollView parent of the element that broadcasted this event //(the active element that needs to be shown) should receive this event e.stopPropagation(); }); function shouldIgnorePress(e) { // Don't react if initial down happens on a form element return e.target.tagName.match(IS_INPUT_LIKE_REGEX) || e.target.isContentEditable; } if ('ontouchstart' in window) { container.addEventListener("touchstart", function(e) { if (e.defaultPrevented || shouldIgnorePress(e)) { return; } self.doTouchStart(e.touches, e.timeStamp); e.preventDefault(); }, false); document.addEventListener("touchmove", function(e) { if(e.defaultPrevented) { return; } self.doTouchMove(e.touches, e.timeStamp); }, false); document.addEventListener("touchend", function(e) { self.doTouchEnd(e.timeStamp); }, false); } else { var mousedown = false; container.addEventListener("mousedown", function(e) { if (e.defaultPrevented || shouldIgnorePress(e)) { return; } self.doTouchStart([{ pageX: e.pageX, pageY: e.pageY }], e.timeStamp); e.preventDefault(); mousedown = true; }, false); document.addEventListener("mousemove", function(e) { if (!mousedown || e.defaultPrevented) { return; } self.doTouchMove([{ pageX: e.pageX, pageY: e.pageY }], e.timeStamp); mousedown = true; }, false); document.addEventListener("mouseup", function(e) { if (!mousedown) { return; } self.doTouchEnd(e.timeStamp); mousedown = false; }, false); } }, /** Create a scroll bar div with the given direction **/ __createScrollbar: function(direction) { var bar = document.createElement('div'), indicator = document.createElement('div'); indicator.className = 'scroll-bar-indicator'; if(direction == 'h') { bar.className = 'scroll-bar scroll-bar-h'; } else { bar.className = 'scroll-bar scroll-bar-v'; } bar.appendChild(indicator); return bar; }, __createScrollbars: function() { var indicatorX, indicatorY; if(this.options.scrollingX) { indicatorX = { el: this.__createScrollbar('h'), sizeRatio: 1 }; indicatorX.indicator = indicatorX.el.children[0]; if(this.options.scrollbarX) { this.__container.appendChild(indicatorX.el); } this.__indicatorX = indicatorX; } if(this.options.scrollingY) { indicatorY = { el: this.__createScrollbar('v'), sizeRatio: 1 }; indicatorY.indicator = indicatorY.el.children[0]; if(this.options.scrollbarY) { this.__container.appendChild(indicatorY.el); } this.__indicatorY = indicatorY; } }, __resizeScrollbars: function() { var self = this; // Bring the scrollbars in to show the content change self.__fadeScrollbars('in'); // Update horiz bar if(self.__indicatorX) { var width = Math.max(Math.round(self.__clientWidth * self.__clientWidth / (self.__contentWidth)), 20); if(width > self.__contentWidth) { width = 0; } self.__indicatorX.size = width; self.__indicatorX.minScale = this.options.minScrollbarSizeX / width; self.__indicatorX.indicator.style.width = width + 'px'; self.__indicatorX.maxPos = self.__clientWidth - width; self.__indicatorX.sizeRatio = self.__maxScrollLeft ? self.__indicatorX.maxPos / self.__maxScrollLeft : 1; } // Update vert bar if(self.__indicatorY) { var height = Math.max(Math.round(self.__clientHeight * self.__clientHeight / (self.__contentHeight)), 20); if(height > self.__contentHeight) { height = 0; } self.__indicatorY.size = height; self.__indicatorY.minScale = this.options.minScrollbarSizeY / height; self.__indicatorY.maxPos = self.__clientHeight - height; self.__indicatorY.indicator.style.height = height + 'px'; self.__indicatorY.sizeRatio = self.__maxScrollTop ? self.__indicatorY.maxPos / self.__maxScrollTop : 1; } }, /** * Move and scale the scrollbars as the page scrolls. */ __repositionScrollbars: function() { var self = this, width, heightScale, widthDiff, heightDiff, x, y, xstop = 0, ystop = 0; if(self.__indicatorX) { // Handle the X scrollbar // Don't go all the way to the right if we have a vertical scrollbar as well if(self.__indicatorY) xstop = 10; x = Math.round(self.__indicatorX.sizeRatio * self.__scrollLeft) || 0, // The the difference between the last content X position, and our overscrolled one widthDiff = self.__scrollLeft - (self.__maxScrollLeft - xstop); if(self.__scrollLeft < 0) { widthScale = Math.max(self.__indicatorX.minScale, (self.__indicatorX.size - Math.abs(self.__scrollLeft)) / self.__indicatorX.size); // Stay at left x = 0; // Make sure scale is transformed from the left/center origin point self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'left center'; } else if(widthDiff > 0) { widthScale = Math.max(self.__indicatorX.minScale, (self.__indicatorX.size - widthDiff) / self.__indicatorX.size); // Stay at the furthest x for the scrollable viewport x = self.__indicatorX.maxPos - xstop; // Make sure scale is transformed from the right/center origin point self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'right center'; } else { // Normal motion x = Math.min(self.__maxScrollLeft, Math.max(0, x)); widthScale = 1; } self.__indicatorX.indicator.style[self.__transformProperty] = 'translate3d(' + x + 'px, 0, 0) scaleX(' + widthScale + ')'; } if(self.__indicatorY) { y = Math.round(self.__indicatorY.sizeRatio * self.__scrollTop) || 0; // Don't go all the way to the right if we have a vertical scrollbar as well if(self.__indicatorX) ystop = 10; heightDiff = self.__scrollTop - (self.__maxScrollTop - ystop); if(self.__scrollTop < 0) { heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - Math.abs(self.__scrollTop)) / self.__indicatorY.size); // Stay at top y = 0; // Make sure scale is transformed from the center/top origin point self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center top'; } else if(heightDiff > 0) { heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - heightDiff) / self.__indicatorY.size); // Stay at bottom of scrollable viewport y = self.__indicatorY.maxPos - ystop; // Make sure scale is transformed from the center/bottom origin point self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center bottom'; } else { // Normal motion y = Math.min(self.__maxScrollTop, Math.max(0, y)); heightScale = 1; } self.__indicatorY.indicator.style[self.__transformProperty] = 'translate3d(0,' + y + 'px, 0) scaleY(' + heightScale + ')'; } }, __fadeScrollbars: function(direction, delay) { var self = this; if(!this.options.scrollbarsFade) { return; } var className = 'scroll-bar-fade-out'; if(self.options.scrollbarsFade === true) { clearTimeout(self.__scrollbarFadeTimeout); if(direction == 'in') { if(self.__indicatorX) { self.__indicatorX.indicator.classList.remove(className); } if(self.__indicatorY) { self.__indicatorY.indicator.classList.remove(className); } } else { self.__scrollbarFadeTimeout = setTimeout(function() { if(self.__indicatorX) { self.__indicatorX.indicator.classList.add(className); } if(self.__indicatorY) { self.__indicatorY.indicator.classList.add(className); } }, delay || self.options.scrollbarFadeDelay); } } }, __scrollingComplete: function() { var self = this; self.options.scrollingComplete(); self.__fadeScrollbars('out'); }, resize: function() { // Update Scroller dimensions for changed content // Add padding to bottom of content this.setDimensions( this.__container.clientWidth, this.__container.clientHeight, Math.max(this.__content.scrollWidth, this.__content.offsetWidth), Math.max(this.__content.scrollHeight, this.__content.offsetHeight) ); }, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ getRenderFn: function() { var self = this; var content = this.__content; var docStyle = document.documentElement.style; var engine; if ('MozAppearance' in docStyle) { engine = 'gecko'; } else if ('WebkitAppearance' in docStyle) { engine = 'webkit'; } else if (typeof navigator.cpuClass === 'string') { engine = 'trident'; } var vendorPrefix = { trident: 'ms', gecko: 'Moz', webkit: 'Webkit', presto: 'O' }[engine]; var helperElem = document.createElement("div"); var undef; var perspectiveProperty = vendorPrefix + "Perspective"; var transformProperty = vendorPrefix + "Transform"; var transformOriginProperty = vendorPrefix + 'TransformOrigin'; self.__perspectiveProperty = transformProperty; self.__transformProperty = transformProperty; self.__transformOriginProperty = transformOriginProperty; if (helperElem.style[perspectiveProperty] !== undef) { return function(left, top, zoom) { content.style[transformProperty] = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0)'; self.__repositionScrollbars(); self.triggerScrollEvent(); }; } else if (helperElem.style[transformProperty] !== undef) { return function(left, top, zoom) { content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px)'; self.__repositionScrollbars(); self.triggerScrollEvent(); }; } else { return function(left, top, zoom) { content.style.marginLeft = left ? (-left/zoom) + 'px' : ''; content.style.marginTop = top ? (-top/zoom) + 'px' : ''; content.style.zoom = zoom || ''; self.__repositionScrollbars(); self.triggerScrollEvent(); }; } }, /** * Configures the dimensions of the client (outer) and content (inner) elements. * Requires the available space for the outer element and the outer size of the inner element. * All values which are falsy (null or zero etc.) are ignored and the old value is kept. * * @param clientWidth {Integer} Inner width of outer element * @param clientHeight {Integer} Inner height of outer element * @param contentWidth {Integer} Outer width of inner element * @param contentHeight {Integer} Outer height of inner element */ setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) { var self = this; // Only update values which are defined if (clientWidth === +clientWidth) { self.__clientWidth = clientWidth; } if (clientHeight === +clientHeight) { self.__clientHeight = clientHeight; } if (contentWidth === +contentWidth) { self.__contentWidth = contentWidth; } if (contentHeight === +contentHeight) { self.__contentHeight = contentHeight; } // Refresh maximums self.__computeScrollMax(); self.__resizeScrollbars(); // Refresh scroll position self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Sets the client coordinates in relation to the document. * * @param left {Integer} Left position of outer element * @param top {Integer} Top position of outer element */ setPosition: function(left, top) { var self = this; self.__clientLeft = left || 0; self.__clientTop = top || 0; }, /** * Configures the snapping (when snapping is active) * * @param width {Integer} Snapping width * @param height {Integer} Snapping height */ setSnapSize: function(width, height) { var self = this; self.__snapWidth = width; self.__snapHeight = height; }, /** * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever * the user event is released during visibility of this zone. This was introduced by some apps on iOS like * the official Twitter client. * * @param height {Integer} Height of pull-to-refresh zone on top of rendered list * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release. * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled. * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh. */ activatePullToRefresh: function(height, activateCallback, deactivateCallback, startCallback) { var self = this; self.__refreshHeight = height; self.__refreshActivate = activateCallback; self.__refreshDeactivate = deactivateCallback; self.__refreshStart = startCallback; }, /** * Starts pull-to-refresh manually. */ triggerPullToRefresh: function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); if (this.__refreshStart) { this.__refreshStart(); } }, /** * Signalizes that pull-to-refresh is finished. */ finishPullToRefresh: function() { var self = this; self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Returns the scroll position and zooming values * * @return {Map} `left` and `top` scroll position and `zoom` level */ getValues: function() { var self = this; return { left: self.__scrollLeft, top: self.__scrollTop, zoom: self.__zoomLevel }; }, /** * Returns the maximum scroll values * * @return {Map} `left` and `top` maximum scroll values */ getScrollMax: function() { var self = this; return { left: self.__maxScrollLeft, top: self.__maxScrollTop }; }, /** * Zooms to the given level. Supports optional animation. Zooms * the center when no coordinates are given. * * @param level {Number} Level to zoom to * @param animate {Boolean} Whether to use animation * @param originLeft {Number} Zoom in at given left coordinate * @param originTop {Number} Zoom in at given top coordinate */ zoomTo: function(level, animate, originLeft, originTop) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }, /** * Zooms the content by the given factor. * * @param factor {Number} Zoom by given factor * @param animate {Boolean} Whether to use animation * @param originLeft {Number} Zoom in at given left coordinate * @param originTop {Number} Zoom in at given top coordinate */ zoomBy: function(factor, animate, originLeft, originTop) { var self = this; self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop); }, /** * Scrolls to the given position. Respect limitations and snapping automatically. * * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code> * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code> * @param animate {Boolean} Whether the scrolling should happen using an animation * @param zoom {Number} Zoom level to go to */ scrollTo: function(left, top, animate, zoom) { var self = this; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values self.__publish(left, top, zoom, animate); }, /** * Scroll by the given offset * * @param left {Number} Scroll x-axis by given offset * @param top {Number} Scroll x-axis by given offset * @param animate {Boolean} Whether to animate the given change */ scrollBy: function(left, top, animate) { var self = this; var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft; var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop; self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate); }, /* --------------------------------------------------------------------------- EVENT CALLBACKS --------------------------------------------------------------------------- */ /** * Mouse wheel handler for zooming support */ doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) { var self = this; var change = wheelDelta > 0 ? 0.97 : 1.03; return self.zoomTo(self.__zoomLevel * change, false, pageX - self.__clientLeft, pageY - self.__clientTop); }, /** * Touch start handler for scrolling support */ doTouchStart: function(touches, timeStamp) { this.hintResize(); // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; self.__fadeScrollbars('in'); // Reset interruptedAnimation flag self.__interruptedAnimation = true; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; self.__interruptedAnimation = true; } // Stop animation if (self.__isAnimating) { core.effect.Animate.stop(self.__isAnimating); self.__isAnimating = false; self.__interruptedAnimation = true; } // Use center point when dealing with two fingers var currentTouchLeft, currentTouchTop; var isSingleTouch = touches.length === 1; if (isSingleTouch) { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } else { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } // Store initial positions self.__initialTouchLeft = currentTouchLeft; self.__initialTouchTop = currentTouchTop; // Store current zoom level self.__zoomLevelStart = self.__zoomLevel; // Store initial touch positions self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; // Store initial move time stamp self.__lastTouchMove = timeStamp; // Reset initial scale self.__lastScale = 1; // Reset locking flags self.__enableScrollX = !isSingleTouch && self.options.scrollingX; self.__enableScrollY = !isSingleTouch && self.options.scrollingY; // Reset tracking flag self.__isTracking = true; // Reset deceleration complete flag self.__didDecelerationComplete = false; // Dragging starts directly with two fingers, otherwise lazy with an offset self.__isDragging = !isSingleTouch; // Some features are disabled in multi touch scenarios self.__isSingleTouch = isSingleTouch; // Clearing data structure self.__positions = []; }, /** * Touch move handler for scrolling support */ doTouchMove: function(touches, timeStamp, scale) { // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (event might be outside of element) if (!self.__isTracking) { return; } var currentTouchLeft, currentTouchTop; // Compute move based around of center of fingers if (touches.length === 2) { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } else { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } var positions = self.__positions; // Are we already is dragging mode? if (self.__isDragging) { // Compute move distance var moveX = currentTouchLeft - self.__lastTouchLeft; var moveY = currentTouchTop - self.__lastTouchTop; // Read previous scroll position and zooming var scrollLeft = self.__scrollLeft; var scrollTop = self.__scrollTop; var level = self.__zoomLevel; // Work with scaling if (scale != null && self.options.zooming) { var oldLevel = level; // Recompute level based on previous scale and new scale level = level / self.__lastScale * scale; // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Only do further compution when change happened if (oldLevel !== level) { // Compute relative event position to container var currentTouchLeftRel = currentTouchLeft - self.__clientLeft; var currentTouchTopRel = currentTouchTop - self.__clientTop; // Recompute left and top coordinates based on new zoom level scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel; scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel; // Recompute max scroll values self.__computeScrollMax(level); } } if (self.__enableScrollX) { scrollLeft -= moveX * this.options.speedMultiplier; var maxScrollLeft = self.__maxScrollLeft; if (scrollLeft > maxScrollLeft || scrollLeft < 0) { // Slow down on the edges if (self.options.bouncing) { scrollLeft += (moveX / 2 * this.options.speedMultiplier); } else if (scrollLeft > maxScrollLeft) { scrollLeft = maxScrollLeft; } else { scrollLeft = 0; } } } // Compute new vertical scroll position if (self.__enableScrollY) { scrollTop -= moveY * this.options.speedMultiplier; var maxScrollTop = self.__maxScrollTop; if (scrollTop > maxScrollTop || scrollTop < 0) { // Slow down on the edges if (self.options.bouncing || (self.__refreshHeight && scrollTop < 0)) { scrollTop += (moveY / 2 * this.options.speedMultiplier); // Support pull-to-refresh (only when only y is scrollable) if (!self.__enableScrollX && self.__refreshHeight != null) { if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) { self.__refreshActive = true; if (self.__refreshActivate) { self.__refreshActivate(); } } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } else if (scrollTop > maxScrollTop) { scrollTop = maxScrollTop; } else { scrollTop = 0; } } } // Keep list from growing infinitely (holding min 10, max 20 measure points) if (positions.length > 60) { positions.splice(0, 30); } // Track scroll movement for decleration positions.push(scrollLeft, scrollTop, timeStamp); // Sync scroll position self.__publish(scrollLeft, scrollTop, level); // Otherwise figure out whether we are switching into dragging mode now. } else { var minimumTrackingForScroll = self.options.locking ? 3 : 0; var minimumTrackingForDrag = 5; var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft); var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop); self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll; self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll; positions.push(self.__scrollLeft, self.__scrollTop, timeStamp); self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag); if (self.__isDragging) { self.__interruptedAnimation = false; } } // Update last touch positions and time stamp for next event self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; self.__lastTouchMove = timeStamp; self.__lastScale = scale; }, /** * Touch end handler for scrolling support */ doTouchEnd: function(timeStamp) { if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (no touchstart event on element) // This is required as this listener ('touchmove') sits on the document and not on the element itself. if (!self.__isTracking) { return; } // Not touching anymore (when two finger hit the screen there are two touch end events) self.__isTracking = false; // Be sure to reset the dragging flag now. Here we also detect whether // the finger has moved fast enough to switch into a deceleration animation. if (self.__isDragging) { // Reset dragging flag self.__isDragging = false; // Start deceleration // Verify that the last move detected was in some relevant time frame if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) { // Then figure out what the scroll position was about 100ms ago var positions = self.__positions; var endPos = positions.length - 1; var startPos = endPos; // Move pointer to position measured 100ms ago for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) { startPos = i; } // If start and stop position is identical in a 100ms timeframe, // we cannot compute any useful deceleration. if (startPos !== endPos) { // Compute relative movement between these two points var timeOffset = positions[endPos] - positions[startPos]; var movedLeft = self.__scrollLeft - positions[startPos - 2]; var movedTop = self.__scrollTop - positions[startPos - 1]; // Based on 50ms compute the movement to apply for each render step self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60); self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60); // How much velocity is required to start the deceleration var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? 4 : 1; // Verify that we have enough velocity to start deceleration if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) { // Deactivate pull-to-refresh when decelerating if (!self.__refreshActive) { self.__startDeceleration(timeStamp); } } } else { self.__scrollingComplete(); } } else if ((timeStamp - self.__lastTouchMove) > 100) { self.__scrollingComplete(); } } // If this was a slower move it is per default non decelerated, but this // still means that we want snap back to the bounds which is done here. // This is placed outside the condition above to improve edge case stability // e.g. touchend fired without enabled dragging. This should normally do not // have modified the scroll positions or even showed the scrollbars though. if (!self.__isDecelerating) { if (self.__refreshActive && self.__refreshStart) { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true); if (self.__refreshStart) { self.__refreshStart(); } } else { if (self.__interruptedAnimation || self.__isDragging) { self.__scrollingComplete(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel); // Directly signalize deactivation (nothing todo on refresh?) if (self.__refreshActive) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } // Fully cleanup list self.__positions.length = 0; }, /* --------------------------------------------------------------------------- PRIVATE API --------------------------------------------------------------------------- */ /** * Applies the scroll position to the content element * * @param left {Number} Left scroll position * @param top {Number} Top scroll position * @param animate {Boolean} Whether animation should be used to move to the new coordinates */ __publish: function(left, top, zoom, animate) { var self = this; // Remember whether we had an animation, then we try to continue based on the current "drive" of the animation var wasAnimating = self.__isAnimating; if (wasAnimating) { core.effect.Animate.stop(wasAnimating); self.__isAnimating = false; } if (animate && self.options.animating) { // Keep scheduled positions for scrollBy/zoomBy functionality self.__scheduledLeft = left; self.__scheduledTop = top; self.__scheduledZoom = zoom; var oldLeft = self.__scrollLeft; var oldTop = self.__scrollTop; var oldZoom = self.__zoomLevel; var diffLeft = left - oldLeft; var diffTop = top - oldTop; var diffZoom = zoom - oldZoom; var step = function(percent, now, render) { if (render) { self.__scrollLeft = oldLeft + (diffLeft * percent); self.__scrollTop = oldTop + (diffTop * percent); self.__zoomLevel = oldZoom + (diffZoom * percent); // Push values out if (self.__callback) { self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel); } } }; var verify = function(id) { return self.__isAnimating === id; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { if (animationId === self.__isAnimating) { self.__isAnimating = false; } if (self.__didDecelerationComplete || wasFinished) { self.__scrollingComplete(); } if (self.options.zooming) { self.__computeScrollMax(); } }; // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out self.__isAnimating = core.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic); } else { self.__scheduledLeft = self.__scrollLeft = left; self.__scheduledTop = self.__scrollTop = top; self.__scheduledZoom = self.__zoomLevel = zoom; // Push values out if (self.__callback) { self.__callback(left, top, zoom); } // Fix max scroll ranges if (self.options.zooming) { self.__computeScrollMax(); } } }, /** * Recomputes scroll minimum values based on client dimensions and content dimensions. */ __computeScrollMax: function(zoomLevel) { var self = this; if (zoomLevel == null) { zoomLevel = self.__zoomLevel; } self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0); self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0); if(!self.__didWaitForSize && self.__maxScrollLeft == 0 && self.__maxScrollTop == 0) { self.__didWaitForSize = true; self.__waitForSize(); } }, /** * If the scroll view isn't sized correctly on start, wait until we have at least some size */ __waitForSize: function() { var self = this; clearTimeout(self.__sizerTimeout); var sizer = function() { self.resize(); if((self.options.scrollingX && self.__maxScrollLeft == 0) || (self.options.scrollingY && self.__maxScrollTop == 0)) { //self.__sizerTimeout = setTimeout(sizer, 1000); } }; sizer(); self.__sizerTimeout = setTimeout(sizer, 1000); }, /* --------------------------------------------------------------------------- ANIMATION (DECELERATION) SUPPORT --------------------------------------------------------------------------- */ /** * Called when a touch sequence end and the speed of the finger was high enough * to switch into deceleration mode. */ __startDeceleration: function(timeStamp) { var self = this; if (self.options.paging) { var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0); var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0); var clientWidth = self.__clientWidth; var clientHeight = self.__clientHeight; // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area. // Each page should have exactly the size of the client area. self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth; self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight; self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth; self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight; } else { self.__minDecelerationScrollLeft = 0; self.__minDecelerationScrollTop = 0; self.__maxDecelerationScrollLeft = self.__maxScrollLeft; self.__maxDecelerationScrollTop = self.__maxScrollTop; } // Wrap class method var step = function(percent, now, render) { self.__stepThroughDeceleration(render); }; // How much velocity is required to keep the deceleration running self.__minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1; // Detect whether it's still worth to continue animating steps // If we are already slow enough to not being user perceivable anymore, we stop the whole process here. var verify = function() { var shouldContinue = Math.abs(self.__decelerationVelocityX) >= self.__minVelocityToKeepDecelerating || Math.abs(self.__decelerationVelocityY) >= self.__minVelocityToKeepDecelerating; if (!shouldContinue) { self.__didDecelerationComplete = true; } return shouldContinue; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { self.__isDecelerating = false; if (self.__didDecelerationComplete) { self.__scrollingComplete(); } // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions if(self.options.paging) { self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping); } }; // Start animation and switch on flag self.__isDecelerating = core.effect.Animate.start(step, verify, completed); }, /** * Called on every step of the animation * * @param inMemory {Boolean} Whether to not render the current step, but keep it in memory only. Used internally only! */ __stepThroughDeceleration: function(render) { var self = this; // // COMPUTE NEXT SCROLL POSITION // // Add deceleration to scroll position var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX; var scrollTop = self.__scrollTop + self.__decelerationVelocityY; // // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE // if (!self.options.bouncing) { var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft); if (scrollLeftFixed !== scrollLeft) { scrollLeft = scrollLeftFixed; self.__decelerationVelocityX = 0; } var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop); if (scrollTopFixed !== scrollTop) { scrollTop = scrollTopFixed; self.__decelerationVelocityY = 0; } } // // UPDATE SCROLL POSITION // if (render) { self.__publish(scrollLeft, scrollTop, self.__zoomLevel); } else { self.__scrollLeft = scrollLeft; self.__scrollTop = scrollTop; } // // SLOW DOWN // // Slow down velocity on every iteration if (!self.options.paging) { // This is the factor applied to every iteration of the animation // to slow down the process. This should emulate natural behavior where // objects slow down when the initiator of the movement is removed var frictionFactor = 0.95; self.__decelerationVelocityX *= frictionFactor; self.__decelerationVelocityY *= frictionFactor; } // // BOUNCING SUPPORT // if (self.options.bouncing) { var scrollOutsideX = 0; var scrollOutsideY = 0; // This configures the amount of change applied to deceleration/acceleration when reaching boundaries var penetrationDeceleration = self.options.penetrationDeceleration; var penetrationAcceleration = self.options.penetrationAcceleration; // Check limits if (scrollLeft < self.__minDecelerationScrollLeft) { scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft; } else if (scrollLeft > self.__maxDecelerationScrollLeft) { scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft; } if (scrollTop < self.__minDecelerationScrollTop) { scrollOutsideY = self.__minDecelerationScrollTop - scrollTop; } else if (scrollTop > self.__maxDecelerationScrollTop) { scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop; } // Slow down until slow enough, then flip back to snap position if (scrollOutsideX !== 0) { var isHeadingOutwardsX = scrollOutsideX * self.__decelerationVelocityX <= self.__minDecelerationScrollLeft; if (isHeadingOutwardsX) { self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration; } var isStoppedX = Math.abs(self.__decelerationVelocityX) <= self.__minVelocityToKeepDecelerating; //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds if (!isHeadingOutwardsX || isStoppedX) { self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration; } } if (scrollOutsideY !== 0) { var isHeadingOutwardsY = scrollOutsideY * self.__decelerationVelocityY <= self.__minDecelerationScrollTop; if (isHeadingOutwardsY) { self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration; } var isStoppedY = Math.abs(self.__decelerationVelocityY) <= self.__minVelocityToKeepDecelerating; //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds if (!isHeadingOutwardsY || isStoppedY) { self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration; } } } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * An ActionSheet is the slide up menu popularized on iOS. * * You see it all over iOS apps, where it offers a set of options * triggered after an action. */ ionic.views.ActionSheet = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; }, show: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.add('active'); }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.remove('active'); } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.HeaderBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; ionic.extend(this, { alignTitle: 'center' }, opts); this.align(); }, /** * Align the title text given the buttons in the header * so that the header text size is maximized and aligned * correctly as long as possible. */ align: ionic.animationFrameThrottle(function(titleSelector) { // Find the titleEl element var titleEl = this.el.querySelector(titleSelector || '.title'); if(!titleEl) { return; } var i, c, childSize; var childNodes = this.el.childNodes; var leftWidth = 0; var rightWidth = 0; var isCountingRightWidth = true; // Compute how wide the left children are // Skip all titles (there may still be two titles, one leaving the dom) // Once we encounter a titleEl, realize we are now counting the right-buttons, not left for(i = 0; i < childNodes.length; i++) { c = childNodes[i]; if (c.tagName && c.tagName.toLowerCase() == 'h1') { isCountingRightWidth = false; continue; } childSize = null; if(c.nodeType == 3) { childSize = ionic.DomUtil.getTextBounds(c); } else if(c.nodeType == 1) { childSize = c.getBoundingClientRect(); } if(childSize) { if (isCountingRightWidth) { rightWidth += childSize.width; } else { leftWidth += childSize.width; } } } var margin = Math.max(leftWidth, rightWidth) + 10; // Size and align the header titleEl based on the sizes of the left and // right children, and the desired alignment mode if(this.alignTitle == 'center') { if(margin > 10) { titleEl.style.left = margin + 'px'; titleEl.style.right = margin + 'px'; } if(titleEl.offsetWidth < titleEl.scrollWidth) { if(rightWidth > 0) { titleEl.style.right = (rightWidth + 5) + 'px'; } } } else if(this.alignTitle == 'left') { titleEl.classList.add('titleEl-left'); if(leftWidth > 0) { titleEl.style.left = (leftWidth + 15) + 'px'; } } else if(this.alignTitle == 'right') { titleEl.classList.add('titleEl-right'); if(rightWidth > 0) { titleEl.style.right = (rightWidth + 15) + 'px'; } } }) }); })(ionic); ; (function(ionic) { 'use strict'; var ITEM_CLASS = 'item'; var ITEM_CONTENT_CLASS = 'item-content'; var ITEM_SLIDING_CLASS = 'item-sliding'; var ITEM_OPTIONS_CLASS = 'item-options'; var ITEM_PLACEHOLDER_CLASS = 'item-placeholder'; var ITEM_REORDERING_CLASS = 'item-reordering'; var ITEM_DRAG_CLASS = 'item-drag'; var DragOp = function() {}; DragOp.prototype = { start: function(e) { }, drag: function(e) { }, end: function(e) { } }; var SlideDrag = function(opts) { this.dragThresholdX = opts.dragThresholdX || 10; this.el = opts.el; }; SlideDrag.prototype = new DragOp(); SlideDrag.prototype.start = function(e) { var content, buttons, offsetX, buttonsWidth; if(e.target.classList.contains(ITEM_CONTENT_CLASS)) { content = e.target; } else if(e.target.classList.contains(ITEM_CLASS)) { content = e.target.querySelector('.' + ITEM_CONTENT_CLASS); } // If we don't have a content area as one of our children (or ourselves), skip if(!content) { return; } // Make sure we aren't animating as we slide content.classList.remove(ITEM_SLIDING_CLASS); // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start) offsetX = parseFloat(content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; // Grab the buttons buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS); if(!buttons) { return; } buttonsWidth = buttons.offsetWidth; this._currentDrag = { buttonsWidth: buttonsWidth, content: content, startOffsetX: offsetX }; }; SlideDrag.prototype.drag = ionic.animationFrameThrottle(function(e) { var buttonsWidth; // We really aren't dragging if(!this._currentDrag) { return; } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if(!this._isDragging && ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) || (Math.abs(this._currentDrag.startOffsetX) > 0))) { this._isDragging = true; } if(this._isDragging) { buttonsWidth = this._currentDrag.buttonsWidth; // Grab the new X point, capping it at zero var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX); // If the new X position is past the buttons, we need to slow down the drag (rubber band style) if(newX < -buttonsWidth) { // Calculate the new X position, capped at the top of the buttons newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4))); } this._currentDrag.content.style.webkitTransform = 'translate3d(' + newX + 'px, 0, 0)'; this._currentDrag.content.style.webkitTransition = 'none'; } }); SlideDrag.prototype.end = function(e, doneCallback) { var _this = this; // There is no drag, just end immediately if(!this._currentDrag) { doneCallback && doneCallback(); return; } // If we are currently dragging, we want to snap back into place // The final resting point X will be the width of the exposed buttons var restingPoint = -this._currentDrag.buttonsWidth; // Check if the drag didn't clear the buttons mid-point // and we aren't moving fast enough to swipe open if(e.gesture.deltaX > -(this._currentDrag.buttonsWidth/2)) { // If we are going left but too slow, or going right, go back to resting if(e.gesture.direction == "left" && Math.abs(e.gesture.velocityX) < 0.3) { restingPoint = 0; } else if(e.gesture.direction == "right") { restingPoint = 0; } } // var content = this._currentDrag.content; // var onRestingAnimationEnd = function(e) { // if(e.propertyName == '-webkit-transform') { // if(content) content.classList.remove(ITEM_SLIDING_CLASS); // } // e.target.removeEventListener('webkitTransitionEnd', onRestingAnimationEnd); // }; ionic.requestAnimationFrame(function() { // var currentX = parseFloat(_this._currentDrag.content.style.webkitTransform.replace('translate3d(', '').split(',')[0]) || 0; // if(currentX !== restingPoint) { // _this._currentDrag.content.classList.add(ITEM_SLIDING_CLASS); // _this._currentDrag.content.addEventListener('webkitTransitionEnd', onRestingAnimationEnd); // } if(restingPoint === 0) { _this._currentDrag.content.style.webkitTransform = ''; } else { _this._currentDrag.content.style.webkitTransform = 'translate3d(' + restingPoint + 'px, 0, 0)'; } _this._currentDrag.content.style.webkitTransition = ''; // Kill the current drag _this._currentDrag = null; // We are done, notify caller doneCallback && doneCallback(); }); }; var ReorderDrag = function(opts) { this.dragThresholdY = opts.dragThresholdY || 0; this.onReorder = opts.onReorder; this.el = opts.el; this.scrollEl = opts.scrollEl; this.scrollView = opts.scrollView; }; ReorderDrag.prototype = new DragOp(); ReorderDrag.prototype._moveElement = function(e) { var y = (e.gesture.center.pageY - this._currentDrag.elementHeight/2); this.el.style.webkitTransform = 'translate3d(0, '+y+'px, 0)'; }; ReorderDrag.prototype.start = function(e) { var content; // Grab the starting Y point for the item var offsetY = this.el.offsetTop;//parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[1]) || 0; var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase()); var elementHeight = this.el.offsetHeight; var placeholder = this.el.cloneNode(true); // If we have a scroll pane, move our draggable element outside of it // We do this because when we drag our element down below the edge of the page // and scroll the scroll-pane, if the element is *part* of the scroll-pane, // it will scroll 'with' the scroll-pane's contents and change position. var appendToElement = (this.scrollEl || this.el).parentNode; placeholder.classList.add(ITEM_PLACEHOLDER_CLASS); this.el.parentNode.insertBefore(placeholder, this.el); this.el.classList.add(ITEM_REORDERING_CLASS); appendToElement.parentNode.appendChild(this.el); this._currentDrag = { elementHeight: elementHeight, startIndex: startIndex, placeholder: placeholder, scrollHeight: scroll, list: placeholder.parentNode }; this._moveElement(e); }; ReorderDrag.prototype.drag = ionic.animationFrameThrottle(function(e) { // We really aren't dragging if(!this._currentDrag) { return; } var scrollY = 0; var pageY = e.gesture.center.pageY; //If we have a scrollView, check scroll boundaries for dragged element and scroll if necessary if (this.scrollView) { var container = this.scrollEl; scrollY = this.scrollView.getValues().top; var containerTop = container.offsetTop; var pixelsPastTop = containerTop - pageY + this._currentDrag.elementHeight/2; var pixelsPastBottom = pageY + this._currentDrag.elementHeight/2 - containerTop - container.offsetHeight; if (e.gesture.deltaY < 0 && pixelsPastTop > 0 && scrollY > 0) { this.scrollView.scrollBy(null, -pixelsPastTop); } if (e.gesture.deltaY > 0 && pixelsPastBottom > 0) { if (scrollY < this.scrollView.getScrollMax().top) { this.scrollView.scrollBy(null, pixelsPastBottom); } } } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if(!this._isDragging && Math.abs(e.gesture.deltaY) > this.dragThresholdY) { this._isDragging = true; } if(this._isDragging) { this._moveElement(e); this._currentDrag.currentY = scrollY + pageY - this._currentDrag.placeholder.parentNode.offsetTop; this._reorderItems(); } }); // When an item is dragged, we need to reorder any items for sorting purposes ReorderDrag.prototype._reorderItems = function() { var placeholder = this._currentDrag.placeholder; var siblings = Array.prototype.slice.call(this._currentDrag.placeholder.parentNode.children); var index = siblings.indexOf(this._currentDrag.placeholder); var topSibling = siblings[Math.max(0, index - 1)]; var bottomSibling = siblings[Math.min(siblings.length, index+1)]; var thisOffsetTop = this._currentDrag.currentY;// + this._currentDrag.startOffsetTop; if(topSibling && (thisOffsetTop < topSibling.offsetTop + topSibling.offsetHeight/2)) { ionic.DomUtil.swapNodes(this._currentDrag.placeholder, topSibling); return index - 1; } else if(bottomSibling && thisOffsetTop > (bottomSibling.offsetTop + bottomSibling.offsetHeight/2)) { ionic.DomUtil.swapNodes(bottomSibling, this._currentDrag.placeholder); return index + 1; } }; ReorderDrag.prototype.end = function(e, doneCallback) { if(!this._currentDrag) { doneCallback && doneCallback(); return; } var placeholder = this._currentDrag.placeholder; var finalPosition = ionic.DomUtil.getChildIndex(placeholder, placeholder.nodeName.toLowerCase()); // Reposition the element this.el.classList.remove(ITEM_REORDERING_CLASS); this.el.style.webkitTransform = ''; placeholder.parentNode.insertBefore(this.el, placeholder); placeholder.parentNode.removeChild(placeholder); this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalPosition); this._currentDrag = null; doneCallback && doneCallback(); }; /** * The ListView handles a list of items. It will process drag animations, edit mode, * and other operations that are common on mobile lists or table views. */ ionic.views.ListView = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; opts = ionic.extend({ onReorder: function(el, oldIndex, newIndex) {}, virtualRemoveThreshold: -200, virtualAddThreshold: 200 }, opts); ionic.extend(this, opts); if(!this.itemHeight && this.listEl) { this.itemHeight = this.listEl.children[0] && parseInt(this.listEl.children[0].style.height, 10); } //ionic.views.ListView.__super__.initialize.call(this, opts); this.onRefresh = opts.onRefresh || function() {}; this.onRefreshOpening = opts.onRefreshOpening || function() {}; this.onRefreshHolding = opts.onRefreshHolding || function() {}; window.ionic.onGesture('touch', function(e) { _this._handleTouch(e); }, this.el); window.ionic.onGesture('release', function(e) { _this._handleEndDrag(e); }, this.el); window.ionic.onGesture('drag', function(e) { _this._handleDrag(e); }, this.el); // Start the drag states this._initDrag(); }, /** * Called to tell the list to stop refreshing. This is useful * if you are refreshing the list and are done with refreshing. */ stopRefreshing: function() { var refresher = this.el.querySelector('.list-refresher'); refresher.style.height = '0px'; }, /** * If we scrolled and have virtual mode enabled, compute the window * of active elements in order to figure out the viewport to render. */ didScroll: function(e) { if(this.isVirtual) { var itemHeight = this.itemHeight; // TODO: This would be inaccurate if we are windowed var totalItems = this.listEl.children.length; // Grab the total height of the list var scrollHeight = e.target.scrollHeight; // Get the viewport height var viewportHeight = this.el.parentNode.offsetHeight; // scrollTop is the current scroll position var scrollTop = e.scrollTop; // High water is the pixel position of the first element to include (everything before // that will be removed) var highWater = Math.max(0, e.scrollTop + this.virtualRemoveThreshold); // Low water is the pixel position of the last element to include (everything after // that will be removed) var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + this.virtualAddThreshold); // Compute how many items per viewport size can show var itemsPerViewport = Math.floor((lowWater - highWater) / itemHeight); // Get the first and last elements in the list based on how many can fit // between the pixel range of lowWater and highWater var first = parseInt(Math.abs(highWater / itemHeight), 10); var last = parseInt(Math.abs(lowWater / itemHeight), 10); // Get the items we need to remove this._virtualItemsToRemove = Array.prototype.slice.call(this.listEl.children, 0, first); // Grab the nodes we will be showing var nodes = Array.prototype.slice.call(this.listEl.children, first, first + itemsPerViewport); this.renderViewport && this.renderViewport(highWater, lowWater, first, last); } }, didStopScrolling: function(e) { if(this.isVirtual) { for(var i = 0; i < this._virtualItemsToRemove.length; i++) { var el = this._virtualItemsToRemove[i]; //el.parentNode.removeChild(el); this.didHideItem && this.didHideItem(i); } // Once scrolling stops, check if we need to remove old items } }, _initDrag: function() { //ionic.views.ListView.__super__._initDrag.call(this); //this._isDragging = false; this._dragOp = null; }, // Return the list item from the given target _getItem: function(target) { while(target) { if(target.classList.contains(ITEM_CLASS)) { return target; } target = target.parentNode; } return null; }, _startDrag: function(e) { var _this = this; this._isDragging = false; // Check if this is a reorder drag if(ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_DRAG_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) { var item = this._getItem(e.target); if(item) { this._dragOp = new ReorderDrag({ el: item, scrollEl: this.scrollEl, scrollView: this.scrollView, onReorder: function(el, start, end) { _this.onReorder && _this.onReorder(el, start, end); } }); this._dragOp.start(e); e.preventDefault(); return; } } // Or check if this is a swipe to the side drag else if((e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) { this._dragOp = new SlideDrag({ el: this.el }); this._dragOp.start(e); e.preventDefault(); return; } // We aren't handling it, so pass it up the chain //ionic.views.ListView.__super__._startDrag.call(this, e); }, _handleEndDrag: function(e) { var _this = this; if(!this._dragOp) { //ionic.views.ListView.__super__._handleEndDrag.call(this, e); return; } // Cancel touch timeout clearTimeout(this._touchTimeout); var items = _this.el.querySelectorAll('.item'); for(var i = 0, l = items.length; i < l; i++) { items[i].classList.remove('active'); } this._dragOp.end(e, function() { _this._initDrag(); }); }, /** * Process the drag event to move the item to the left or right. */ _handleDrag: function(e) { var _this = this, content, buttons; // If the user has a touch timeout to highlight an element, clear it if we // get sufficient draggage if(Math.abs(e.gesture.deltaX) > 10 || Math.abs(e.gesture.deltaY) > 10) { clearTimeout(this._touchTimeout); } clearTimeout(this._touchTimeout); // If we get a drag event, make sure we aren't in another drag, then check if we should // start one if(!this.isDragging && !this._dragOp) { this._startDrag(e); } // No drag still, pass it up if(!this._dragOp) { //ionic.views.ListView.__super__._handleDrag.call(this, e); return; } e.gesture.srcEvent.preventDefault(); this._dragOp.drag(e); }, /** * Handle the touch event to show the active state on an item if necessary. */ _handleTouch: function(e) { var _this = this; var item = ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_CLASS); if(!item) { return; } this._touchTimeout = setTimeout(function() { var items = _this.el.querySelectorAll('.item'); for(var i = 0, l = items.length; i < l; i++) { items[i].classList.remove('active'); } item.classList.add('active'); }, 250); }, }); })(ionic); ; (function(ionic) { 'use strict'; /** * Loading * * The Loading is an overlay that can be used to indicate * activity while blocking user interaction. */ ionic.views.Loading = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; this.el = opts.el; this.maxWidth = opts.maxWidth || 200; this.showDelay = opts.showDelay || 0; this._loadingBox = this.el.querySelector('.loading'); }, show: function() { var _this = this; if(this._loadingBox) { var lb = _this._loadingBox; var width = Math.min(_this.maxWidth, Math.max(window.outerWidth - 40, lb.offsetWidth)); lb.style.width = width + 'px'; lb.style.marginLeft = (-lb.offsetWidth) / 2 + 'px'; lb.style.marginTop = (-lb.offsetHeight) / 2 + 'px'; // Wait 'showDelay' ms before showing the loading screen this._showDelayTimeout = window.setTimeout(function() { _this.el.classList.add('active'); }, _this.showDelay); } }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; // Prevent unnecessary 'show' after 'hide' has already been called window.clearTimeout(this._showDelayTimeout); this.el.classList.remove('active'); } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.Modal = ionic.views.View.inherit({ initialize: function(opts) { opts = ionic.extend({ focusFirstInput: false, unfocusOnHide: true, focusFirstDelay: 600 }, opts); ionic.extend(this, opts); this.el = opts.el; }, show: function() { var self = this; this.el.classList.add('active'); if(this.focusFirstInput) { // Let any animations run first window.setTimeout(function() { var input = self.el.querySelector('input, textarea'); input && input.focus && input.focus(); }, this.focusFirstDelay); } }, hide: function() { this.el.classList.remove('active'); // Unfocus all elements if(this.unfocusOnHide) { var inputs = this.el.querySelectorAll('input, textarea'); // Let any animations run first window.setTimeout(function() { for(var i = 0; i < inputs.length; i++) { inputs[i].blur && inputs[i].blur(); } }); } } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.NavBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this._titleEl = this.el.querySelector('.title'); if(opts.hidden) { this.hide(); } }, hide: function() { this.el.classList.add('hidden'); }, show: function() { this.el.classList.remove('hidden'); }, shouldGoBack: function() {}, setTitle: function(title) { if(!this._titleEl) { return; } this._titleEl.innerHTML = title; }, showBackButton: function(shouldShow) { var _this = this; if(!this._currentBackButton) { var back = document.createElement('a'); back.className = 'button back'; back.innerHTML = 'Back'; this._currentBackButton = back; this._currentBackButton.onclick = function(event) { _this.shouldGoBack && _this.shouldGoBack(); }; } if(shouldShow && !this._currentBackButton.parentNode) { // Prepend the back button this.el.insertBefore(this._currentBackButton, this.el.firstChild); } else if(!shouldShow && this._currentBackButton.parentNode) { // Remove the back button if it's there this._currentBackButton.parentNode.removeChild(this._currentBackButton); } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * An ActionSheet is the slide up menu popularized on iOS. * * You see it all over iOS apps, where it offers a set of options * triggered after an action. */ ionic.views.Popup = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; this.el = opts.el; }, setTitle: function(title) { var titleEl = el.querySelector('.popup-title'); if(titleEl) { titleEl.innerHTML = title; } }, alert: function(message) { var _this = this; ionic.requestAnimationFrame(function() { _this.setTitle(message); _this.el.classList.add('active'); }); }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.remove('active'); } }); })(ionic); ; (function(ionic) { 'use strict'; /** * The side menu view handles one of the side menu's in a Side Menu Controller * configuration. * It takes a DOM reference to that side menu element. */ ionic.views.SideMenu = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.isEnabled = opts.isEnabled || true; this.setWidth(opts.width); }, getFullWidth: function() { return this.width; }, setWidth: function(width) { this.width = width; this.el.style.width = width + 'px'; }, setIsEnabled: function(isEnabled) { this.isEnabled = isEnabled; }, bringUp: function() { this.el.style.zIndex = 0; }, pushDown: function() { this.el.style.zIndex = -1; } }); ionic.views.SideMenuContent = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; ionic.extend(this, { animationClass: 'menu-animated', onDrag: function(e) {}, onEndDrag: function(e) {}, }, opts); ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el); ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el); }, _onDrag: function(e) { this.onDrag && this.onDrag(e); }, _onEndDrag: function(e) { this.onEndDrag && this.onEndDrag(e); }, disableAnimation: function() { this.el.classList.remove(this.animationClass); }, enableAnimation: function() { this.el.classList.add(this.animationClass); }, getTranslateX: function() { return parseFloat(this.el.style.webkitTransform.replace('translate3d(', '').split(',')[0]); }, setTranslateX: ionic.animationFrameThrottle(function(x) { this.el.style.webkitTransform = 'translate3d(' + x + 'px, 0, 0)'; }) }); })(ionic); ; /* * Adapted from Swipe.js 2.0 * * Brad Birdsall * Copyright 2013, MIT License * */ (function(ionic) { 'use strict'; ionic.views.Slider = ionic.views.View.inherit({ initialize: function (options) { // utilities var noop = function() {}; // simple no operation function var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution // check browser capabilities var browser = { addEventListener: !!window.addEventListener, touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch, transitions: (function(temp) { var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition']; for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true; return false; })(document.createElement('swipe')) }; var container = options.el; // quit if no root element if (!container) return; var element = container.children[0]; var slides, slidePos, width, length; options = options || {}; var index = parseInt(options.startSlide, 10) || 0; var speed = options.speed || 300; options.continuous = options.continuous !== undefined ? options.continuous : true; function setup() { // cache slides slides = element.children; length = slides.length; // set continuous to false if only one slide if (slides.length < 2) options.continuous = false; //special case if two slides if (browser.transitions && options.continuous && slides.length < 3) { element.appendChild(slides[0].cloneNode(true)); element.appendChild(element.children[1].cloneNode(true)); slides = element.children; } // create an array to store current positions of each slide slidePos = new Array(slides.length); // determine width of each slide width = container.getBoundingClientRect().width || container.offsetWidth; element.style.width = (slides.length * width) + 'px'; // stack elements var pos = slides.length; while(pos--) { var slide = slides[pos]; slide.style.width = width + 'px'; slide.setAttribute('data-index', pos); if (browser.transitions) { slide.style.left = (pos * -width) + 'px'; move(pos, index > pos ? -width : (index < pos ? width : 0), 0); } } // reposition elements before and after index if (options.continuous && browser.transitions) { move(circle(index-1), -width, 0); move(circle(index+1), width, 0); } if (!browser.transitions) element.style.left = (index * -width) + 'px'; container.style.visibility = 'visible'; options.slidesChanged && options.slidesChanged(); } function prev() { if (options.continuous) slide(index-1); else if (index) slide(index-1); } function next() { if (options.continuous) slide(index+1); else if (index < slides.length - 1) slide(index+1); } function circle(index) { // a simple positive modulo using slides.length return (slides.length + (index % slides.length)) % slides.length; } function slide(to, slideSpeed) { // do nothing if already on requested slide if (index == to) return; if (browser.transitions) { var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward // get the actual position of the slide if (options.continuous) { var natural_direction = direction; direction = -slidePos[circle(to)] / width; // if going forward but to < index, use to = slides.length + to // if going backward but to > index, use to = -slides.length + to if (direction !== natural_direction) to = -direction * slides.length + to; } var diff = Math.abs(index-to) - 1; // move all the slides between index and to in the right direction while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0); to = circle(to); move(index, width * direction, slideSpeed || speed); move(to, 0, slideSpeed || speed); if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place } else { to = circle(to); animate(index * -width, to * -width, slideSpeed || speed); //no fallback for a circular continuous if the browser does not accept transitions } index = to; offloadFn(options.callback && options.callback(index, slides[index])); } function move(index, dist, speed) { translate(index, dist, speed); slidePos[index] = dist; } function translate(index, dist, speed) { var slide = slides[index]; var style = slide && slide.style; if (!style) return; style.webkitTransitionDuration = style.MozTransitionDuration = style.msTransitionDuration = style.OTransitionDuration = style.transitionDuration = speed + 'ms'; style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)'; style.msTransform = style.MozTransform = style.OTransform = 'translateX(' + dist + 'px)'; } function animate(from, to, speed) { // if not an animation, just reposition if (!speed) { element.style.left = to + 'px'; return; } var start = +new Date; var timer = setInterval(function() { var timeElap = +new Date - start; if (timeElap > speed) { element.style.left = to + 'px'; if (delay) begin(); options.transitionEnd && options.transitionEnd.call(event, index, slides[index]); clearInterval(timer); return; } element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px'; }, 4); } // setup auto slideshow var delay = options.auto || 0; var interval; function begin() { interval = setTimeout(next, delay); } function stop() { delay = 0; clearTimeout(interval); } // setup initial vars var start = {}; var delta = {}; var isScrolling; // setup event capturing var events = { handleEvent: function(event) { if(event.type == 'mousedown' || event.type == 'mouseup' || event.type == 'mousemove') { event.touches = [{ pageX: event.pageX, pageY: event.pageY }]; } switch (event.type) { case 'mousedown': this.start(event); break; case 'touchstart': this.start(event); break; case 'touchmove': this.move(event); break; case 'mousemove': this.move(event); break; case 'touchend': offloadFn(this.end(event)); break; case 'mouseup': offloadFn(this.end(event)); break; case 'webkitTransitionEnd': case 'msTransitionEnd': case 'oTransitionEnd': case 'otransitionend': case 'transitionend': offloadFn(this.transitionEnd(event)); break; case 'resize': offloadFn(setup); break; } if (options.stopPropagation) event.stopPropagation(); }, start: function(event) { var touches = event.touches[0]; // measure start values start = { // get initial touch coords x: touches.pageX, y: touches.pageY, // store time to determine touch duration time: +new Date }; // used for testing first move event isScrolling = undefined; // reset delta and end measurements delta = {}; // attach touchmove and touchend listeners if(browser.touch) { element.addEventListener('touchmove', this, false); element.addEventListener('touchend', this, false); } else { element.addEventListener('mousemove', this, false); element.addEventListener('mouseup', this, false); document.addEventListener('mouseup', this, false); } }, move: function(event) { // ensure swiping with one touch and not pinching if ( event.touches.length > 1 || event.scale && event.scale !== 1) return if (options.disableScroll) event.preventDefault(); var touches = event.touches[0]; // measure change in x and y delta = { x: touches.pageX - start.x, y: touches.pageY - start.y } // determine if scrolling test has run - one time test if ( typeof isScrolling == 'undefined') { isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) ); } // if user is not trying to scroll vertically if (!isScrolling) { // prevent native scrolling event.preventDefault(); // stop slideshow stop(); // increase resistance if first or last slide if (options.continuous) { // we don't add resistance at the end translate(circle(index-1), delta.x + slidePos[circle(index-1)], 0); translate(index, delta.x + slidePos[index], 0); translate(circle(index+1), delta.x + slidePos[circle(index+1)], 0); } else { delta.x = delta.x / ( (!index && delta.x > 0 // if first slide and sliding left || index == slides.length - 1 // or if last slide and sliding right && delta.x < 0 // and if sliding at all ) ? ( Math.abs(delta.x) / width + 1 ) // determine resistance level : 1 ); // no resistance if false // translate 1:1 translate(index-1, delta.x + slidePos[index-1], 0); translate(index, delta.x + slidePos[index], 0); translate(index+1, delta.x + slidePos[index+1], 0); } } }, end: function(event) { // measure duration var duration = +new Date - start.time; // determine if slide attempt triggers next/prev slide var isValidSlide = Number(duration) < 250 // if slide duration is less than 250ms && Math.abs(delta.x) > 20 // and if slide amt is greater than 20px || Math.abs(delta.x) > width/2; // or if slide amt is greater than half the width // determine if slide attempt is past start and end var isPastBounds = !index && delta.x > 0 // if first slide and slide amt is greater than 0 || index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0 if (options.continuous) isPastBounds = false; // determine direction of swipe (true:right, false:left) var direction = delta.x < 0; // if not scrolling vertically if (!isScrolling) { if (isValidSlide && !isPastBounds) { if (direction) { if (options.continuous) { // we need to get the next in this direction in place move(circle(index-1), -width, 0); move(circle(index+2), width, 0); } else { move(index-1, -width, 0); } move(index, slidePos[index]-width, speed); move(circle(index+1), slidePos[circle(index+1)]-width, speed); index = circle(index+1); } else { if (options.continuous) { // we need to get the next in this direction in place move(circle(index+1), width, 0); move(circle(index-2), -width, 0); } else { move(index+1, width, 0); } move(index, slidePos[index]+width, speed); move(circle(index-1), slidePos[circle(index-1)]+width, speed); index = circle(index-1); } options.callback && options.callback(index, slides[index]); } else { if (options.continuous) { move(circle(index-1), -width, speed); move(index, 0, speed); move(circle(index+1), width, speed); } else { move(index-1, -width, speed); move(index, 0, speed); move(index+1, width, speed); } } } // kill touchmove and touchend event listeners until touchstart called again if(browser.touch) { element.removeEventListener('touchmove', events, false) element.removeEventListener('touchend', events, false) } else { element.removeEventListener('mousemove', events, false) element.removeEventListener('mouseup', events, false) document.removeEventListener('mouseup', events, false); } }, transitionEnd: function(event) { if (parseInt(event.target.getAttribute('data-index'), 10) == index) { if (delay) begin(); options.transitionEnd && options.transitionEnd.call(event, index, slides[index]); } } } // Public API this.setup = function() { setup(); }; this.slide = function(to, speed) { // cancel slideshow stop(); slide(to, speed); }; this.prev = function() { // cancel slideshow stop(); prev(); }; this.next = function() { // cancel slideshow stop(); next(); }; this.stop = function() { // cancel slideshow stop(); }; this.getPos = function() { // return current index position return index; }; this.getNumSlides = function() { // return total number of slides return length; }; this.kill = function() { // cancel slideshow stop(); // reset element element.style.width = ''; element.style.left = ''; // reset slides var pos = slides.length; while(pos--) { var slide = slides[pos]; slide.style.width = ''; slide.style.left = ''; if (browser.transitions) translate(pos, 0, 0); } // removed event listeners if (browser.addEventListener) { // remove current event listeners element.removeEventListener('touchstart', events, false); element.removeEventListener('webkitTransitionEnd', events, false); element.removeEventListener('msTransitionEnd', events, false); element.removeEventListener('oTransitionEnd', events, false); element.removeEventListener('otransitionend', events, false); element.removeEventListener('transitionend', events, false); window.removeEventListener('resize', events, false); } else { window.onresize = null; } }; this.load = function() { // trigger setup setup(); // start auto slideshow if applicable if (delay) begin(); // add event listeners if (browser.addEventListener) { // set touchstart event on element if (browser.touch) { element.addEventListener('touchstart', events, false); } else { element.addEventListener('mousedown', events, false); } if (browser.transitions) { element.addEventListener('webkitTransitionEnd', events, false); element.addEventListener('msTransitionEnd', events, false); element.addEventListener('oTransitionEnd', events, false); element.addEventListener('otransitionend', events, false); element.addEventListener('transitionend', events, false); } // set resize event on window window.addEventListener('resize', events, false); } else { window.onresize = function () { setup() }; // to play nice with old IE } } } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.views.TabBarItem = ionic.views.View.inherit({ initialize: function(el) { this.el = el; this._buildItem(); }, // Factory for creating an item from a given javascript object create: function(itemData) { var item = document.createElement('a'); item.className = 'tab-item'; // If there is an icon, add the icon element if(itemData.icon) { var icon = document.createElement('i'); icon.className = itemData.icon; item.appendChild(icon); } // If there is a badge, add the badge element if(itemData.badge) { var badge = document.createElement('i'); badge.className = 'badge'; badge.innerHTML = itemData.badge; item.appendChild(badge); item.className = 'tab-item has-badge'; } item.appendChild(document.createTextNode(itemData.title)); return new ionic.views.TabBarItem(item); }, _buildItem: function() { var _this = this, child, children = Array.prototype.slice.call(this.el.children); for(var i = 0, j = children.length; i < j; i++) { child = children[i]; // Test if this is a "i" tag with icon in the class name // TODO: This heuristic might not be sufficient if(child.tagName.toLowerCase() == 'i' && /icon/.test(child.className)) { this.icon = child.className; } // Test if this is a "i" tag with badge in the class name // TODO: This heuristic might not be sufficient if(child.tagName.toLowerCase() == 'i' && /badge/.test(child.className)) { this.badge = child.textContent.trim(); } } this.title = ''; for(i = 0, j = this.el.childNodes.length; i < j; i++) { child = this.el.childNodes[i]; if (child.nodeName === "#text") { this.title += child.nodeValue.trim(); } } this._tapHandler = function(e) { _this.onTap && _this.onTap(e); }; ionic.on('tap', this._tapHandler, this.el); }, onTap: function(e) { }, // Remove the event listeners from this object destroy: function() { ionic.off('tap', this._tapHandler, this.el); }, getIcon: function() { return this.icon; }, getTitle: function() { return this.title; }, getBadge: function() { return this.badge; }, setSelected: function(isSelected) { this.isSelected = isSelected; if(isSelected) { this.el.classList.add('active'); } else { this.el.classList.remove('active'); } } }); ionic.views.TabBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.items = []; this._buildItems(); }, // get all the items for the TabBar getItems: function() { return this.items; }, // Add an item to the tab bar addItem: function(item) { // Create a new TabItem var tabItem = ionic.views.TabBarItem.prototype.create(item); this.appendItemElement(tabItem); this.items.push(tabItem); this._bindEventsOnItem(tabItem); }, appendItemElement: function(item) { if(!this.el) { return; } this.el.appendChild(item.el); }, // Remove an item from the tab bar removeItem: function(index) { var item = this.items[index]; if(!item) { return; } item.onTap = undefined; item.destroy(); }, _bindEventsOnItem: function(item) { var _this = this; if(!this._itemTapHandler) { this._itemTapHandler = function(e) { //_this.selectItem(this); _this.trySelectItem(this); }; } item.onTap = this._itemTapHandler; }, // Get the currently selected item getSelectedItem: function() { return this.selectedItem; }, // Set the currently selected item by index setSelectedItem: function(index) { this.selectedItem = this.items[index]; // Deselect all for(var i = 0, j = this.items.length; i < j; i += 1) { this.items[i].setSelected(false); } // Select the new item if(this.selectedItem) { this.selectedItem.setSelected(true); //this.onTabSelected && this.onTabSelected(this.selectedItem, index); } }, // Select the given item assuming we can find it in our // item list. selectItem: function(item) { for(var i = 0, j = this.items.length; i < j; i += 1) { if(this.items[i] == item) { this.setSelectedItem(i); return; } } }, // Try to select a given item. This triggers an event such // that the view controller managing this tab bar can decide // whether to select the item or cancel it. trySelectItem: function(item) { for(var i = 0, j = this.items.length; i < j; i += 1) { if(this.items[i] == item) { this.tryTabSelect && this.tryTabSelect(i); return; } } }, // Build the initial items list from the given DOM node. _buildItems: function() { var item, items = Array.prototype.slice.call(this.el.children); for(var i = 0, j = items.length; i < j; i += 1) { item = new ionic.views.TabBarItem(items[i]); this.items[i] = item; this._bindEventsOnItem(item); } if(this.items.length > 0) { this.selectedItem = this.items[0]; } }, // Destroy this tab bar destroy: function() { for(var i = 0, j = this.items.length; i < j; i += 1) { this.items[i].destroy(); } this.items.length = 0; } }); })(window.ionic); ; (function(ionic) { 'use strict'; ionic.views.Toggle = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.checkbox = opts.checkbox; this.track = opts.track; this.handle = opts.handle; this.openPercent = -1; }, tap: function(e) { if(this.el.getAttribute('disabled') !== 'disabled') { this.val( !this.checkbox.checked ); } }, drag: function(e) { var slidePageLeft = this.track.offsetLeft + (this.handle.offsetWidth / 2); var slidePageRight = this.track.offsetLeft + this.track.offsetWidth - (this.handle.offsetWidth / 2); if(e.pageX >= slidePageRight - 4) { this.val(true); } else if(e.pageX <= slidePageLeft) { this.val(false); } else { this.setOpenPercent( Math.round( (1 - ((slidePageRight - e.pageX) / (slidePageRight - slidePageLeft) )) * 100) ); } }, setOpenPercent: function(openPercent) { // only make a change if the new open percent has changed if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) { this.openPercent = openPercent; if(openPercent === 0) { this.val(false); } else if(openPercent === 100) { this.val(true); } else { var openPixel = Math.round( (openPercent / 100) * this.track.offsetWidth - (this.handle.offsetWidth) ); openPixel = (openPixel < 1 ? 0 : openPixel); this.handle.style.webkitTransform = 'translate3d(' + openPixel + 'px,0,0)'; } } }, release: function(e) { this.val( this.openPercent >= 50 ); }, val: function(value) { if(value === true || value === false) { if(this.handle.style.webkitTransform !== "") { this.handle.style.webkitTransform = ""; } this.checkbox.checked = value; this.openPercent = (value ? 100 : 0); } return this.checkbox.checked; } }); })(ionic); ; (function(ionic) { 'use strict'; ionic.controllers.ViewController = function(options) { this.initialize.apply(this, arguments); }; ionic.controllers.ViewController.inherit = ionic.inherit; ionic.extend(ionic.controllers.ViewController.prototype, { initialize: function() {}, // Destroy this view controller, including all child views destroy: function() { } }); })(window.ionic); ; (function(ionic) { 'use strict'; /** * The NavController makes it easy to have a stack * of views or screens that can be pushed and popped * for a dynamic navigation flow. This API is modelled * off of the UINavigationController in iOS. * * The NavController can drive a nav bar to show a back button * if the stack can be poppped to go back to the last view, and * it will handle updating the title of the nav bar and processing animations. */ ionic.controllers.NavController = ionic.controllers.ViewController.inherit({ initialize: function(opts) { var _this = this; this.navBar = opts.navBar; this.content = opts.content; this.controllers = opts.controllers || []; this._updateNavBar(); // TODO: Is this the best way? this.navBar.shouldGoBack = function() { _this.pop(); }; }, /** * @return {array} the array of controllers on the stack. */ getControllers: function() { return this.controllers; }, /** * @return {object} the controller at the top of the stack. */ getTopController: function() { return this.controllers[this.controllers.length-1]; }, /** * Push a new controller onto the navigation stack. The new controller * will automatically become the new visible view. * * @param {object} controller the controller to push on the stack. */ push: function(controller) { var last = this.controllers[this.controllers.length - 1]; this.controllers.push(controller); // Indicate we are switching controllers var shouldSwitch = this.switchingController && this.switchingController(controller) || true; // Return if navigation cancelled if(shouldSwitch === false) return; // Actually switch the active controllers if(last) { last.isVisible = false; last.visibilityChanged && last.visibilityChanged('push'); } // Grab the top controller on the stack var next = this.controllers[this.controllers.length - 1]; next.isVisible = true; // Trigger visibility change, but send 'first' if this is the first page next.visibilityChanged && next.visibilityChanged(last ? 'push' : 'first'); this._updateNavBar(); return controller; }, /** * Pop the top controller off the stack, and show the last one. This is the * "back" operation. * * @return {object} the last popped controller */ pop: function() { var next, last; // Make sure we keep one on the stack at all times if(this.controllers.length < 2) { return; } // Grab the controller behind the top one on the stack last = this.controllers.pop(); if(last) { last.isVisible = false; last.visibilityChanged && last.visibilityChanged('pop'); } // Remove the old one //last && last.detach(); next = this.controllers[this.controllers.length - 1]; // TODO: No DOM stuff here //this.content.el.appendChild(next.el); next.isVisible = true; next.visibilityChanged && next.visibilityChanged('pop'); // Switch to it (TODO: Animate or such things here) this._updateNavBar(); return last; }, /** * Show the NavBar (if any) */ showNavBar: function() { if(this.navBar) { this.navBar.show(); } }, /** * Hide the NavBar (if any) */ hideNavBar: function() { if(this.navBar) { this.navBar.hide(); } }, // Update the nav bar after a push or pop _updateNavBar: function() { if(!this.getTopController() || !this.navBar) { return; } this.navBar.setTitle(this.getTopController().title); if(this.controllers.length > 1) { this.navBar.showBackButton(true); } else { this.navBar.showBackButton(false); } } }); })(window.ionic); ; (function(ionic) { 'use strict'; /** * The SideMenuController is a controller with a left and/or right menu that * can be slid out and toggled. Seen on many an app. * * The right or left menu can be disabled or not used at all, if desired. */ ionic.controllers.SideMenuController = ionic.controllers.ViewController.inherit({ initialize: function(options) { var self = this; this.left = options.left; this.right = options.right; this.content = options.content; this.dragThresholdX = options.dragThresholdX || 10; this._rightShowing = false; this._leftShowing = false; this._isDragging = false; if(this.content) { this.content.onDrag = function(e) { self._handleDrag(e); }; this.content.onEndDrag =function(e) { self._endDrag(e); }; } }, /** * Set the content view controller if not passed in the constructor options. * * @param {object} content */ setContent: function(content) { var self = this; this.content = content; this.content.onDrag = function(e) { self._handleDrag(e); }; this.content.endDrag = function(e) { self._endDrag(e); }; }, /** * Toggle the left menu to open 100% */ toggleLeft: function() { this.content.enableAnimation(); var openAmount = this.getOpenAmount(); if(openAmount > 0) { this.openPercentage(0); } else { this.openPercentage(100); } }, /** * Toggle the right menu to open 100% */ toggleRight: function() { this.content.enableAnimation(); var openAmount = this.getOpenAmount(); if(openAmount < 0) { this.openPercentage(0); } else { this.openPercentage(-100); } }, /** * Close all menus. */ close: function() { this.openPercentage(0); }, /** * @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative) */ getOpenAmount: function() { return this.content && this.content.getTranslateX() || 0; }, /** * @return {float} The ratio of open amount over menu width. For example, a * menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative * for right menu. */ getOpenRatio: function() { var amount = this.getOpenAmount(); if(amount >= 0) { return amount / this.left.width; } return amount / this.right.width; }, isOpen: function() { return this.getOpenRatio() == 1; }, /** * @return {float} The percentage of open amount over menu width. For example, a * menu of width 100 open 50 pixels would be open 50%. Value is negative * for right menu. */ getOpenPercentage: function() { return this.getOpenRatio() * 100; }, /** * Open the menu with a given percentage amount. * @param {float} percentage The percentage (positive or negative for left/right) to open the menu. */ openPercentage: function(percentage) { var p = percentage / 100; if(this.left && percentage >= 0) { this.openAmount(this.left.width * p); } else if(this.right && percentage < 0) { var maxRight = this.right.width; this.openAmount(this.right.width * p); } }, /** * Open the menu the given pixel amount. * @param {float} amount the pixel amount to open the menu. Positive value for left menu, * negative value for right menu (only one menu will be visible at a time). */ openAmount: function(amount) { var maxLeft = this.left && this.left.width || 0; var maxRight = this.right && this.right.width || 0; // Check if we can move to that side, depending if the left/right panel is enabled if((!(this.left && this.left.isEnabled) && amount > 0) || (!(this.right && this.right.isEnabled) && amount < 0)) { return; } if((this._leftShowing && amount > maxLeft) || (this._rightShowing && amount < -maxRight)) { return; } this.content.setTranslateX(amount); if(amount >= 0) { this._leftShowing = true; this._rightShowing = false; // Push the z-index of the right menu down this.right && this.right.pushDown && this.right.pushDown(); // Bring the z-index of the left menu up this.left && this.left.bringUp && this.left.bringUp(); } else { this._rightShowing = true; this._leftShowing = false; // Bring the z-index of the right menu up this.right && this.right.bringUp && this.right.bringUp(); // Push the z-index of the left menu down this.left && this.left.pushDown && this.left.pushDown(); } }, /** * Given an event object, find the final resting position of this side * menu. For example, if the user "throws" the content to the right and * releases the touch, the left menu should snap open (animated, of course). * * @param {Event} e the gesture event to use for snapping */ snapToRest: function(e) { // We want to animate at the end of this this.content.enableAnimation(); this._isDragging = false; // Check how much the panel is open after the drag, and // what the drag velocity is var ratio = this.getOpenRatio(); if(ratio === 0) return; var velocityThreshold = 0.3; var velocityX = e.gesture.velocityX; var direction = e.gesture.direction; // Less than half, going left //if(ratio > 0 && ratio < 0.5 && direction == 'left' && velocityX < velocityThreshold) { //this.openPercentage(0); //} // Going right, less than half, too slow (snap back) if(ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) { this.openPercentage(0); } // Going left, more than half, too slow (snap back) else if(ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) { this.openPercentage(100); } // Going left, less than half, too slow (snap back) else if(ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) { this.openPercentage(0); } // Going right, more than half, too slow (snap back) else if(ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) { this.openPercentage(-100); } // Going right, more than half, or quickly (snap open) else if(direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) { this.openPercentage(100); } // Going left, more than half, or quickly (span open) else if(direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) { this.openPercentage(-100); } // Snap back for safety else { this.openPercentage(0); } }, // End a drag with the given event _endDrag: function(e) { if(this._isDragging) { this.snapToRest(e); } this._startX = null; this._lastX = null; this._offsetX = null; }, // Handle a drag event _handleDrag: function(e) { // If we don't have start coords, grab and store them if(!this._startX) { this._startX = e.gesture.touches[0].pageX; this._lastX = this._startX; } else { // Grab the current tap coords this._lastX = e.gesture.touches[0].pageX; } // Calculate difference from the tap points if(!this._isDragging && Math.abs(this._lastX - this._startX) > this.dragThresholdX) { // if the difference is greater than threshold, start dragging using the current // point as the starting point this._startX = this._lastX; this._isDragging = true; // Initialize dragging this.content.disableAnimation(); this._offsetX = this.getOpenAmount(); } if(this._isDragging) { this.openAmount(this._offsetX + (this._lastX - this._startX)); } } }); })(ionic); ; (function(ionic) { 'use strict'; /** * The TabBarController handles a set of view controllers powered by a tab strip * at the bottom (or possibly top) of a screen. * * The API here is somewhat modelled off of UITabController in the sense that the * controllers actually define what the tab will look like (title, icon, etc.). * * Tabs shouldn't be interacted with through your own code. Instead, use the controller * methods which will power the tab bar. */ ionic.controllers.TabBarController = ionic.controllers.ViewController.inherit({ initialize: function(options) { this.tabBar = options.tabBar; this._bindEvents(); this.controllers = []; var controllers = options.controllers || []; for(var i = 0; i < controllers.length; i++) { this.addController(controllers[i]); } // Bind or set our tabWillChange callback this.controllerWillChange = options.controllerWillChange || function(controller) {}; this.controllerChanged = options.controllerChanged || function(controller) {}; // Try to select the first controller if we have one this.setSelectedController(0); }, // Start listening for events on our tab bar _bindEvents: function() { var _this = this; this.tabBar.tryTabSelect = function(index) { _this.setSelectedController(index); }; }, selectController: function(index) { var shouldChange = true; // Check if we should switch to this tab. This lets the app // cancel tab switches if the context isn't right, for example. if(this.controllerWillChange) { if(this.controllerWillChange(this.controllers[index], index) === false) { shouldChange = false; } } if(shouldChange) { this.setSelectedController(index); } }, // Force the selection of a controller at the given index setSelectedController: function(index) { if(index >= this.controllers.length) { return; } var lastController = this.selectedController; var lastIndex = this.selectedIndex; this.selectedController = this.controllers[index]; this.selectedIndex = index; this._showController(index); this.tabBar.setSelectedItem(index); this.controllerChanged && this.controllerChanged(lastController, lastIndex, this.selectedController, this.selectedIndex); }, _showController: function(index) { var c; for(var i = 0, j = this.controllers.length; i < j; i ++) { c = this.controllers[i]; //c.detach && c.detach(); c.isVisible = false; c.visibilityChanged && c.visibilityChanged(); } c = this.controllers[index]; //c.attach && c.attach(); c.isVisible = true; c.visibilityChanged && c.visibilityChanged(); }, _clearSelected: function() { this.selectedController = null; this.selectedIndex = -1; }, // Return the tab at the given index getController: function(index) { return this.controllers[index]; }, // Return the current tab list getControllers: function() { return this.controllers; }, // Get the currently selected controller getSelectedController: function() { return this.selectedController; }, // Get the index of the currently selected controller getSelectedControllerIndex: function() { return this.selectedIndex; }, // Add a tab addController: function(controller) { this.controllers.push(controller); this.tabBar.addItem({ title: controller.title, icon: controller.icon, badge: controller.badge }); // If we don't have a selected controller yet, select the first one. if(!this.selectedController) { this.setSelectedController(0); } }, // Set the tabs and select the first setControllers: function(controllers) { this.controllers = controllers; this._clearSelected(); this.selectController(0); }, }); })(window.ionic);
ajax/libs/yui/3.0.0pr2/yui/yui.js
jackdoyle/cdnjs
/** * YUI core * @module yui */ (function() { var _instances = {}, // @TODO: this needs to be created at build time from module metadata _APPLY_TO_WHITE_LIST = { 'io.xdrReady': 1, 'io.start': 1, 'io.success': 1, 'io.failure': 1, 'io.abort': 1 }; if (typeof YUI === 'undefined' || !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. * * @class YUI * @constructor * @global * @uses Event.Target * @param o Optional configuration object. Options: * <ul> * <li>------------------------------------------------------------------------</li> * <li>Global:</li> * <li>------------------------------------------------------------------------</li> * <li>debug: * Turn debug statements on or off</li> * <li>useBrowserConsole: * Log to the browser console if debug is on and the console is available</li> * <li>logInclude: * A hash of log sources that should be logged. If specified, only log messages from these sources will be logged. * * </li> * <li>logExclude: * A hash of log sources that should be not be logged. If specified, all sources are logged if not on this list.</li> * <li>throwFail: * If throwFail is set, Y.fail will generate or re-throw a JS error. Otherwise the failure is logged. * <li>win: * The target window/frame</li> * <li>core: * A list of modules that defines the YUI core (overrides the default)</li> * <li>------------------------------------------------------------------------</li> * <li>For event and get:</li> * <li>------------------------------------------------------------------------</li> * <li>pollInterval: * The default poll interval</li> * <li>-------------------------------------------------------------------------</li> * <li>For loader:</li> * <li>-------------------------------------------------------------------------</li> * <li>base: * The base dir</li> * <li>secureBase: * The secure base dir (not implemented)</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>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</li> * <li>timeout: * number of milliseconds before a timeout occurs when dynamically loading nodes. in 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>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> * </ul> */ /*global YUI*/ YUI = function(o) { var Y = this; // Allow instantiation without the new operator if (!(Y instanceof YUI)) { return new YUI(o); } else { // set up the core environment Y._init(o); // bind the specified additional modules for this instance Y._setup(); return Y; } }; } // The prototype contains the functions that are required to allow the external // modules to be registered and for the instance to be initialized. YUI.prototype = { /** * Initialize this YUI instance * @param o config options * @private */ _init: function(o) { o = o || {}; // find targeted window and @TODO create facades var w = (o.win) ? (o.win.contentWindow) : o.win || window; o.win = w; o.doc = w.document; o.debug = ('debug' in o) ? o.debug : true; o.useBrowserConsole = ('useBrowserConsole' in o) ? o.useBrowserConsole : true; o.throwFail = ('throwFail' in o) ? o.throwFail : true; // add a reference to o for anything that needs it // before _setup is called. this.config = o; this.Env = { // @todo expand the new module metadata mods: {}, _idx: 0, _pre: 'yuid', _used: {}, _attached: {}, _yidx: 0, _uidx: 0 }; if (YUI.Env) { this.Env._yidx = ++YUI.Env._idx; this.id = this.stamp(this); _instances[this.id] = this; } this.constructor = YUI; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { this.use("yui"); // @TODO eval the need to copy the config this.config = this.merge(this.config); }, /** * 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_WHITE_LIST)) { this.fail(method + ': applyTo not allowed'); return null; } var instance = _instances[id]; if (instance) { var nest = method.split('.'), m = instance; for (var i=0; i<nest.length; i=i+1) { m = m[nest[i]]; if (!m) { this.fail('applyTo not found: ' + method); } } return m.apply(instance, args); } return null; }, /** * Register a 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 * @return {YUI} the YUI instance * * requires - features that should be present before loading * optional - optional features that should be present if load optional defined * use - features that should be attached automatically * skinnable - * rollup * omit - features that should not be loaded if this module is present */ add: function(name, fn, version, details) { // @todo expand this to include version mapping // @todo allow requires/supersedes // @todo may want to restore the build property // @todo fire moduleAvailable event var m = { name: name, fn: fn, version: version, details: details || {} }; YUI.Env.mods[name] = m; return this; // chain support }, _attach: function(r, fromLoader) { var mods = YUI.Env.mods, attached = this.Env._attached; for (var i=0, l=r.length; i<l; i=i+1) { var name = r[i], m = mods[name], mm; if (!attached[name] && m) { attached[name] = true; var d = m.details, req = d.requires, use = d.use; if (req) { this._attach(this.Array(req)); } if (m.fn) { m.fn(this); } if (use) { this._attach(this.Array(use)); } } } }, /** * Bind a module to a YUI instance * @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. * * @TODO * Implement versioning? loader can load different versions? * Should sub-modules/plugins be normal modules, or do * we add syntax for specifying these? * * YUI().use('dragdrop') * YUI().use('dragdrop:2.4.0'); // specific version * YUI().use('dragdrop:2.4.0-'); // at least this version * YUI().use('dragdrop:2.4.0-2.9999.9999'); // version range * YUI().use('*'); // use all available modules * YUI().use('lang+dump+substitute'); // use lang and some plugins * YUI().use('lang+*'); // use lang and all known plugins * * * @return {YUI} the YUI instance */ use: function() { var Y = this, a=Array.prototype.slice.call(arguments, 0), mods = YUI.Env.mods, used = Y.Env._used, loader, firstArg = a[0], dynamic = false, callback = a[a.length-1]; // The last argument supplied to use can be a load complete callback if (typeof callback === 'function') { a.pop(); Y.Env._callback = callback; } else { callback = null; } // YUI().use('*'); // bind everything available if (firstArg === "*") { a = []; for (var k in mods) { if (mods.hasOwnProperty(k)) { a.push(k); } } return Y.use.apply(Y, a); } // use loader to expand dependencies and sort the // requirements if it is available. if (Y.Loader) { dynamic = true; loader = new Y.Loader(Y.config); loader.require(a); loader.ignoreRegistered = true; loader.allowRollup = false; loader.calculate(); a = loader.sorted; } var missing = [], r = [], f = function(name) { // only attach a module once if (used[name]) { return; } var m = mods[name], j, req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { missing.push(name); } // make sure requirements are attached if (req) { if (Y.Lang.isString(req)) { f(req); } else { for (j = 0; j < req.length; j = j + 1) { f(req[j]); } } } // add this module to full list of things to attach r.push(name); }; // process each requirement and any additional requirements // the module metadata specifies for (var i=0, l=a.length; i<l; i=i+1) { f(a[i]); } var onComplete = function(fromLoader) { fromLoader = fromLoader || { success: true, msg: 'not dynamic' }; if (Y.Env._callback) { var cb = Y.Env._callback; Y.Env._callback = null; cb(Y, fromLoader); } if (Y.fire) { Y.fire('yui:load', Y, fromLoader); } }; // dynamic load if (Y.Loader && missing.length) { loader = new Y.Loader(Y.config); loader.onSuccess = onComplete; loader.onFailure = onComplete; loader.onTimeout = onComplete; loader.attaching = a; loader.require(missing); loader.insert(); } else { Y._attach(r); onComplete(); } return Y; // chain support var yui = YUI().use('dragdrop'); }, /** * 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 YAHOO.property, then * YUI.property.package * * 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=null, i, j, d; for (i=0; i<a.length; i=i+1) { d = a[i].split("."); o = this; for (j=(d[0] == "YAHOO") ? 1 : 0; j<d.length; j=j+1) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } return o; }, // this is replaced if the log module is included log: function() { }, /** * 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 fail * @param msg {string} the failure message * @param e {Error} Optional JS error that was caught. If supplied * and throwFail is specified, this error will be re-thrown. * @return {YUI} this YUI instance */ fail: function(msg, e) { if (this.config.throwFail) { throw (e || new Error(msg)); } else { var instance = this; instance.log(msg, "error"); // don't scrub this one } return this; }, /** * 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 e = this.Env, p = (pre) || e._pre; return p +'-' + e._yidx + '-' + e._uidx++; }, /** * Stamps an object with a guid. If the object already * has one, a new one is not created * @method stamp * @param o The object to stamp * @return {string} The object's guid */ stamp: function(o) { if (!o) { return o; } var uid = (typeof o === 'string') ? o : o._yuid; if (!uid) { uid = this.guid(); o._yuid = uid; } return uid; } }; // Give the YUI global the same properties as an instance. // This makes it so that the YUI global can be used like the YAHOO // global was used prior to 3.x. More importantly, the YUI global // provides global metadata, so env needs to be configured. // @TODO review var Y = YUI, p = Y.prototype, i; // inheritance utilities are not available yet for (i in p) { if (true) { Y[i] = p[i]; } } // set up the environment Y._init(); })(); /** * YUI stub * @module yui * @submodule yui-base */ // This is just a stub to for dependency processing YUI.add("yui-base", null, "@VERSION@"); /* * YUI console logger * @module yui * @submodule log */ YUI.add("log", function(instance) { /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the logger widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. * * @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 Y = instance, c = Y.config, es = Y.Env._eventstack, // bail = (es && es.logging); bail = false; // 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 && !bail) { // apply source filters if (src) { var exc = c.logExclude, inc = c.logInclude; // console.log('checking src filter: ' + src + ', inc: ' + inc + ', exc: ' + exc); if (inc && !(src in inc)) { // console.log('bail: inc list found, but src is not in list: ' + src); bail = true; } else if (exc && (src in exc)) { // console.log('bail: exc list found, and src is in it: ' + src); bail = true; } } if (!bail) { if (c.useBrowserConsole) { var m = (src) ? src + ': ' + msg : msg; if (typeof console != 'undefined') { var f = (cat && console[cat]) ? cat : 'log'; console[f](m); } else if (typeof opera != 'undefined') { opera.postError(m); } } if (Y.fire && !bail && !silent) { Y.fire('yui:log', msg, cat, src); } } } return Y; }; }, "@VERSION@"); /* * YUI lang utils * @module yui * @submodule lang */ YUI.add("lang", function(Y) { /** * Provides the language utilites and extensions used by the library * @class Lang * @static */ Y.Lang = Y.Lang || {}; var L = Y.Lang, ARRAY_TOSTRING = '[object Array]', FUNCTION_TOSTRING = '[object Function]', STRING = 'string', OBJECT = 'object', BOOLEAN = 'boolean', UNDEFINED = 'undefined', OP = Object.prototype; /** * Determines whether or not the provided object is an array. * Testing typeof/instanceof/constructor of arrays across frame * boundaries isn't possible in Safari unless you have a reference * to the other frame to test against its Array prototype. To * handle this case, we test well-known array properties instead. * properties. * @TODO can we kill this cross frame hack? * @method isArray * @static * @param o The object to test * @return {boolean} true if o is an array */ L.isArray = function(o) { return OP.toString.apply(o) === ARRAY_TOSTRING; }; /** * Determines whether or not the provided object 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; }; /** * Determines whether or not the provided object is a function * Note: Internet Explorer thinks certain functions are objects: * * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * * You will have to implement additional tests if these functions * matter to you. * * @method isFunction * @static * @param o The object to test * @return {boolean} true if o is a function */ L.isFunction = function(o) { return OP.toString.apply(o) === FUNCTION_TOSTRING; }; /** * Determines whether or not the supplied object 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 o instanceof Date; }; /** * Determines whether or not the provided object 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 object 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 object is of type object * or function * @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 */ L.isObject = function(o, failfn) { return (o && (typeof o === OBJECT || (!failfn && L.isFunction(o)))) || false; }; /** * Determines whether or not the provided object 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 object 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 = function(s){ try { return s.replace(/^\s+|\s+$/g, ""); } catch(e) { return 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) { // return (o || o === false || o === 0 || o === ''); // Infinity fails return (L.isObject(o) || L.isString(o) || L.isNumber(o) || L.isBoolean(o)); }; }, "@VERSION@"); /* * Array utilities * @module yui * @submodule array */ /** * YUI core * @module yui */ YUI.add("array", function(Y) { var L = Y.Lang, Native = Array.prototype; /** * Adds the following array utilities to the YUI instance * @class YUI~array */ /** * Y.Array(o) returns an array: * - Arrays are return unmodified unless the start position is specified. * - "Array-like" collections (@see Array.test) are converted to arrays * - For everything else, a new array is created with the input as the sole item * - The start position is used if the input is or is like an array to return * a subset of the collection. * * @TODO this will not automatically convert elements that are also collections * such as forms and selects. Passing true as the third param will * force a conversion. * * @method Array * @static * @param o the item to arrayify * @param i {int} if an array or array-like, this is the start index * @param al {boolean} if true, it forces the array-like fork. This * can be used to avoid multiple array.test calls. * @return {Array} the resulting array */ Y.Array = function(o, i, al) { var t = (al) ? 2 : Y.Array.test(o); // switch (t) { // case 1: // // return (i) ? o.slice(i) : o; // case 2: // return Native.slice.call(o, i || 0); // default: // return [o]; // } if (t) { return Native.slice.call(o, i || 0); } else { return [o]; } }; var A = Y.Array; /** * Evaluates the input to determine if it is an array, array-like, or * something else. This is used to handle the arguments collection * available within functions, and HTMLElement collections * * @method Array.test * @static * * @todo current implementation (intenionally) will not implicitly * handle html elements that are array-like (forms, selects, etc). * * @return {int} a number indicating the results: * 0: Not an array or an array-like collection * 1: A real array. * 2: array-like collection. */ A.test = function(o) { var r = 0; if (L.isObject(o, true)) { if (L.isArray(o)) { r = 1; } else { try { // indexed, but no tagName (element) or alert (window) if ("length" in o && !("tagName" in o) && !("alert" in o) && (!Y.Lang.isFunction(o.size) || o.size() > 1)) { r = 2; } } catch(ex) {} } } return r; }; /** * Executes the supplied function on each item in the array. * @method Array.each * @param a {Array} the array to iterate * @param f {Function} the function to execute on each item * @param o Optional context object * @static * @return {YUI} the YUI instance */ A.each = (Native.forEach) ? function (a, f, o) { Native.forEach.call(a, f, o || Y); return Y; } : function (a, f, o) { var l = a.length, i; for (i = 0; i < l; i=i+1) { f.call(o || Y, a[i], i, a); } return Y; }; /** * Executes the supplied function on each item in the array. * Returning true from the processing function will stop the * processing of the remaining * items. * @method Array.some * @param a {Array} the array to iterate * @param f {Function} the function to execute on each item * @param o Optional context object * @static * @return {boolean} true if the */ A.some = (Native.forEach) ? function (a, f, o) { Native.some.call(a, f, o || Y); return Y; } : function (a, f, o) { var l = a.length; for (var i = 0; i < l; i=i+1) { if (f.call(o, a[i], i, a)) { return true; } } return false; }; /** * Returns an object using the first array as keys, and * the second as values. If the second array is not * provided the value is set to true for each. * @method Array.hash * @static * @param k {Array} keyset * @param v {Array} optional valueset * @return {object} the hash */ A.hash = function(k, v) { var o = {}, l = k.length, vl = v && v.length, i; for (i=0; i<l; i=i+1) { o[k[i]] = (vl && vl > i) ? v[i] : true; } return o; }; /** * Returns the index of the first item in the array * that contains the specified value, -1 if the * value isn't found. * @TODO use native method if avail * @method Array.indexOf * @static * @param a {Array} the array to search * @param val the value to search for * @return {int} the index of the item that contains the value or -1 */ A.indexOf = function(a, val) { for (var i=0; i<a.length; i=i+1) { if (a[i] === val) { return i; } } return -1; }; }, "@VERSION@"); /* * YUI core utilities * @module yui * @submodule core */ // requires lang YUI.add("core", function(Y) { var L = Y.Lang, A = Y.Array, OP = Object.prototype, IEF = ["toString", "valueOf"], PROTO = 'prototype', /** * IE will not enumerate native functions in a derived object even if the * function was overridden. This is a workaround for specific functions * we care about on the Object prototype. * @property _iefix * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param w a whitelist object (the keys are the valid items to reference) * @private * @for YUI */ _iefix = (Y.UA && Y.UA.ie) ? function(r, s, w) { for (var i=0, a=IEF; i<a.length; i=i+1) { var n = a[i], f = s[n]; if (L.isFunction(f) && f != OP[n]) { if (!w || (n in w)) { r[n]=f; } } } } : function() {}; /** * 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 arguments {Object*} the objects to merge * @return {object} the new merged object */ Y.merge = function() { // var o={}, a=arguments; // for (var i=0, l=a.length; i<l; i=i+1) { //var a=arguments, o=Y.Object(a[0]); var a=arguments, o={}; for (var i=0, l=a.length; i<l; i=i+1) { Y.mix(o, a[i], true); } return o; }; /** * Applies the supplier's properties to the receiver. By default * all prototype and static propertes on the supplier are applied * to the corresponding spot on the receiver. By default all * properties are applied, and a property that is already on the * reciever will not be overwritten. The default behavior can * be modified by supplying the appropriate parameters. * * @TODO add constants for the modes * * @method mix * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param ov {boolean} if true, properties already on the receiver * will be overwritten if found on the supplier. * @param wl {string[]} a whitelist. If supplied, only properties in * this list will be applied to the receiver. * @param {int} mode what should be copies, and to where * default(0): object to object * 1: prototype to prototype (old augment) * 2: prototype to prototype and object props (new augment) * 3: prototype to object * 4: object to prototype * @param merge {boolean} merge objects instead of overwriting/ignoring * Used by Y.aggregate * @return {object} the augmented object * @TODO review for PR2 */ Y.mix = function(r, s, ov, wl, mode, merge) { if (!s||!r) { return Y; } var w = (wl && wl.length) ? A.hash(wl) : null, m = merge, f = function(fr, fs, proto, iwl) { var arr = m && L.isArray(fr); for (var i in fs) { if (fs.hasOwnProperty(i)) { // We never want to overwrite the prototype // if (PROTO === i) { if (PROTO === i || '_yuid' === i) { continue; } // @TODO deal with the hasownprop issue // check white list if it was supplied if (!w || iwl || (i in w)) { // if the receiver has this property, it is an object, // and merge is specified, merge the two objects. if (m && L.isObject(fr[i], true)) { // console.log('aggregate RECURSE: ' + i); // @TODO recursive or no? // Y.mix(fr[i], fs[i]); // not recursive f(fr[i], fs[i], proto, true); // recursive // otherwise apply the property only if overwrite // is specified or the receiver doesn't have one. // @TODO make sure the 'arr' check isn't desructive } else if (!arr && (ov || !(i in fr))) { // console.log('hash: ' + i); fr[i] = fs[i]; // if merge is specified and the receiver is an array, // append the array item } else if (arr) { // console.log('array: ' + i); // @TODO probably will need to remove dups fr.push(fs[i]); } } } } _iefix(fr, fs, w); }; var rp = r.prototype, sp = s.prototype; switch (mode) { case 1: // proto to proto f(rp, sp, true); break; case 2: // object to object and proto to proto f(r, s); f(rp, sp, true); break; case 3: // proto to static f(r, sp, true); break; case 4: // static to proto f(rp, s); break; default: // object to object f(r, s); } return r; }; }, "@VERSION@"); /* * YUI object utilities * @module yui * @submodule object */ YUI.add("object", function(Y) { /** * Adds the following Object utilities to the YUI instance * @class YUI~object */ /** * Y.Object(o) returns a new object based upon the supplied object. * @method Object * @static * @param o the supplier object * @return {object} the new object */ Y.Object = function(o) { var F = function() {}; F.prototype = o; return new F(); }; var O = Y.Object, L = Y.Lang; /** * Determines whether or not the property was added * to the object instance. Returns false if the property is not present * in the object, or was inherited from the prototype. * * @deprecated Safari 1.x support has been removed, so this is simply a * wrapper for the native implementation. Use the native implementation * directly instead. * * @TODO Remove in PR2 * * @method Object.owns * @static * @param o {any} The object being testing * @param p {string} the property to look for * @return {boolean} true if the object has the property on the instance */ O.owns = function(o, p) { return (o && o.hasOwnProperty) ? o.hasOwnProperty(p) : false; }; /** * Returns an array containing the object's keys * @method Object.keys * @static * @param o an object * @return {string[]} the keys */ O.keys = function(o) { var a=[], i; for (i in o) { if (o.hasOwnProperty(i)) { a.push(i); } } return a; }; /** * Executes a function on each item. The function * receives the value, the key, and the object * as paramters (in that order). * @method Object.each * @static * @param o the object to iterate * @param f {function} the function to execute * @param c the execution context * @param proto {boolean} include proto * @return {YUI} the YUI instance */ O.each = function (o, f, c, proto) { var s = c || Y; for (var i in o) { if (proto || o.hasOwnProperty(i)) { f.call(s, o[i], i, o); } } return Y; }; }, "@VERSION@"); /* * YUI user agent detection * @module yui * @submodule ua */ YUI.add("ua", function(Y) { /** * Browser/platform detection * @class UA * @static */ Y.UA = function() { var 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 <-- Reports 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- Reports 1.8 * Firefox 3 alpha: 1.9a4 <-- Reports 1.9 * </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.1 * <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 * * </pre> * http://developer.apple.com/internet/safari/uamatrix.html * @property webkit * @type float * @static */ webkit: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 * @static */ mobile: null }; var ua=navigator.userAgent, m; // 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=parseFloat(m[1]); // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = "Apple"; // iPhone or iPod Touch } else { m=ua.match(/NokiaN[^\/]*/); if (m) { o.mobile = m[0]; // Nokia N-series, ex: NokiaN95 } } } 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=parseFloat(m[1]); 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=parseFloat(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=parseFloat(m[1]); } } } } } return o; }(); }, "@VERSION@"); /* * YUI setTimeout/setInterval abstraction * @module yui * @submodule later */ YUI.add("later", function(Y) { var L = Y.Lang; /** * 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]. * @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. */ var later = function(when, o, fn, data, periodic) { when = when || 0; o = o || {}; var m=fn, d=data, f, r; if (L.isString(fn)) { m = o[fn]; } if (!m) { Y.fail("method undefined"); } if (!L.isArray(d)) { d = [data]; } f = function() { m.apply(o, d); }; r = (periodic) ? setInterval(f, when) : setTimeout(f, when); return { interval: periodic, cancel: function() { if (this.interval) { clearInterval(r); } else { clearTimeout(r); } } }; }; Y.later = later; L.later = later; }, "@VERSION@"); YUI.add("get", function(Y) { var ua=Y.UA, L=Y.Lang; /** * 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 */ Y.Get = function() { /** * hash of queues to manage multiple requests * @property queues * @private */ var queues={}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx=0, /** * node index used to generate unique node ids * @property nidx * @type int * @private */ nidx=0, // ridx=0, // sandboxFrame=null, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ purging=false; /** * Generates an HTML element, this is not appended to a document * @method _node * @param type {string} the type of element * @param attr {string} the attributes * @param win {Window} optional window to create the element in * @return {HTMLElement} the generated node * @private */ var _node = function(type, attr, win) { var w = win || Y.config.win, d=w.document, n=d.createElement(type); for (var i in attr) { if (attr[i] && Y.Object.owns(attr, i)) { n.setAttribute(i, attr[i]); } } return n; }; /** * Generates a link node * @method _linkNode * @param url {string} the url for the css file * @param win {Window} optional window to create the node in * @return {HTMLElement} the generated node * @private */ var _linkNode = function(url, win, charset) { var c = charset || "utf-8"; return _node("link", { "id": "yui__dyn_" + (nidx++), "type": "text/css", "charset": c, "rel": "stylesheet", "href": url }, win); }; /** * Generates a script node * @method _scriptNode * @param url {string} the url for the script file * @param win {Window} optional window to create the node in * @return {HTMLElement} the generated node * @private */ var _scriptNode = function(url, win, charset) { var c = charset || "utf-8"; return _node("script", { "id": "yui__dyn_" + (nidx++), "type": "text/javascript", "charset": c, "src": url }, win); }; /** * Removes the nodes for the specified queue * @method _purge * @private */ var _purge = function(tId) { var q=queues[tId]; if (q) { var n=q.nodes, l=n.length, d=q.win.document, h=d.getElementsByTagName("head")[0]; if (q.insertBefore) { var s = _get(q.insertBefore, tId); if (s) { h = s.parentNode; } } for (var i=0; i<l; i=i+1) { h.removeChild(n[i]); } } q.nodes = []; }; /** * Returns the data payload for callback functions * @method _returnData * @private */ var _returnData = function(q, msg) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, purge: function() { _purge(this.tId); } }; }; /* * 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 id {string} the id of the request * @private */ var _fail = function(id, msg) { var q = queues[id]; if (q.timer) { q.timer.cancel(); } // execute failure callback if (q.onFailure) { var sc=q.context || q; q.onFailure.call(sc, _returnData(q, msg)); } }; var _get = 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; }; /** * The request is complete, so executing the requester's callback * @method _finish * @param id {string} the id of the request * @private */ var _finish = function(id) { var q = queues[id]; if (q.timer) { q.timer.cancel(); } q.finished = true; if (q.aborted) { var msg = "transaction " + id + " was aborted"; _fail(id, msg); return; } // execute success callback if (q.onSuccess) { var sc=q.context || q; q.onSuccess.call(sc, _returnData(q)); } }; /** * Timeout detected * @method _timeout * @param id {string} the id of the request * @private */ var _timeout = function(id) { var q = queues[id]; if (q.onTimeout) { var sc=q.context || q; q.onTimeout.call(sc, _returnData(q)); } }; /** * Loads the next item for a given request * @method _next * @param id {string} the id of the request * @param loaded {string} the url that was just loaded, if any * @private */ var _next = function(id, loaded) { var q = queues[id]; if (q.timer) { q.timer.cancel(); } if (q.aborted) { var msg = "transaction " + id + " was aborted"; _fail(id, msg); return; } if (loaded) { q.url.shift(); if (q.varName) { q.varName.shift(); } } else { // This is the first pass: make sure the url is an array q.url = (L.isString(q.url)) ? [q.url] : q.url; if (q.varName) { q.varName = (L.isString(q.varName)) ? [q.varName] : q.varName; } } var w=q.win, d=w.document, h=d.getElementsByTagName("head")[0], n; if (q.url.length === 0) { _finish(id); return; } var url = q.url[0]; // if the url is undefined, this is probably a trailing comma problem in IE if (!url) { q.url.shift(); return _next(id); } if (q.timeout) { q.timer = L.later(q.timeout, q, _timeout, id); } if (q.type === "script") { n = _scriptNode(url, w, q.charset); } else { n = _linkNode(url, w, q.charset); } // track this node's load progress _track(q.type, n, id, url, w, q.url.length); // add the node to the queue so we can return it to the user supplied callback q.nodes.push(n); // add it to the head or insert it before 'insertBefore' if (q.insertBefore) { var s = _get(q.insertBefore, id); if (s) { s.parentNode.insertBefore(n, s); } } else { h.appendChild(n); } // 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. if ((ua.webkit || ua.gecko) && q.type === "css") { _next(id, url); } }; /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ var _autoPurge = function() { if (purging) { return; } purging = true; for (var i in queues) { if (queues.hasOwnProperty(i)) { var 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 type {string} the type of node to insert * @param url {string} the url to load * @param opts the hash of options for this request * @private */ var _queue = function(type, url, opts) { var id = "q" + (qidx++); opts = opts || {}; if (qidx % Y.Get.PURGE_THRESH === 0) { _autoPurge(); } queues[id] = Y.merge(opts, { tId: id, type: type, url: url, finished: false, nodes: [] }); var q = queues[id]; q.win = q.win || Y.config.win; q.context = q.context || q; q.autopurge = ("autopurge" in q) ? q.autopurge : (type === "script") ? true : false; L.later(0, q, _next, id); return { tId: 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 _track * @param type {string} the type of node to track * @param n {HTMLElement} the node to track * @param id {string} the id of the request * @param url {string} the url that is being loaded * @param win {Window} the targeted window * @param qlength the number of remaining items in the queue, * including this one * @param trackfn {Function} function to execute when finished * the default is _next * @private */ var _track = function(type, n, id, url, win, qlength, trackfn) { var f = trackfn || _next; // 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; f(id, url); } }; // webkit prior to 3.x is no longer supported } else if (ua.webkit) { if (type === "script") { // Safari 3.x supports the load event for script nodes (DOM2) n.addEventListener("load", function() { f(id, url); }); } // 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. } else { n.onload = function() { f(id, url); }; n.onerror = function(e) { _fail(id, e + ": " + url); }; } }; return { /** * The number of request required before an automatic purge. * property PURGE_THRESH * @static * @type int * @default 20 */ PURGE_THRESH: 20, /** * Called by the the helper for detecting script load in Safari * @method _finalize * @static * @param id {string} the transaction id * @private */ _finalize: function(id) { L.later(0, null, _finish, id); }, /** * Abort a transaction * @method abort * @static * @param o {string|object} Either the tId or the object returned from * script() or css() */ abort: function(o) { var id = (L.isString(o)) ? o : o.tId; var 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 url {string|string[]} the url or urls to the script(s) * @param opts {object} 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>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>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>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</dd> * </dl> * <dt>charset</dt> * <dd>Node charset, default utf-8</dd> * <dt>timeout</dt> * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd> * <pre> * &nbsp;&nbsp;Y.Get.script( * &nbsp;&nbsp;["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js", * &nbsp;&nbsp;&nbsp;"http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], &#123; * &nbsp;&nbsp;&nbsp;&nbsp;onSuccess: function(o) &#123; * &nbsp;&nbsp;&nbsp;&nbsp;&#125;, * &nbsp;&nbsp;&nbsp;&nbsp;onFailure: function(o) &#123; * &nbsp;&nbsp;&nbsp;&nbsp;&#125;, * &nbsp;&nbsp;&nbsp;&nbsp;onTimeout: function(o) &#123; * &nbsp;&nbsp;&nbsp;&nbsp;&#125;, * &nbsp;&nbsp;&nbsp;&nbsp;data: "foo", * &nbsp;&nbsp;&nbsp;&nbsp;timeout: 10000, // 10 second timeout * &nbsp;&nbsp;&nbsp;&nbsp;context: Y, // make the YUI instance * &nbsp;&nbsp;&nbsp;&nbsp;// win: otherframe // target another window/frame * &nbsp;&nbsp;&nbsp;&nbsp;autopurge: true // allow the utility to choose when to remove the nodes * &nbsp;&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 url {string} the url or urls to the css file(s) * @param 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>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</dd> * </dl> * <pre> * Y.Get.css("http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css"); * </pre> * <pre> * &nbsp;&nbsp;Y.Get.css( * &nbsp;&nbsp;["http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css", * &nbsp;&nbsp;&nbsp;"http://yui.yahooapis.com/2.3.1/build/logger/assets/skins/sam/logger.css"], &#123; * &nbsp;&nbsp;&nbsp;&nbsp;insertBefore: 'custom-styles' // nodes will be inserted before the specified node * &nbsp;&nbsp;&#125;); * </pre> * @return {tId: string} an object containing info about the transaction */ css: function(url, opts) { return _queue("css", url, opts); } }; }(); }, "@VERSION@"); /** * 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 yui * @submodule loader */ /** * 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. * @class Loader * @constructor * @param o an optional set of configuration options. Valid options: * <ul> * <li>base: * The base dir</li> * <li>secureBase: * The secure base dir (not implemented)</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>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</li> * <li>timeout: * number of milliseconds before a timeout occurs when dynamically loading nodes. in 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>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> * </ul> */ // @TODO backed out the custom event changes so that the event system // isn't required in the seed build. If needed, we may want to // add them back if the event system is detected. /* * Executed when the loader successfully completes an insert operation * This can be subscribed to normally, or a listener can be passed * as an onSuccess config option. * @event success */ /* * Executed when the loader fails to complete an insert operation. * This can be subscribed to normally, or a listener can be passed * as an onFailure config option. * * @event failure */ /* * Executed when a Get operation times out. * This can be subscribed to normally, or a listener can be passed * as an onTimeout config option. * * @event timeout */ // http://yui.yahooapis.com/combo?2.5.2/build/yahoo/yahoo-min.js&2.5.2/build/dom/dom-min.js&2.5.2/build/event/event-min.js&2.5.2/build/autocomplete/autocomplete-min.js" YUI.add("loader", function(Y) { var BASE = 'base', CSS = 'css', JS = 'js', CSSRESET = 'cssreset', CSSFONTS = 'cssfonts', CSSGRIDS = 'cssgrids', CSSBASE = 'cssbase', CSS_AFTER = [CSSRESET, CSSFONTS, CSSGRIDS, 'cssreset-context', 'cssfonts-context', 'cssgrids-context'], YUI_CSS = ['reset', 'fonts', 'grids', 'base'], VERSION = '@VERSION@', ROOT = VERSION + '/build/', CONTEXT = '-context', META = { version: VERSION, root: ROOT, base: 'http://yui.yahooapis.com/' + ROOT, comboBase: 'http://yui.yahooapis.com/combo?', skin: { defaultSkin: 'sam', base: 'assets/skins/', path: 'skin.css', after: ['reset', 'fonts', 'grids', 'base'] //rollup: 3 }, modules: { dom: { requires: ['event'], submodules: { 'dom-base': { requires: ['event'] }, 'dom-style': { requires: ['dom-base'] }, 'dom-screen': { requires: ['dom-base', 'dom-style'] }, selector: { requires: ['dom-base'] } } }, node: { requires: ['dom'], submodules: { 'node-base': { requires: ['dom-base', 'selector'] }, 'node-style': { requires: ['dom-style', 'node-base'] }, 'node-screen': { requires: ['dom-screen', 'node-base'] }, 'node-event-simulate': { requires: ['node-base'] } } }, anim: { requires: [BASE, 'node'], submodules: { 'anim-base': { requires: ['base', 'node-style'] }, 'anim-color': { requires: ['anim-base'] }, 'anim-curve': { requires: ['anim-xy'] }, 'anim-easing': { }, 'anim-scroll': { requires: ['anim-base'] }, 'anim-xy': { requires: ['anim-base', 'node-screen'] }, 'anim-node-plugin': { requires: ['node', 'anim-base'] } } }, attribute: { requires: ['event'] }, base: { requires: ['attribute'] }, compat: { requires: ['node', 'dump', 'substitute'] }, classnamemanager: { }, console: { requires: ['widget', 'substitute'], skinnable: true }, cookie: { }, // Note: CSS attributes are modified programmatically to reduce metadata size // cssbase: { // after: CSS_AFTER // }, // cssgrids: { // requires: [CSSFONTS], // optional: [CSSRESET] // }, dd:{ submodules: { 'dd-ddm-base': { requires: ['node', BASE] }, 'dd-ddm':{ requires: ['dd-ddm-base'] }, 'dd-ddm-drop':{ requires: ['dd-ddm'] }, 'dd-drag':{ requires: ['dd-ddm-base'] }, 'dd-drop':{ requires: ['dd-ddm-drop'] }, 'dd-proxy':{ requires: ['dd-drag'] }, 'dd-constrain':{ requires: ['dd-drag', 'dd-proxy'] }, 'dd-plugin':{ requires: ['dd-drag'], optional: ['dd-constrain', 'dd-proxy'] }, 'dd-drop-plugin':{ requires: ['dd-drop'] } } }, dump: { }, event: { requires: ['oop'] }, get: { requires: ['yui-base'] }, io:{ submodules: { 'io-base': { requires: ['node'] }, 'io-xdr': { requires: ['io-base'] }, 'io-form': { requires: ['io-base'] }, 'io-upload-iframe': { requires: ['io-base'] }, 'io-queue': { requires: ['io-base'] } } }, json: { submodules: { 'json-parse': { }, 'json-stringify': { } } }, loader: { requires: ['get'] }, 'node-menunav': { requires: ['node', 'classnamemanager'], skinnable: true }, oop: { requires: ['yui-base'] }, overlay: { requires: ['widget', 'widget-position', 'widget-position-ext', 'widget-stack', 'widget-stdmod'], skinnable: true }, plugin: { requires: ['base'] }, profiler: { }, queue: { requires: ['node'] }, slider: { requires: ['widget', 'dd-constrain'], skinnable: true }, stylesheet: { }, substitute: { optional: ['dump'] }, widget: { requires: ['base', 'node', 'classnamemanager'], plugins: { 'widget-position': { }, 'widget-position-ext': { requires: ['widget-position'] }, 'widget-stack': { skinnable: true }, 'widget-stdmod': { } }, skinnable: true }, // Since YUI is required for everything else, it should not be specified as // a dependency. yui: { supersedes: ['yui-base', 'get', 'loader'] }, 'yui-base': { }, yuitest: { requires: ['substitute', 'node', 'json'] } } }; var _path = function(dir, file, type) { return dir + '/' + file + '-min.' + (type || CSS); }; var _cssmeta = function() { var mods = META.modules; // modify the meta info for YUI CSS for (var i=0; i<YUI_CSS.length; i=i+1) { var bname = YUI_CSS[i], mname = CSS + bname; mods[mname] = { type: CSS, path: _path(mname, bname) }; // define -context module var contextname = mname + CONTEXT; bname = bname + CONTEXT; mods[contextname] = { type: CSS, path: _path(mname, bname) }; if (mname == CSSGRIDS) { mods[mname].requires = [CSSFONTS]; mods[mname].optional = [CSSRESET]; mods[contextname].requires = [CSSFONTS + CONTEXT]; mods[contextname].optional = [CSSRESET + CONTEXT]; } else if (mname == CSSBASE) { mods[mname].after = CSS_AFTER; mods[contextname].after = CSS_AFTER; } } }(); Y.Env.meta = META; var L=Y.Lang, env=Y.Env, PROV = "_provides", SUPER = "_supersedes", REQ = "expanded"; Y.Loader = function(o) { /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ this._internalCallback = null; /** * Use the YUI environment listener to detect script load. This * is only switched on for Safari 2.x and below. * @property _useYahooListener * @private */ this._useYahooListener = false; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ this.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ this.onFailure = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ this.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ this.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ this.context = Y; /** * Data that is passed to all callbacks * @property data */ this.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ this.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @default utf-8 */ this.charset = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ this.base = Y.Env.meta.base; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ this.comboBase = Y.Env.meta.comboBase; /** * If configured, YUI JS resources will use the combo * handler * @property combine * @type boolean * @default true if a base dir isn't in the config */ this.combine = (!(BASE in o)); /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ this.ignoreRegistered = false; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ this.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, this value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ this.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ this.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[] */ this.force = null; /** * Should we allow rollups * @property allowRollup * @type boolean * @default true */ this.allowRollup = true; /** * 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} */ this.filter = null; /** * The list of requested modules * @property required * @type {string: boolean} */ this.required = {}; /** * The library metadata * @property moduleInfo */ // this.moduleInfo = Y.merge(Y.Env.meta.moduleInfo); this.moduleInfo = {}; /** * 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/', * * // The name of the rollup css file for the skin * path: 'skin.css', * * // The number of skinnable components requested that are * // required before using the rollup file rather than the * // individual component css files * rollup: 3, * * // 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 */ this.skin = Y.merge(Y.Env.meta.skin); var defaults = Y.Env.meta.modules; for (var i in defaults) { if (defaults.hasOwnProperty(i)) { this._internal = true; this.addModule(defaults[i], i); this._internal = false; } } /** * List of rollup files found in the library metadata * @property rollups */ this.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ this.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[] */ this.sorted = []; /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by the tool * @propery loaded * @type {string: boolean} */ this.loaded = {}; /** * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ this.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ this.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ this.inserted = {}; this.skipped = {}; // Y.on('yui:load', this.loadNext, this); this._config(o); }; Y.Loader.prototype = { FILTERS: { RAW: { 'searchExp': "-min\\.js", 'replaceStr': ".js" }, DEBUG: { 'searchExp': "-min\\.js", 'replaceStr': "-debug.js" } }, SKIN_PREFIX: "skin-", _config: function(o) { // apply config values if (o) { for (var i in o) { if (o.hasOwnProperty(i)) { var val = o[i]; if (i == 'require') { this.require(val); } else if (i == 'modules') { // add a hash of module definitions for (var j in val) { if (val.hasOwnProperty(j)) { this.addModule(val[j], j); } } } else { this[i] = val; } } } } // fix filter var f = this.filter; if (L.isString(f)) { f = f.toUpperCase(); this.filterName = f; this.filter = this.FILTERS[f]; } }, /** * 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 skin {string} the name of the skin * @param mod {string} optional: the name of a module to skin * @return {string} the full skin module name */ formatSkin: function(skin, mod) { var s = this.SKIN_PREFIX + skin; if (mod) { s = s + "-" + mod; } return s; }, /** * Reverses <code>formatSkin</code>, providing the skin name and * module name if the string matches the pattern for skins. * @method parseSkin * @param mod {string} the module name to parse * @return {skin: string, module: string} the parsed skin name * and module name, or null if the supplied string does not match * the skin pattern */ parseSkin: function(mod) { if (mod.indexOf(this.SKIN_PREFIX) === 0) { var a = mod.split("-"); return {skin: a[1], module: a[2]}; } return null; }, /** * Adds the skin def to the module info * @method _addSkin * @param skin {string} the name of the skin * @param mod {string} the name of the module * @param parent {string} 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 name = this.formatSkin(skin), info = this.moduleInfo, sinf = this.skin, ext = info[mod] && info[mod].ext; /* // Add a module definition for the skin rollup css if (!info[name]) { this.addModule({ 'name': name, 'type': 'css', 'path': sinf.base + skin + '/' + sinf.path, //'supersedes': '*', 'after': sinf.after, 'rollup': sinf.rollup, 'ext': ext }); } */ // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!info[name]) { var mdef = info[mod], pkg = mdef.pkg || mod; this.addModule({ 'name': name, 'type': 'css', 'after': sinf.after, 'path': (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', 'ext': ext }); } } return name; }, /** 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>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 has of submodules</dd> * </dl> * @method addModule * @param o An object containing the module data * @param name the module name (optional), required if not in the module data * @return {boolean} true if the module was added, false if * the object passed in did not provide all required attributes */ addModule: function(o, name) { name = name || o.name; o.name = name; if (!o || !o.name) { return false; } if (!o.type) { o.type = JS; } if (!o.path && !o.fullpath) { // o.path = name + "/" + name + "-min." + o.type; o.path = _path(name, name, o.type); } o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; o.requires = o.requires || []; this.moduleInfo[name] = o; // Handle submodule logic var subs = o.submodules, i; if (subs) { var sup = [], l=0; for (i in subs) { if (subs.hasOwnProperty(i)) { var s = subs[i]; s.path = _path(name, i, o.type); this.addModule(s, i); sup.push(i); if (o.skinnable) { var smod = this._addSkin(this.skin.defaultSkin, i, name); sup.push(smod.name); } l++; } } o.supersedes = sup; o.rollup = Math.min(l-1, 4); } var plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { var plug = plugins[i]; plug.path = _path(name, i, o.type); plug.requires = plug.requires || []; plug.requires.push(name); this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } this.dirty = true; return o; }, /** * Add a requirement for one or more module * @method require * @param what {string[] | string*} the modules to load */ require: function(what) { var a = (typeof what === "string") ? arguments : what; this.dirty = true; Y.mix(this.required, Y.Array.hash(a)); }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param mod The module definition from moduleInfo */ getRequires: function(mod) { if (!mod) { return []; } if (!this.dirty && mod.expanded) { return mod.expanded; } var i, d=[], r=mod.requires, o=mod.optional, info=this.moduleInfo, m, j, add; for (i=0; i<r.length; i=i+1) { d.push(r[i]); m = this.getModule(r[i]); add = this.getRequires(m); for (j=0;j<add.length;j=j+1) { d.push(add[j]); } } // get the requirements from superseded modules, if any r=mod.supersedes; if (r) { for (i=0; i<r.length; i=i+1) { d.push(r[i]); m = this.getModule(r[i]); add = this.getRequires(m); for (j=0;j<add.length;j=j+1) { d.push(add[j]); } } } if (o && this.loadOptional) { for (i=0; i<o.length; i=i+1) { d.push(o[i]); add = this.getRequires(info[o[i]]); for (j=0;j<add.length;j=j+1) { d.push(add[j]); } } } mod.expanded = Y.Object.keys(Y.Array.hash(d)); return mod.expanded; }, /** * Returns an object literal of the modules the supplied module satisfies * @method getProvides * @param name{string} The name of the module * @param notMe {string} don't add this module name, only include superseded modules * @return what this module provides */ getProvides: function(name, notMe) { var addMe = !(notMe), ckey = (addMe) ? PROV : SUPER, m = this.getModule(name), o = {}; if (!m) { return o; } if (m[ckey]) { return m[ckey]; } var s = m.supersedes, done={}, me = this; // use worker to break cycles var add = function(mm) { if (!done[mm]) { done[mm] = true; // we always want the return value normal behavior // (provides) for superseded modules. Y.mix(o, me.getProvides(mm)); } // else { // } }; // calculate superseded modules if (s) { for (var i=0; i<s.length; i=i+1) { add(s[i]); } } // supersedes cache m[SUPER] = o; // provides cache m[PROV] = Y.merge(o); m[PROV][name] = true; return m[ckey]; }, /** * Calculates the dependency tree, the result is stored in the sorted * property * @method calculate * @param o optional options object */ calculate: function(o) { if (o || this.dirty) { this._config(o); this._setup(); this._explode(); if (this.allowRollup) { this._rollup(); } this._reduce(); this._sort(); this.dirty = false; } }, /** * 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; // Create skin modules for (name in info) { if (info.hasOwnProperty(name)) { var m = info[name]; if (m && m.skinnable) { var o=this.skin.overrides, smod; if (o && o[name]) { for (i=0; i<o[name].length; i=i+1) { smod = this._addSkin(o[name][i], name); } } else { smod = this._addSkin(this.skin.defaultSkin, name); } m.requires.push(smod); } } } var l = Y.merge(this.inserted); // shallow clone // available modules if (!this.ignoreRegistered) { Y.mix(l, YUI.Env.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { // OU.appendArray(l, this.ignore); Y.mix(l, Y.Array.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=i+1) { if (this.force[i] in l) { delete l[this.force[i]]; } } } this.loaded = l; }, /** * 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, i, mod; for (i in r) { if (r.hasOwnProperty(i)) { mod = this.getModule(i); var req = this.getRequires(mod); if (req) { Y.mix(r, Y.Array.hash(req)); } } } }, getModule: function(name) { var m = this.moduleInfo[name]; // create the default module // if (!m) { // m = this.addModule({ext: false}, name); // } return m; }, /** * 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() * @method _rollup * @private */ _rollup: function() { var i, j, m, s, rollups={}, r=this.required, roll, info = this.moduleInfo; // find and cache rollup modules if (this.dirty || !this.rollups) { for (i in info) { if (info.hasOwnProperty(i)) { m = this.getModule(i); // if (m && m.rollup && m.supersedes) { if (m && m.rollup) { rollups[i] = m; } } } this.rollups = rollups; } // make as many passes as needed to pick up rollup rollups for (;;) { var rolled = false; // go through the rollup candidates for (i in rollups) { if (rollups.hasOwnProperty(i)) { // there can be only one if (!r[i] && !this.loaded[i]) { m =this.getModule(i); s = m.supersedes ||[]; roll=false; if (!m.rollup) { continue; } var c=0; // check the threshold for (j=0;j<s.length;j=j+1) { // if the superseded module is loaded, we can't load the rollup // if (this.loaded[s[j]] && (!_Y.dupsAllowed[s[j]])) { if (this.loaded[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]]) { 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; } } }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @private */ _reduce: function() { var i, j, s, m, r=this.required; for (i in r) { if (r.hasOwnProperty(i)) { // remove if already loaded if (i in this.loaded) { delete r[i]; // remove anything this module supersedes } else { m = this.getModule(i); s = m && m.supersedes; if (s) { for (j=0; j<s.length; j=j+1) { if (s[j] in r) { delete r[s[j]]; } } } } } } }, _attach: function() { // this is the full list of items the YUI needs attached, // which is needed if some dependencies are already on // the page without their dependencies. if (this.attaching) { Y._attach(this.attaching); } else { Y._attach(this.sorted); } this._pushEvents(); }, _onSuccess: function() { this._attach(); var skipped = this.skipped; for (var i in skipped) { if (skipped.hasOwnProperty(i)) { delete this.inserted[i]; } } this.skipped = {}; // this.fire('success', { // data: this.data // }); var f = this.onSuccess; if (f) { f.call(this.context, { msg: 'success', data: this.data, success: true }); } }, _onFailure: function(msg) { this._attach(); // this.fire('failure', { // msg: 'operation failed: ' + msg, // data: this.data // }); var f = this.onFailure; if (f) { f.call(this.context, { msg: 'failure: ' + msg, data: this.data, success: false }); } }, _onTimeout: function() { this._attach(); // this.fire('timeout', { // data: this.data // }); var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false }); } }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { // create an indexed list var s=Y.Object.keys(this.required), info=this.moduleInfo, loaded=this.loaded, me = this; // returns true if b is not loaded, and is required // directly or by means of modules it supersedes. var requires = function(aa, bb) { var mm=info[aa]; if (loaded[bb] || !mm) { return false; } var ii, rr = mm.expanded, after = mm.after, other=info[bb]; // check if this module requires the other directly if (rr && Y.Array.indexOf(rr, bb) > -1) { return true; } // check if this module should be sorted after the other if (after && Y.Array.indexOf(after, bb) > -1) { return true; } // check if this module requires one the other supersedes var ss=info[bb] && info[bb].supersedes; if (ss) { for (ii=0; ii<ss.length; ii=ii+1) { if (requires(aa, ss[ii])) { return true; } } } // external css files should be sorted below yui css if (mm.ext && mm.type == CSS && !other.ext && other.type == CSS) { return true; } return false; }; // pointer to the first unsorted item var p=0; // keep going until we make a pass without moving anything for (;;) { var l=s.length, a, b, j, k, moved=false; // start the loop after items that are already sorted for (j=p; j<l; j=j+1) { // 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=k+1) { if (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]); 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 = p + 1; } } // when we make it here and moved is false, we are // finished sorting if (!moved) { break; } } this.sorted = s; }, /** * 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 o optional options object * @param type {string} the type of dependency to insert */ insert: function(o, type) { // build the dependency list this.calculate(o); if (!type) { var self = this; this._internalCallback = function() { self._internalCallback = null; self.insert(null, JS); }; this.insert(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 = {}; // keep the loadType (js, css or undefined) cached this.loadType = type; // start the load this.loadNext(); }, /** * 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 mname {string} 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, self=this, type=this.loadType, fn; // @TODO this will need to handle the two phase insert when // CSS support is added if (this.combine && (!this._combineComplete[type])) { this._combining = []; s=this.sorted; len=s.length; url=this.comboBase; for (i=0; i<len; i=i+1) { m = this.getModule(s[i]); // @TODO we can't combine CSS yet until we deliver files with absolute paths to the assets // Do not try to combine non-yui JS if (m && m.type === this.loadType && !m.ext) { url += this.root + m.path; if (i < len-1) { url += '&'; } this._combining.push(s[i]); } } if (this._combining.length) { var callback=function(o) { this._combineComplete[type] = true; var c=this._combining, len=c.length, i, m; for (i=0; i<len; i=i+1) { this.inserted[c[i]] = true; } this.loadNext(o.data); }; fn =(type === CSS) ? Y.Get.css : Y.Get.script; // @TODO get rid of the redundant Get code fn(this._filter(url), { data: this._loading, onSuccess: callback, onFailure: this._onFailure, onTimeout: this._onTimeout, insertBefore: this.insertBefore, charset: this.charset, timeout: this.timeout, context: self }); return; } else { this._combineComplete[type] = true; } } if (mname) { // if the module that was just loaded isn't what we were expecting, // continue to wait if (mname !== this._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 this.inserted[mname] = true; // this.fire('progress', { // name: mname, // data: this.data // }); if (this.onProgress) { this.onProgress.call(this.context, { name: mname, data: this.data }); } } s=this.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 this.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] === this._loading) { return; } // log("inserting " + s[i]); m = this.getModule(s[i]); if (!m) { var msg = "Undefined module " + s[i] + " skipped"; this.inserted[s[i]] = true; this.skipped[s[i]] = true; continue; // this.fire('failure', { // msg: msg, // data: this.data // }); } // The load type is stored to offer the possibility to load // the css separately from the script. if (!type || type === m.type) { this._loading = s[i]; fn = (m.type === CSS) ? Y.Get.css : Y.Get.script; var onsuccess=function(o) { self.loadNext(o.data); }; url = (m.fullpath) ? this._filter(m.fullpath) : this._url(m.path, s[i]); self = this; fn(url, { data: s[i], onSuccess: onsuccess, insertBefore: this.insertBefore, charset: this.charset, onFailure: this._onFailure, onTimeout: this._onTimeout, timeout: this.timeout, context: self }); return; } } // we are finished this._loading = null; fn = this._internalCallback; // internal callback for loading css first if (fn) { this._internalCallback = null; fn.call(this); // } else if (this.onSuccess) { } else { // call Y.use passing this instance. Y will use the sorted // dependency list. this._onSuccess(); } }, /** * In IE, the onAvailable/onDOMReady events need help when Event is * loaded dynamically * @method _pushEvents * @param {Function} optional function reference * @private */ _pushEvents: function() { if (Y.Event) { Y.Event._load(); } }, /** * Apply filter defined for this instance to a url/path * method _filter * @param u {string} the string to filter * @return {string} the filtered string * @private */ _filter: function(u) { var f = this.filter; if (u && f) { var useFilter = true; if (this.filterName == "DEBUG") { var exc = this.logExclude, inc = this.logInclude; if (inc && !(name in inc)) { useFilter = false; } else if (exc && (name in exc)) { useFilter = false; } } if (useFilter) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * method _url * @param path {string} the path fragment * @return {string} the full url * @private */ _url: function(path, name) { return this._filter((this.base || "") + path); } }; // Y.augment(Y.Loader, Y.Event.Target); }, "@VERSION@"); /* * YUI initializer * @module yui * @submodule init */ (function() { var min = ['yui-base', 'log', 'lang', 'array', 'core'], core, M = function(Y) { var C = Y.config; // apply the minimal required functionality Y.use.apply(Y, min); if (C.core) { core = C.core; } else { core = ["object", "ua", "later"]; core.push( "get", "loader"); } Y.use.apply(Y, core); }; YUI.add("yui", M, "@VERSION@"); // { // the following will be bound automatically when this code is loaded // use: core // }); })();
src/frontend/components/DummyEventCreate.js
Bernie-2016/ground-control
import React from 'react'; import Relay from 'react-relay'; export default class DummyEventCreate extends React.Component { render() { window.location.reload(); return <div></div> } }
src/atoms/archive-list-item/stories.js
dsmjs/components
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ import React from 'react'; import any from '@travi/any'; import storyRouter from 'storybook-router'; import {linkTo} from '@storybook/addon-links'; import ArchiveListItem from './component'; const meeting = { node: { fields: {slug: '/meeting-1'}, frontmatter: { date: any.date(), talks: [ {talk: {frontmatter: {title: any.sentence()}}}, {talk: {frontmatter: {title: 'This is a `title` with _markdown_'}}} ] } } }; export default { title: 'Atoms/Archive List-Item', decorators: [storyRouter({'/meeting-1': linkTo('Organisms/Meeting', 'current')})] }; export const Default = () => <ArchiveListItem meeting={meeting} />; Default.story = { name: 'default' };
frontend/jqwidgets/jqwidgets-react/react_jqxnotification.js
liamray/nexl-js
/* jQWidgets v5.7.2 (2018-Apr) Copyright (c) 2011-2018 jQWidgets. License: https://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export const jqx = window.jqx; export default class JqxNotification extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['appendContainer','autoOpen','animationOpenDelay','animationCloseDelay','autoClose','autoCloseDelay','blink','browserBoundsOffset','closeOnClick','disabled','height','hoverOpacity','icon','notificationOffset','opacity','position','rtl','showCloseButton','template','theme','width']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxNotification(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxNotification('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxNotification(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; appendContainer(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('appendContainer', arg) } else { return JQXLite(this.componentSelector).jqxNotification('appendContainer'); } }; autoOpen(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('autoOpen', arg) } else { return JQXLite(this.componentSelector).jqxNotification('autoOpen'); } }; animationOpenDelay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('animationOpenDelay', arg) } else { return JQXLite(this.componentSelector).jqxNotification('animationOpenDelay'); } }; animationCloseDelay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('animationCloseDelay', arg) } else { return JQXLite(this.componentSelector).jqxNotification('animationCloseDelay'); } }; autoClose(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('autoClose', arg) } else { return JQXLite(this.componentSelector).jqxNotification('autoClose'); } }; autoCloseDelay(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('autoCloseDelay', arg) } else { return JQXLite(this.componentSelector).jqxNotification('autoCloseDelay'); } }; blink(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('blink', arg) } else { return JQXLite(this.componentSelector).jqxNotification('blink'); } }; browserBoundsOffset(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('browserBoundsOffset', arg) } else { return JQXLite(this.componentSelector).jqxNotification('browserBoundsOffset'); } }; closeOnClick(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('closeOnClick', arg) } else { return JQXLite(this.componentSelector).jqxNotification('closeOnClick'); } }; disabled(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('disabled', arg) } else { return JQXLite(this.componentSelector).jqxNotification('disabled'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('height', arg) } else { return JQXLite(this.componentSelector).jqxNotification('height'); } }; hoverOpacity(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('hoverOpacity', arg) } else { return JQXLite(this.componentSelector).jqxNotification('hoverOpacity'); } }; icon(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('icon', arg) } else { return JQXLite(this.componentSelector).jqxNotification('icon'); } }; notificationOffset(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('notificationOffset', arg) } else { return JQXLite(this.componentSelector).jqxNotification('notificationOffset'); } }; opacity(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('opacity', arg) } else { return JQXLite(this.componentSelector).jqxNotification('opacity'); } }; position(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('position', arg) } else { return JQXLite(this.componentSelector).jqxNotification('position'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('rtl', arg) } else { return JQXLite(this.componentSelector).jqxNotification('rtl'); } }; showCloseButton(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('showCloseButton', arg) } else { return JQXLite(this.componentSelector).jqxNotification('showCloseButton'); } }; template(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('template', arg) } else { return JQXLite(this.componentSelector).jqxNotification('template'); } }; theme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('theme', arg) } else { return JQXLite(this.componentSelector).jqxNotification('theme'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxNotification('width', arg) } else { return JQXLite(this.componentSelector).jqxNotification('width'); } }; closeAll() { JQXLite(this.componentSelector).jqxNotification('closeAll'); }; closeLast() { JQXLite(this.componentSelector).jqxNotification('closeLast'); }; destroy() { JQXLite(this.componentSelector).jqxNotification('destroy'); }; open() { JQXLite(this.componentSelector).jqxNotification('open'); }; refresh() { JQXLite(this.componentSelector).jqxNotification('refresh'); }; performRender() { JQXLite(this.componentSelector).jqxNotification('render'); }; render() { let id = 'jqxNotification' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}>{this.props.value}{this.props.children}</div> ) }; };
ReactFlux/node_modules/reactify/node_modules/react-tools/src/browser/ui/dom/components/__tests__/ReactDOMIframe-test.js
wandarkaf/React-Bible
/** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; describe('ReactDOMIframe', function() { var React; var ReactTestUtils; beforeEach(function() { React = require('React'); ReactTestUtils = require('ReactTestUtils'); }); it('should trigger load events', function() { var onLoadSpy = jasmine.createSpy(); var iframe = React.createElement('iframe', {onLoad: onLoadSpy}); iframe = ReactTestUtils.renderIntoDocument(iframe); var loadEvent = document.createEvent('Event'); loadEvent.initEvent('load', false, false); iframe.getDOMNode().dispatchEvent(loadEvent); expect(onLoadSpy).toHaveBeenCalled(); }); });
ajax/libs/yui/3.10.2/event-focus/event-focus-min.js
kevinburke/cdnjs
YUI.add("event-focus",function(e,t){function u(t,r,u){var a="_"+t+"Notifiers";e.Event.define(t,{_useActivate:o,_attach:function(i,s,o){return e.DOM.isWindow(i)?n._attach([t,function(e){s.fire(e)},i]):n._attach([r,this._proxy,i,this,s,o],{capture:!0})},_proxy:function(t,r,i){var s=t.target,f=t.currentTarget,l=s.getData(a),c=e.stamp(f._node),h=o||s!==f,p;r.currentTarget=i?s:f,r.container=i?f:null,l?h=!0:(l={},s.setData(a,l),h&&(p=n._attach([u,this._notify,s._node]).sub,p.once=!0)),l[c]||(l[c]=[]),l[c].push(r),h||this._notify(t)},_notify:function(t,n){var r=t.currentTarget,i=r.getData(a),o=r.ancestors(),u=r.get("ownerDocument"),f=[],l=i?e.Object.keys(i).length:0,c,h,p,d,v,m,g,y,b,w;r.clearData(a),o.push(r),u&&o.unshift(u),o._nodes.reverse(),l&&(m=l,o.some(function(t){var n=e.stamp(t),r=i[n],s,o;if(r){l--;for(s=0,o=r.length;s<o;++s)r[s].handle.sub.filter&&f.push(r[s])}return!l}),l=m);while(l&&(c=o.shift())){d=e.stamp(c),h=i[d];if(h){for(g=0,y=h.length;g<y;++g){p=h[g],b=p.handle.sub,v=!0,t.currentTarget=c,b.filter&&(v=b.filter.apply(c,[c,t].concat(b.args||[])),f.splice(s(f,p),1)),v&&(t.container=p.container,w=p.fire(t));if(w===!1||t.stopped===2)break}delete h[d],l--}if(t.stopped!==2)for(g=0,y=f.length;g<y;++g){p=f[g],b=p.handle.sub,b.filter.apply(c,[c,t].concat(b.args||[]))&&(t.container=p.container,t.currentTarget=c,w=p.fire(t));if(w===!1||t.stopped===2)break}if(t.stopped)break}},on:function(e,t,n){t.handle=this._attach(e._node,n)},detach:function(e,t){t.handle.detach()},delegate:function(t,n,r,s){i(s)&&(n.filter=function(n){return e.Selector.test(n._node,s,t===n?null:t._node)}),n.handle=this._attach(t._node,r,!0)},detachDelegate:function(e,t){t.handle.detach()}},!0)}var n=e.Event,r=e.Lang,i=r.isString,s=e.Array.indexOf,o=function(){var t=!1,n=e.config.doc,r;return n&&(r=n.createElement("p"),r.setAttribute("onbeforeactivate",";"),t=r.onbeforeactivate!==undefined),t}();o?(u("focus","beforeactivate","focusin"),u("blur","beforedeactivate","focusout")):(u("focus","focus","focus"),u("blur","blur","blur"))},"@VERSION@",{requires:["event-synthetic"]});
src/svg-icons/notification/do-not-disturb-alt.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationDoNotDisturbAlt = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zM4 12c0-4.4 3.6-8 8-8 1.8 0 3.5.6 4.9 1.7L5.7 16.9C4.6 15.5 4 13.8 4 12zm8 8c-1.8 0-3.5-.6-4.9-1.7L18.3 7.1C19.4 8.5 20 10.2 20 12c0 4.4-3.6 8-8 8z"/> </SvgIcon> ); NotificationDoNotDisturbAlt = pure(NotificationDoNotDisturbAlt); NotificationDoNotDisturbAlt.displayName = 'NotificationDoNotDisturbAlt'; NotificationDoNotDisturbAlt.muiName = 'SvgIcon'; export default NotificationDoNotDisturbAlt;
fixtures/fiber-debugger/src/Editor.js
with-git/react
import React, { Component } from 'react'; class Editor extends Component { constructor(props) { super(props); this.state = { code: props.code }; } render() { return ( <div style={{ height: '100%', width: '100%' }}> <textarea value={this.state.code} onChange={e => this.setState({ code: e.target.value })} style={{ height: '80%', width: '100%', fontSize: '15px' }} /> <div style={{ height: '20%', textAlign: 'center' }}> <button onClick={() => this.props.onClose(this.state.code)} style={{ fontSize: 'large' }}> Run </button> </div> </div> ) } } export default Editor;
src/IconDropdown/index.js
christianalfoni/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles.css'; import Icon from '../Icon'; import classNames from 'classnames'; function IconDropdown(props) { return ( <div className={classNames(styles.wrapper, { [props.className]: props.className })} onClick={props.onClick} > <Icon className={styles.icon} icon={props.icon} size="standard" /> <Icon icon="icon-arrow_drop_down" size="standard" /> </div> ); } IconDropdown.propTypes = { className: PropTypes.string, icon: PropTypes.string, onClick: PropTypes.func }; export default IconDropdown;
ajax/libs/forerunnerdb/1.3.703/fdb-core.min.js
pombredanne/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":5,"../lib/Shim.IE8":29}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":25,"./Shared":28}],3:[function(a,b,c){"use strict";var d,e;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n;d=a("./Shared");var o=function(a,b){this.init.apply(this,arguments)};o.prototype.init=function(a,b){this.sharedPathSolver=n,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Events"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.CRUD"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Sorting"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.Updating"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=new h,d.synthesize(o.prototype,"deferredCalls"),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"metaData"),d.synthesize(o.prototype,"capped"),d.synthesize(o.prototype,"cappedSize"),o.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},o.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},o.prototype.data=function(){return this._data},o.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},o.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},o.prototype._onInsert=function(a,b){this.emit("insert",a,b)},o.prototype._onUpdate=function(a){this.emit("update",a)},o.prototype._onRemove=function(a){this.emit("remove",a)},o.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(o.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"mongoEmulation"),o.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),o.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},o.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},o.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},o.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},o.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},o.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},o.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},o.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length&&(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},o.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},o.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},o.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},o.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},o.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},o.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},o.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},o.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},o.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},o.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},o.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},o.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},o.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},o.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},o.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},o.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},o.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},o.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},o.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new o,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(o.prototype,"subsetOf"),o.prototype.isSubsetOf=function(a){return this._subsetOf===a},o.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},o.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},o.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new o,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},o.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},o.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},o.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},o.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},o.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},o.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},o.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},o.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},o.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},o.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},o.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},o.prototype.sort=function(a,b){var c=this,d=n.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(n.get(a,f.path),n.get(b,f.path)):-1===f.value&&(g=c.sortDesc(n.get(a,f.path),n.get(b,f.path))),0!==g)return g;return g}),b},o.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},o.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t], n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},o.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},o.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new o("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},o.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},o.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},o.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else c=new i(a,b,this);else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},o.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},o.prototype.lastOp=function(){return this._metrics.list()},o.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},o.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),o.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof o?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new o(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=o},{"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],5:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],6:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":25,"./Shared":28}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":28}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":23,"./Shared":28}],13:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],14:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainWillSend:function(){return Boolean(this._chain)},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c; b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":24,"./Serialiser":27}],16:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],17:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":24}],18:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],21:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":24}],22:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":25,"./Shared":28}],24:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],25:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":28}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":28}],27:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.703",modules:{},plugins:{},index:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}]},{},[1]);
src/svg-icons/image/timer-3.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTimer3 = (props) => ( <SvgIcon {...props}> <path d="M11.61 12.97c-.16-.24-.36-.46-.62-.65-.25-.19-.56-.35-.93-.48.3-.14.57-.3.8-.5.23-.2.42-.41.57-.64.15-.23.27-.46.34-.71.08-.24.11-.49.11-.73 0-.55-.09-1.04-.28-1.46-.18-.42-.44-.77-.78-1.06-.33-.28-.73-.5-1.2-.64-.45-.13-.97-.2-1.53-.2-.55 0-1.06.08-1.52.24-.47.17-.87.4-1.2.69-.33.29-.6.63-.78 1.03-.2.39-.29.83-.29 1.29h1.98c0-.26.05-.49.14-.69.09-.2.22-.38.38-.52.17-.14.36-.25.58-.33.22-.08.46-.12.73-.12.61 0 1.06.16 1.36.47.3.31.44.75.44 1.32 0 .27-.04.52-.12.74-.08.22-.21.41-.38.57-.17.16-.38.28-.63.37-.25.09-.55.13-.89.13H6.72v1.57H7.9c.34 0 .64.04.91.11.27.08.5.19.69.35.19.16.34.36.44.61.1.24.16.54.16.87 0 .62-.18 1.09-.53 1.42-.35.33-.84.49-1.45.49-.29 0-.56-.04-.8-.13-.24-.08-.44-.2-.61-.36-.17-.16-.3-.34-.39-.56-.09-.22-.14-.46-.14-.72H4.19c0 .55.11 1.03.32 1.45.21.42.5.77.86 1.05s.77.49 1.24.63.96.21 1.48.21c.57 0 1.09-.08 1.58-.23.49-.15.91-.38 1.26-.68.36-.3.64-.66.84-1.1.2-.43.3-.93.3-1.48 0-.29-.04-.58-.11-.86-.08-.25-.19-.51-.35-.76zm9.26 1.4c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39s.03-.28.09-.41c.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59-.43-.15-.92-.22-1.46-.22-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.68.23.96c.15.28.37.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02z"/> </SvgIcon> ); ImageTimer3 = pure(ImageTimer3); ImageTimer3.displayName = 'ImageTimer3'; ImageTimer3.muiName = 'SvgIcon'; export default ImageTimer3;
src/routes/notFound/index.js
stanxii/laiico
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present 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 Layout from '../../components/Layout'; import NotFound from './NotFound'; const title = 'Page Not Found'; export default { path: '*', action() { return { title, component: <Layout><NotFound title={title} /></Layout>, status: 404, }; }, };
ajax/libs/react-instantsearch/5.0.0-beta.0/Dom.js
holtkamp/cdnjs
/*! ReactInstantSearch 5.0.0-beta.0 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Dom = {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } 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); } function nextTick(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); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd() { return '/'; } function chdir(dir) { throw new Error('process.chdir is not supported'); } function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { return new Date().getTime(); }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp) { var clocktime = performanceNow.call(performance) * 1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor(clocktime % 1 * 1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds < 0) { seconds--; nanoseconds += 1e9; } } return [seconds, nanoseconds]; } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function commonjsRequire () { throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; var emptyFunction_1 = emptyFunction; function invariant(condition, format, a, b, c, d, e, f) { if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } var invariant_1 = invariant; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // It is still safe when called from React. return; } invariant_1( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction_1; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = factoryWithThrowingShims(); } }); /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$1.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$1.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto$2 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$2.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto$2.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty$2.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$3.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]'; var undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]'; var funcTag = '[object Function]'; var genTag = '[object GeneratorFunction]'; var proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto$1 = Function.prototype; var objectProto$4 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.toString; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$4.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } var _getValue = getValue; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = _getValue(object, key); return _baseIsNative(value) ? value : undefined; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var DataView = _getNative(_root, 'DataView'); var _DataView = DataView; /* Built-in method references that are verified to be native. */ var Map = _getNative(_root, 'Map'); var _Map = Map; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set = _getNative(_root, 'Set'); var _Set = Set; /* Built-in method references that are verified to be native. */ var WeakMap = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap; /** `Object#toString` result references. */ var mapTag = '[object Map]'; var objectTag = '[object Object]'; var promiseTag = '[object Promise]'; var setTag = '[object Set]'; var weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = _toSource(_DataView); var mapCtorString = _toSource(_Map); var promiseCtorString = _toSource(_Promise); var setCtorString = _toSource(_Set); var weakMapCtorString = _toSource(_WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag) || (_Map && getTag(new _Map) != mapTag) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag) || (_WeakMap && getTag(new _WeakMap) != weakMapTag)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } var _getTag = getTag; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$5.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$4.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } var isLength_1 = isLength; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]'; var arrayTag = '[object Array]'; var boolTag = '[object Boolean]'; var dateTag = '[object Date]'; var errorTag = '[object Error]'; var funcTag$1 = '[object Function]'; var mapTag$1 = '[object Map]'; var numberTag = '[object Number]'; var objectTag$1 = '[object Object]'; var regexpTag = '[object RegExp]'; var setTag$1 = '[object Set]'; var stringTag = '[object String]'; var weakMapTag$1 = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]'; var dataViewTag$1 = '[object DataView]'; var float32Tag = '[object Float32Array]'; var float64Tag = '[object Float64Array]'; var int8Tag = '[object Int8Array]'; var int16Tag = '[object Int16Array]'; var int32Tag = '[object Int32Array]'; var uint8Tag = '[object Uint8Array]'; var uint8ClampedTag = '[object Uint8ClampedArray]'; var uint16Tag = '[object Uint16Array]'; var uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag] = typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] = typedArrayTags[setTag$1] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag$1] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** `Object#toString` result references. */ var mapTag$2 = '[object Map]'; var setTag$2 = '[object Set]'; /** Used for built-in method references. */ var objectProto$6 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$6.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike_1(value) && (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { return !value.length; } var tag = _getTag(value); if (tag == mapTag$2 || tag == setTag$2) { return !value.size; } if (_isPrototype(value)) { return !_baseKeys(value).length; } for (var key in value) { if (hasOwnProperty$5.call(value, key)) { return false; } } return true; } var isEmpty_1 = isEmpty; /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } var eq_1 = eq; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var _listCacheDelete = listCacheDelete; /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = _assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } var _listCacheGet = listCacheGet; /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return _assocIndexOf(this.__data__, key) > -1; } var _listCacheHas = listCacheHas; /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var _listCacheSet = listCacheSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = _listCacheClear; ListCache.prototype['delete'] = _listCacheDelete; ListCache.prototype.get = _listCacheGet; ListCache.prototype.has = _listCacheHas; ListCache.prototype.set = _listCacheSet; var _ListCache = ListCache; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } var _stackDelete = stackDelete; /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } var _stackGet = stackGet; /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } var _stackHas = stackHas; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$7.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (_nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty$6.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$8.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; return this; } var _hashSet = hashSet; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = _hashClear; Hash.prototype['delete'] = _hashDelete; Hash.prototype.get = _hashGet; Hash.prototype.has = _hashHas; Hash.prototype.set = _hashSet; var _Hash = Hash; /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new _Hash, 'map': new (_Map || _ListCache), 'string': new _Hash }; } var _mapCacheClear = mapCacheClear; /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } var _isKeyable = isKeyable; /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } var _getMapData = getMapData; /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = _getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } var _mapCacheDelete = mapCacheDelete; /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return _getMapData(this, key).get(key); } var _mapCacheGet = mapCacheGet; /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return _getMapData(this, key).has(key); } var _mapCacheHas = mapCacheHas; /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = _getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var _mapCacheSet = mapCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = _mapCacheClear; MapCache.prototype['delete'] = _mapCacheDelete; MapCache.prototype.get = _mapCacheGet; MapCache.prototype.has = _mapCacheHas; MapCache.prototype.set = _mapCacheSet; var _MapCache = MapCache; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof _ListCache) { var pairs = data.__data__; if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new _MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } var _stackSet = stackSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new _ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = _stackClear; Stack.prototype['delete'] = _stackDelete; Stack.prototype.get = _stackGet; Stack.prototype.has = _stackHas; Stack.prototype.set = _stackSet; var _Stack = Stack; /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } var _arrayEach = arrayEach; var defineProperty = (function() { try { var func = _getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); var _defineProperty = defineProperty; /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && _defineProperty) { _defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } var _baseAssignValue = baseAssignValue; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$9.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty$8.call(object, key) && eq_1(objValue, value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignValue = assignValue; /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { _baseAssignValue(object, key, newValue); } else { _assignValue(object, key, newValue); } } return object; } var _copyObject = copyObject; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER$1 : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used for built-in method references. */ var objectProto$10 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$10.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$9.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && _copyObject(source, keys_1(source), object); } var _baseAssign = baseAssign; /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var _nativeKeysIn = nativeKeysIn; /** Used for built-in method references. */ var objectProto$11 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$10 = objectProto$11.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject_1(object)) { return _nativeKeysIn(object); } var isProto = _isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$10.call(object, key)))) { result.push(key); } } return result; } var _baseKeysIn = baseKeysIn; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn$1(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); } var keysIn_1 = keysIn$1; /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && _copyObject(source, keysIn_1(source), object); } var _baseAssignIn = baseAssignIn; var _cloneBuffer = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; }); /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } var _copyArray = copyArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var _arrayFilter = arrayFilter; /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$12 = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$12.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable$1.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return _copyObject(source, _getSymbols(source), object); } var _copySymbols = copySymbols; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var _arrayPush = arrayPush; /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols$1 = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) { var result = []; while (object) { _arrayPush(result, _getSymbols(object)); object = _getPrototype(object); } return result; }; var _getSymbolsIn = getSymbolsIn; /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return _copyObject(source, _getSymbolsIn(source), object); } var _copySymbolsIn = copySymbolsIn; /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return _baseGetAllKeys(object, keys_1, _getSymbols); } var _getAllKeys = getAllKeys; /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn); } var _getAllKeysIn = getAllKeysIn; /** Used for built-in method references. */ var objectProto$13 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$11 = objectProto$13.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty$11.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } var _initCloneArray = initCloneArray; /** Built-in value references. */ var Uint8Array = _root.Uint8Array; var _Uint8Array = Uint8Array; /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new _Uint8Array(result).set(new _Uint8Array(arrayBuffer)); return result; } var _cloneArrayBuffer = cloneArrayBuffer; /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } var _cloneDataView = cloneDataView; /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } var _addMapEntry = addMapEntry; /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } var _arrayReduce = arrayReduce; /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var _mapToArray = mapToArray; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(_mapToArray(map), CLONE_DEEP_FLAG) : _mapToArray(map); return _arrayReduce(array, _addMapEntry, new map.constructor); } var _cloneMap = cloneMap; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var _cloneRegExp = cloneRegExp; /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } var _addSetEntry = addSetEntry; /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var _setToArray = setToArray; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 1; /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(_setToArray(set), CLONE_DEEP_FLAG$1) : _setToArray(set); return _arrayReduce(array, _addSetEntry, new set.constructor); } var _cloneSet = cloneSet; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined; var symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } var _cloneSymbol = cloneSymbol; /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } var _cloneTypedArray = cloneTypedArray; /** `Object#toString` result references. */ var boolTag$1 = '[object Boolean]'; var dateTag$1 = '[object Date]'; var mapTag$3 = '[object Map]'; var numberTag$1 = '[object Number]'; var regexpTag$1 = '[object RegExp]'; var setTag$3 = '[object Set]'; var stringTag$1 = '[object String]'; var symbolTag = '[object Symbol]'; var arrayBufferTag$1 = '[object ArrayBuffer]'; var dataViewTag$2 = '[object DataView]'; var float32Tag$1 = '[object Float32Array]'; var float64Tag$1 = '[object Float64Array]'; var int8Tag$1 = '[object Int8Array]'; var int16Tag$1 = '[object Int16Array]'; var int32Tag$1 = '[object Int32Array]'; var uint8Tag$1 = '[object Uint8Array]'; var uint8ClampedTag$1 = '[object Uint8ClampedArray]'; var uint16Tag$1 = '[object Uint16Array]'; var uint32Tag$1 = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag$1: return _cloneArrayBuffer(object); case boolTag$1: case dateTag$1: return new Ctor(+object); case dataViewTag$2: return _cloneDataView(object, isDeep); case float32Tag$1: case float64Tag$1: case int8Tag$1: case int16Tag$1: case int32Tag$1: case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: return _cloneTypedArray(object, isDeep); case mapTag$3: return _cloneMap(object, isDeep, cloneFunc); case numberTag$1: case stringTag$1: return new Ctor(object); case regexpTag$1: return _cloneRegExp(object); case setTag$3: return _cloneSet(object, isDeep, cloneFunc); case symbolTag: return _cloneSymbol(object); } } var _initCloneByTag = initCloneByTag; /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject_1(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); var _baseCreate = baseCreate; /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !_isPrototype(object)) ? _baseCreate(_getPrototype(object)) : {}; } var _initCloneObject = initCloneObject; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$2 = 1; var CLONE_FLAT_FLAG = 2; var CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]'; var arrayTag$1 = '[object Array]'; var boolTag$2 = '[object Boolean]'; var dateTag$2 = '[object Date]'; var errorTag$1 = '[object Error]'; var funcTag$2 = '[object Function]'; var genTag$1 = '[object GeneratorFunction]'; var mapTag$4 = '[object Map]'; var numberTag$2 = '[object Number]'; var objectTag$2 = '[object Object]'; var regexpTag$2 = '[object RegExp]'; var setTag$4 = '[object Set]'; var stringTag$2 = '[object String]'; var symbolTag$1 = '[object Symbol]'; var weakMapTag$2 = '[object WeakMap]'; var arrayBufferTag$2 = '[object ArrayBuffer]'; var dataViewTag$3 = '[object DataView]'; var float32Tag$2 = '[object Float32Array]'; var float64Tag$2 = '[object Float64Array]'; var int8Tag$2 = '[object Int8Array]'; var int16Tag$2 = '[object Int16Array]'; var int32Tag$2 = '[object Int32Array]'; var uint8Tag$2 = '[object Uint8Array]'; var uint8ClampedTag$2 = '[object Uint8ClampedArray]'; var uint16Tag$2 = '[object Uint16Array]'; var uint32Tag$2 = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] = cloneableTags[boolTag$2] = cloneableTags[dateTag$2] = cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] = cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] = cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] = cloneableTags[numberTag$2] = cloneableTags[objectTag$2] = cloneableTags[regexpTag$2] = cloneableTags[setTag$4] = cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] = cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] = cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true; cloneableTags[errorTag$1] = cloneableTags[funcTag$2] = cloneableTags[weakMapTag$2] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG$2, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject_1(value)) { return value; } var isArr = isArray_1(value); if (isArr) { result = _initCloneArray(value); if (!isDeep) { return _copyArray(value, result); } } else { var tag = _getTag(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer_1(value)) { return _cloneBuffer(value, isDeep); } if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : _initCloneObject(value); if (!isDeep) { return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = _initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new _Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? _getAllKeysIn : _getAllKeys) : (isFlat ? keysIn : keys_1); var props = isArr ? undefined : keysFunc(value); _arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var _baseClone = baseClone; /** `Object#toString` result references. */ var symbolTag$2 = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$2); } var isSymbol_1 = isSymbol; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; var reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || _MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = _MapCache; var memoize_1 = memoize; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var reLeadingDot = /^\./; var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = _memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); var _stringToPath = stringToPath; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined; var symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : _baseToString(value); } var toString_1 = toString; /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } var last_1 = last; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _toKey = toKey; /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = _castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[_toKey(path[index++])]; } return (index && index == length) ? object : undefined; } var _baseGet = baseGet; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } var _baseSlice = baseSlice; /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1)); } var _parent = parent; /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = _castPath(path, object); object = _parent(object, path); return object == null || delete object[_toKey(last_1(path))]; } var _baseUnset = baseUnset; /** `Object#toString` result references. */ var objectTag$3 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype; var objectProto$14 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$12 = objectProto$14.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$12.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject_1(value) ? undefined : value; } var _customOmitClone = customOmitClone; /** Built-in value references. */ var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var _isFlattenable = isFlattenable; /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = _isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { _arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } var _baseFlatten = baseFlatten; /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? _baseFlatten(array, 1) : []; } var flatten_1 = flatten; /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } var _apply = apply; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return _apply(func, this, otherArgs); }; } var _overRest = overRest; /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } var constant_1 = constant; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } var identity_1 = identity; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !_defineProperty ? identity_1 : function(func, string) { return _defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant_1(string), 'writable': true }); }; var _baseSetToString = baseSetToString; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800; var HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } var _shortOut = shortOut; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = _shortOut(_baseSetToString); var _setToString = setToString; /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return _setToString(_overRest(func, undefined, flatten_1), func + ''); } var _flatRest = flatRest; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$3 = 1; var CLONE_FLAT_FLAG$1 = 2; var CLONE_SYMBOLS_FLAG$1 = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = _flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = _arrayMap(paths, function(path) { path = _castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); _copyObject(object, _getAllKeysIn(object), result); if (isDeep) { result = _baseClone(result, CLONE_DEEP_FLAG$3 | CLONE_FLAT_FLAG$1 | CLONE_SYMBOLS_FLAG$1, _customOmitClone); } var length = paths.length; while (length--) { _baseUnset(result, paths[length]); } return result; }); var omit_1 = omit; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED$2); return this; } var _setCacheAdd = setCacheAdd; /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } var _setCacheHas = setCacheHas; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new _MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; SetCache.prototype.has = _setCacheHas; var _SetCache = SetCache; /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } var _baseFindIndex = baseFindIndex; /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } var _baseIsNaN = baseIsNaN; /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } var _strictIndexOf = strictIndexOf; /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex); } var _baseIndexOf = baseIndexOf; /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && _baseIndexOf(array, value, 0) > -1; } var _arrayIncludes = arrayIncludes; /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } var _arrayIncludesWith = arrayIncludesWith; /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } var _cacheHas = cacheHas; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? _arrayIncludesWith : _arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = _arrayMap(array, _baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new _SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? _cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? _cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } var _baseIntersection = baseIntersection; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return _setToString(_overRest(func, start, identity_1), func + ''); } var _baseRest = baseRest; /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike_1(value) && isArrayLike_1(value); } var isArrayLikeObject_1 = isArrayLikeObject; /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject_1(value) ? value : []; } var _castArrayLikeObject = castArrayLikeObject; /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = _baseRest(function(arrays) { var mapped = _arrayMap(arrays, _castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? _baseIntersection(mapped) : []; }); var intersection_1 = intersection; /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var _createBaseFor = createBaseFor; /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = _createBaseFor(); var _baseFor = baseFor; /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && _baseFor(object, iteratee, keys_1); } var _baseForOwn = baseForOwn; /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity_1; } var _castFunction = castFunction; /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && _baseForOwn(object, _castFunction(iteratee)); } var forOwn_1 = forOwn; /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike_1(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } var _createBaseEach = createBaseEach; /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = _createBaseEach(_baseForOwn); var _baseEach = baseEach; /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray_1(collection) ? _arrayEach : _baseEach; return func(collection, _castFunction(iteratee)); } var forEach_1 = forEach; /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } var _baseFilter = baseFilter; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var _arraySome = arraySome; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; var COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!_arraySome(other, function(othValue, othIndex) { if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } var _equalArrays = equalArrays; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1; var COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag$3 = '[object Boolean]'; var dateTag$3 = '[object Date]'; var errorTag$2 = '[object Error]'; var mapTag$5 = '[object Map]'; var numberTag$3 = '[object Number]'; var regexpTag$3 = '[object RegExp]'; var setTag$5 = '[object Set]'; var stringTag$3 = '[object String]'; var symbolTag$3 = '[object Symbol]'; var arrayBufferTag$3 = '[object ArrayBuffer]'; var dataViewTag$4 = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined; var symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag$4: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag$3: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag$3: case dateTag$3: case numberTag$3: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag$2: return object.name == other.name && object.message == other.message; case regexpTag$3: case stringTag$3: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag$5: var convert = _mapToArray; case setTag$5: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; convert || (convert = _setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag$3: if (symbolValueOf$1) { return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); } } return false; } var _equalByTag = equalByTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; /** Used for built-in method references. */ var objectProto$15 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$13 = objectProto$15.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty$13.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } var _equalObjects = equalObjects; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]'; var arrayTag$2 = '[object Array]'; var objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var objectProto$16 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$14 = objectProto$16.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$2 : _getTag(object), othTag = othIsArr ? arrayTag$2 : _getTag(other); objTag = objTag == argsTag$3 ? objectTag$4 : objTag; othTag = othTag == argsTag$3 ? objectTag$4 : othTag; var objIsObj = objTag == objectTag$4, othIsObj = othTag == objectTag$4, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(object)) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { var objIsWrapped = objIsObj && hasOwnProperty$14.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$14.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new _Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new _Stack); return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); } var _baseIsEqualDeep = baseIsEqualDeep; /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$4 = 1; var COMPARE_UNORDERED_FLAG$2 = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result )) { return false; } } } return true; } var _baseIsMatch = baseIsMatch; /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject_1(value); } var _isStrictComparable = isStrictComparable; /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys_1(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, _isStrictComparable(value)]; } return result; } var _getMatchData = getMatchData; /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } var _matchesStrictComparable = matchesStrictComparable; /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = _getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return _matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || _baseIsMatch(object, source, matchData); }; } var _baseMatches = baseMatches; /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : _baseGet(object, path); return result === undefined ? defaultValue : result; } var get_1 = get; /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } var _baseHasIn = baseHasIn; /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = _castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = _toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && _hasPath(object, path, _baseHasIn); } var hasIn_1 = hasIn; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$5 = 1; var COMPARE_UNORDERED_FLAG$3 = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (_isKey(path) && _isStrictComparable(srcValue)) { return _matchesStrictComparable(_toKey(path), srcValue); } return function(object) { var objValue = get_1(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } var _baseMatchesProperty = baseMatchesProperty; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } var _baseProperty = baseProperty; /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return _baseGet(object, path); }; } var _basePropertyDeep = basePropertyDeep; /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); } var property_1 = property; /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity_1; } if (typeof value == 'object') { return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); } return property_1(value); } var _baseIteratee = baseIteratee; /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray_1(collection) ? _arrayFilter : _baseFilter; return func(collection, _baseIteratee(predicate, 3)); } var filter_1 = filter; /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike_1(collection) ? Array(collection.length) : []; _baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } var _baseMap = baseMap; /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray_1(collection) ? _arrayMap : _baseMap; return func(collection, _baseIteratee(iteratee, 3)); } var map_1 = map; /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } var _baseReduce = baseReduce; /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray_1(collection) ? _arrayReduce : _baseReduce, initAccum = arguments.length < 3; return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach); } var reduce_1 = reduce; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY$2 = 1 / 0; var MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber_1(value); if (value === INFINITY$2 || value === -INFINITY$2) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite_1(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } var toInteger_1 = toInteger; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$1 = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$1(length + index, 0); } return _baseIndexOf(array, value, index); } var indexOf_1 = indexOf; /** `Object#toString` result references. */ var numberTag$4 = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike_1(value) && _baseGetTag(value) == numberTag$4); } var isNumber_1 = isNumber; /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN$1(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber_1(value) && value != +value; } var _isNaN = isNaN$1; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return _baseIsEqual(value, other); } var isEqual_1 = isEqual; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } var isUndefined_1 = isUndefined; /** `Object#toString` result references. */ var stringTag$4 = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4); } var isString_1 = isString; /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike_1(collection)) { var iteratee = _baseIteratee(predicate, 3); collection = keys_1(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } var _createFind = createFind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$2 = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$2(length + index, 0); } return _baseFindIndex(array, _baseIteratee(predicate, 3), index); } var findIndex_1 = findIndex; /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = _createFind(findIndex_1); var find_1 = find; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : _baseSlice(array, start, end); } var _castSlice = castSlice; /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsEndIndex = charsEndIndex; /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsStartIndex = charsStartIndex; /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } var _asciiToArray = asciiToArray; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff'; var rsComboMarksRange = '\\u0300-\\u036f'; var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; var rsComboSymbolsRange = '\\u20d0-\\u20ff'; var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; var rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } var _hasUnicode = hasUnicode; /** Used to compose unicode character classes. */ var rsAstralRange$1 = '\\ud800-\\udfff'; var rsComboMarksRange$1 = '\\u0300-\\u036f'; var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; var rsVarRange$1 = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange$1 + ']'; var rsCombo = '[' + rsComboRange$1 + ']'; var rsFitz = '\\ud83c[\\udffb-\\udfff]'; var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; var rsNonAstral = '[^' + rsAstralRange$1 + ']'; var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; var rsZWJ$1 = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?'; var rsOptVar = '[' + rsVarRange$1 + ']?'; var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; var rsSeq = rsOptVar + reOptMod + rsOptJoin; var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } var _unicodeToArray = unicodeToArray; /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return _hasUnicode(string) ? _unicodeToArray(string) : _asciiToArray(string); } var _stringToArray = stringToArray; /** Used to match leading and trailing whitespace. */ var reTrim$1 = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString_1(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim$1, ''); } if (!string || !(chars = _baseToString(chars))) { return string; } var strSymbols = _stringToArray(string), chrSymbols = _stringToArray(chars), start = _charsStartIndex(strSymbols, chrSymbols), end = _charsEndIndex(strSymbols, chrSymbols) + 1; return _castSlice(strSymbols, start, end).join(''); } var trim_1 = trim; /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject_1(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike_1(object) && _isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq_1(object[index], value); } return false; } var _isIterateeCall = isIterateeCall; /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return _baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } var _createAssigner = createAssigner; /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = _createAssigner(function(object, source, srcIndex, customizer) { _copyObject(source, keysIn_1(source), object, customizer); }); var assignInWith_1 = assignInWith; /** Used for built-in method references. */ var objectProto$17 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$15 = objectProto$17.hasOwnProperty; /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq_1(objValue, objectProto$17[key]) && !hasOwnProperty$15.call(object, key))) { return srcValue; } return objValue; } var _customDefaultsAssignIn = customDefaultsAssignIn; /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = _baseRest(function(args) { args.push(undefined, _customDefaultsAssignIn); return _apply(assignInWith_1, undefined, args); }); var defaults_1 = defaults; /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq_1(object[key], value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignMergeValue = assignMergeValue; /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return _copyObject(value, keysIn_1(value)); } var toPlainObject_1 = toPlainObject; /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { _assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray_1(srcValue), isBuff = !isArr && isBuffer_1(srcValue), isTyped = !isArr && !isBuff && isTypedArray_1(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray_1(objValue)) { newValue = objValue; } else if (isArrayLikeObject_1(objValue)) { newValue = _copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = _cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = _cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) { newValue = objValue; if (isArguments_1(objValue)) { newValue = toPlainObject_1(objValue); } else if (!isObject_1(objValue) || (srcIndex && isFunction_1(objValue))) { newValue = _initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } _assignMergeValue(object, key, newValue); } var _baseMergeDeep = baseMergeDeep; /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } _baseFor(source, function(srcValue, key) { if (isObject_1(srcValue)) { stack || (stack = new _Stack); _baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } _assignMergeValue(object, key, newValue); } }, keysIn_1); } var _baseMerge = baseMerge; /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = _createAssigner(function(object, source, srcIndex) { _baseMerge(object, source, srcIndex); }); var merge_1 = merge; function valToNumber(v) { if (isNumber_1(v)) { return v; } else if (isString_1(v)) { return parseFloat(v); } else if (isArray_1(v)) { return map_1(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } var valToNumber_1 = valToNumber; function filterState(state, filters) { var partialState = {}; var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf_1(attributes, '*') === -1) { forEach_1(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty_1(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty_1(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty_1(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty_1(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter_1( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach_1( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } var filterState_1 = filterState; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated refinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults_1({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * kinds of behavior can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optional parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined_1(attribute)) { return {}; } else if (isString_1(attribute)) { return omit_1(refinementList, attribute); } else if (isFunction_1(attribute)) { return reduce_1(refinementList, function(memo, values, key) { var facetList = filter_1(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty_1(facetList)) memo[key] = facetList; return memo; }, {}); } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = indexOf_1; var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined_1(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find_1(array, function(currentValue) { return isEqual_1(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * separated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each faceted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn_1(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys_1(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach_1(numberKeys, function(k) { var value = partialState[k]; if (isString_1(value)) { var parsedValue = parseFloat(value); numbers[k] = _isNaN(parsedValue) ? value : parsedValue; } }); if (partialState.numericRefinements) { var numericRefinements = {}; forEach_1(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach_1(operators, function(values, operator) { var parsedValues = map_1(values, function(v) { if (isArray_1(v)) { return map_1(v, function(vPrime) { if (isString_1(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString_1(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge_1({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach_1(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty_1(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty_1(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) faceting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber_1(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge_1({}, this.numericRefinements); mod[attribute] = merge_1({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber_1(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual_1(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined_1(attribute)) { return {}; } else if (isString_1(attribute)) { return omit_1(this.numericRefinements, attribute); } else if (isFunction_1(attribute)) { return reduce_1(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach_1(operators, function(values, operator) { var outValues = []; forEach_1(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty_1(outValues)) operatorList[operator] = outValues; }); if (!isEmpty_1(operatorList)) memo[key] = operatorList; return memo; }, {}); } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter_1(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter_1(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter_1(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the faceted attribute. * @method * @param {string} facet name of the attribute used for faceting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter_1(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper * @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement} */ toggleRefinement: function toggleRefinement(facet, value) { return this.toggleFacetRefinement(facet, value); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf_1(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf_1(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value, optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf_1(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined_1(value) && isUndefined_1(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined_1(this.numericRefinements[attribute][operator]); if (isUndefined_1(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = !isUndefined_1( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf_1(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1( keys_1(this.numericRefinements), this.disjunctiveFacets ); return keys_1(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map_1(this.hierarchicalFacets, 'name'), keys_1(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter_1(this.disjunctiveFacets, function(f) { return indexOf_1(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn_1(this, function(paramValue, paramName) { if (indexOf_1(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys_1(params); forEach_1(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState_1(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find_1( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map_1(path, trim_1); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ var SearchParameters_1 = SearchParameters; /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } var compact_1 = compact; /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } var _baseSum = baseSum; /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? _baseSum(array, _baseIteratee(iteratee, 2)) : 0; } var sumBy_1 = sumBy; /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return _arrayMap(props, function(key) { return object[key]; }); } var _baseValues = baseValues; /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : _baseValues(object, keys_1(object)); } var values_1 = values; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$3 = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike_1(collection) ? collection : values_1(collection); fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax$3(length + fromIndex, 0); } return isString_1(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && _baseIndexOf(collection, value, fromIndex) > -1); } var includes_1 = includes; /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } var _baseSortBy = baseSortBy; /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } var _compareAscending = compareAscending; /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = _compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } var _compareMultiple = compareMultiple; /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = _arrayMap(iteratees.length ? iteratees : [identity_1], _baseUnary(_baseIteratee)); var result = _baseMap(collection, function(value, key, collection) { var criteria = _arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return _baseSortBy(result, function(object, other) { return _compareMultiple(object, other, orders); }); } var _baseOrderBy = baseOrderBy; /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray_1(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray_1(orders)) { orders = orders == null ? [] : [orders]; } return _baseOrderBy(collection, iteratees, orders); } var orderBy_1 = orderBy; /** Used to store function metadata. */ var metaMap = _WeakMap && new _WeakMap; var _metaMap = metaMap; /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !_metaMap ? identity_1 : function(func, data) { _metaMap.set(func, data); return func; }; var _baseSetData = baseSetData; /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = _baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject_1(result) ? result : thisBinding; }; } var _createCtor = createCtor; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = _createCtor(func); function wrapper() { var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } var _createBind = createBind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$4 = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax$4(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } var _composeArgs = composeArgs; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$5 = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax$5(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } var _composeArgsRight = composeArgsRight; /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } var _countHolders = countHolders; /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } var _baseLodash = baseLodash; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; var _LazyWrapper = LazyWrapper; /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop$1() { // No operation performed. } var noop_1 = noop$1; /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !_metaMap ? noop_1 : function(func) { return _metaMap.get(func); }; var _getData = getData; /** Used to lookup unminified function names. */ var realNames = {}; var _realNames = realNames; /** Used for built-in method references. */ var objectProto$18 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$16 = objectProto$18.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = _realNames[result], length = hasOwnProperty$16.call(_realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } var _getFuncName = getFuncName; /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = _baseCreate(_baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; var _LodashWrapper = LodashWrapper; /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof _LazyWrapper) { return wrapper.clone(); } var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = _copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } var _wrapperClone = wrapperClone; /** Used for built-in method references. */ var objectProto$19 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$17 = objectProto$19.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) { if (value instanceof _LodashWrapper) { return value; } if (hasOwnProperty$17.call(value, '__wrapped__')) { return _wrapperClone(value); } } return new _LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = _baseLodash.prototype; lodash.prototype.constructor = lodash; var wrapperLodash = lodash; /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = _getFuncName(func), other = wrapperLodash[funcName]; if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = _getData(other); return !!data && func === data[0]; } var _isLaziable = isLaziable; /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = _shortOut(_baseSetData); var _setData = setData; /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/; var reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } var _getWrapDetails = getWrapDetails; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } var _insertWrapDetails = insertWrapDetails; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$1 = 1; var WRAP_BIND_KEY_FLAG = 2; var WRAP_CURRY_FLAG = 8; var WRAP_CURRY_RIGHT_FLAG = 16; var WRAP_PARTIAL_FLAG = 32; var WRAP_PARTIAL_RIGHT_FLAG = 64; var WRAP_ARY_FLAG = 128; var WRAP_REARG_FLAG = 256; var WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG$1], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { _arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } var _updateWrapDetails = updateWrapDetails; /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask))); } var _setWrapToString = setWrapToString; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$2 = 1; var WRAP_BIND_KEY_FLAG$1 = 2; var WRAP_CURRY_BOUND_FLAG = 4; var WRAP_CURRY_FLAG$1 = 8; var WRAP_PARTIAL_FLAG$1 = 32; var WRAP_PARTIAL_RIGHT_FLAG$1 = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG$1, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG$2 | WRAP_BIND_KEY_FLAG$1); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (_isLaziable(func)) { _setData(result, newData); } result.placeholder = placeholder; return _setWrapToString(result, func, bitmask); } var _createRecurry = createRecurry; /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } var _getHolder = getHolder; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$1 = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin$1(indexes.length, arrLength), oldArray = _copyArray(array); while (length--) { var index = indexes[length]; array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } var _reorder = reorder; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } var _replaceHolders = replaceHolders; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$3 = 1; var WRAP_BIND_KEY_FLAG$2 = 2; var WRAP_CURRY_FLAG$2 = 8; var WRAP_CURRY_RIGHT_FLAG$1 = 16; var WRAP_ARY_FLAG$1 = 128; var WRAP_FLIP_FLAG$1 = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG$1, isBind = bitmask & WRAP_BIND_FLAG$3, isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2, isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1), isFlip = bitmask & WRAP_FLIP_FLAG$1, Ctor = isBindKey ? undefined : _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = _getHolder(wrapper), holdersCount = _countHolders(args, placeholder); } if (partials) { args = _composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = _composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = _replaceHolders(args, placeholder); return _createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = _reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== _root && this instanceof wrapper) { fn = Ctor || _createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } var _createHybrid = createHybrid; /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = _getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : _replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return _createRecurry( func, bitmask, _createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return _apply(fn, this, args); } return wrapper; } var _createCurry = createCurry; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$4 = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG$4, Ctor = _createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return _apply(fn, isBind ? thisArg : this, args); } return wrapper; } var _createPartial = createPartial; /** Used as the internal argument placeholder. */ var PLACEHOLDER$1 = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$5 = 1; var WRAP_BIND_KEY_FLAG$3 = 2; var WRAP_CURRY_BOUND_FLAG$1 = 4; var WRAP_CURRY_FLAG$3 = 8; var WRAP_ARY_FLAG$2 = 128; var WRAP_REARG_FLAG$1 = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$2 = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG$5 | WRAP_BIND_KEY_FLAG$3 | WRAP_ARY_FLAG$2); var isCombo = ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$3)) || ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$3)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG$5) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG$5 ? 0 : WRAP_CURRY_BOUND_FLAG$1; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? _composeArgs(partials, value, source[4]) : value; data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER$1) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER$1) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG$2) { data[8] = data[8] == null ? source[8] : nativeMin$2(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } var _mergeData = mergeData; /** Error message constants. */ var FUNC_ERROR_TEXT$1 = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$6 = 1; var WRAP_BIND_KEY_FLAG$4 = 2; var WRAP_CURRY_FLAG$4 = 8; var WRAP_CURRY_RIGHT_FLAG$2 = 16; var WRAP_PARTIAL_FLAG$2 = 32; var WRAP_PARTIAL_RIGHT_FLAG$2 = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$6 = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG$4; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT$1); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG$2 | WRAP_PARTIAL_RIGHT_FLAG$2); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax$6(toInteger_1(ary), 0); arity = arity === undefined ? arity : toInteger_1(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG$2) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : _getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { _mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax$6(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2)) { bitmask &= ~(WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2); } if (!bitmask || bitmask == WRAP_BIND_FLAG$6) { var result = _createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG$4 || bitmask == WRAP_CURRY_RIGHT_FLAG$2) { result = _createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG$2 || bitmask == (WRAP_BIND_FLAG$6 | WRAP_PARTIAL_FLAG$2)) && !holders.length) { result = _createPartial(func, bitmask, thisArg, partials); } else { result = _createHybrid.apply(undefined, newData); } var setter = data ? _baseSetData : _setData; return _setWrapToString(setter(result, newData), func, bitmask); } var _createWrap = createWrap; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG$3 = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partial)); return _createWrap(func, WRAP_PARTIAL_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; var partial_1 = partial; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG$3 = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partialRight)); return _createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; var partialRight_1 = partialRight; /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } var _baseClamp = baseClamp; /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString_1(string); position = position == null ? 0 : _baseClamp(toInteger_1(position), 0, string.length); target = _baseToString(target); return string.slice(position, position + target.length) == target; } var startsWith_1 = startsWith; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { return reduce_1(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find_1(defaults, function(predicate) { return startsWith_1(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject_1(object)) { return object; } path = _castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = _toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject_1(objValue) ? objValue : (_isIndex(path[index + 1]) ? [] : {}); } } _assignValue(nested, key, newValue); nested = nested[key]; } return object; } var _baseSet = baseSet; /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = _baseGet(object, path); if (predicate(value, path)) { _baseSet(result, _castPath(path, object), value); } } return result; } var _basePickBy = basePickBy; /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = _arrayMap(_getAllKeysIn(object), function(prop) { return [prop]; }); predicate = _baseIteratee(predicate); return _basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } var pickBy_1 = pickBy; var generateHierarchicalTree_1 = generateTrees; function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce_1(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find_1(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy_1( map_1( pickBy_1(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim_1(last_1(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the faceting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objects matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} name the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric filters. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach_1(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find_1( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes_1(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; this._rawResults = results; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy_1(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @deprecated * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @deprecated * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * True if the counts of the facets is exhaustive * @member {boolean} */ this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount; /** * True if the number of hits is exhaustive * @member {boolean} */ this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits; /** * Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/). * @member {object[]} */ this.userData = mainSubResponse.userData; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map_1(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach_1(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf_1(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact_1(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach_1(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach_1(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge_1( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults_1({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf_1(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach_1(result.facets, function(facetResults, dfacet) { var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults_1( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach_1(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach_1(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map_1(this.hierarchicalFacets, generateHierarchicalTree_1(state)); this.facets = compact_1(this.facets); this.disjunctiveFacets = compact_1(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the faceted attribute * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find_1(this.facets, predicate) || find_1(this.disjunctiveFacets, predicate) || find_1(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the faceted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find_1(results.facets, predicate); if (!facet) return []; return map_1(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find_1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map_1(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find_1(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map_1(node.data, partial_1(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge_1({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (isArray_1(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (isArray_1(facetValues)) { return orderBy_1(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues); } else if (isFunction_1(options.sortBy)) { if (isArray_1(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial_1(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the faceted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find_1(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach_1(state.facetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach_1(state.facetsExcludes, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach_1(state.numericRefinements, function(operators, attributeName) { forEach_1(operators, function(values, operator) { forEach_1(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach_1(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var count = get_1(facet, 'data[' + name + ']'); var exhaustive = get_1(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find_1(facet.data, {name: splitted[i]}); } var count = get_1(facet, 'count'); var exhaustive = get_1(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } var SearchResults_1 = SearchResults; var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var util = createCommonjsModule(function (module, exports) { // 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. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(commonjsGlobal.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = isBufferBrowser; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = inherits_browser; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }); var util_1 = util.format; var util_2 = util.deprecate; var util_3 = util.debuglog; var util_4 = util.inspect; var util_5 = util.isArray; var util_6 = util.isBoolean; var util_7 = util.isNull; var util_8 = util.isNullOrUndefined; var util_9 = util.isNumber; var util_10 = util.isString; var util_11 = util.isSymbol; var util_12 = util.isUndefined; var util_13 = util.isRegExp; var util_14 = util.isObject; var util_15 = util.isDate; var util_16 = util.isError; var util_17 = util.isFunction; var util_18 = util.isPrimitive; var util_19 = util.isBuffer; var util_20 = util.log; var util_21 = util.inherits; var util_22 = util._extend; // 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. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } var events = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber$2(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject$2(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined$2(handler)) return false; if (isFunction$2(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject$2(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction$2(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction$2(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject$2(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject$2(this._events[type]) && !this._events[type].warned) { if (!isUndefined$2(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction$2(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction$2(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction$2(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject$2(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction$2(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction$2(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction$2(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction$2(arg) { return typeof arg === 'function'; } function isNumber$2(arg) { return typeof arg === 'number'; } function isObject$2(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined$2(arg) { return arg === void 0; } /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; var DerivedHelper_1 = DerivedHelper; var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach_1(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters, analytics: false }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach_1(state.numericRefinements, function(operators, attribute) { forEach_1(operators, function(values, operator) { if (facetName !== attribute) { forEach_1(values, function(value) { if (isArray_1(value)) { var vs = map_1(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach_1(state.facetsRefinements, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach_1(state.facetsExcludes, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach_1(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach_1(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce_1( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var searchForFacetSearchParameters = { facetQuery: query, facetName: facetName }; if (typeof maxFacetHits === 'number') { searchForFacetSearchParameters.maxFacetHits = maxFacetHits; } var queries = merge_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); return queries; } }; var requestBuilder_1 = requestBuilder; /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { _baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } var _baseInverter = baseInverter; /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return _baseInverter(object, setter, toIteratee(iteratee), {}); }; } var _createInverter = createInverter; /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = _createInverter(function(result, value, key) { result[value] = key; }, constant_1(identity_1)); var invert_1 = invert; var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert_1(keys2Short); var shortener = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys_1(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; var utils = createCommonjsModule(function (module, exports) { var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } return obj; }; exports.arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function merge(target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function encode(str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } return compactQueue(queue); }; exports.isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; }); var utils_1 = utils.arrayToObject; var utils_2 = utils.merge; var utils_3 = utils.assign; var utils_4 = utils.decode; var utils_5 = utils.encode; var utils_6 = utils.compact; var utils_7 = utils.isRegExp; var utils_8 = utils.isBuffer; var replace = String.prototype.replace; var percentTwenties = /%20/g; var formats = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var toISO = Date.prototype.toISOString; var defaults$2 = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults$2.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$2.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$2.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; var stringify_1 = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults$2.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$2.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$2.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults$2.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$2.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults$2.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$2.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; }; var has = Object.prototype.hasOwnProperty; var defaults$3 = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults$3.decoder); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults$3.decoder); val = options.decoder(part.slice(pos + 1), defaults$3.decoder); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = obj.concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; var parse = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults$3.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults$3.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$3.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$3.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$3.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$3.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$3.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$3.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$3.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; var lib$1 = { formats: formats, parse: parse, stringify: stringify_1 }; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$7 = 1; var WRAP_PARTIAL_FLAG$4 = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = _baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG$7; if (partials.length) { var holders = _replaceHolders(partials, _getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG$4; } return _createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; var bind_1 = bind; /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return _basePickBy(object, paths, function(value, path) { return hasIn_1(object, path); }); } var _basePick = basePick; /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = _flatRest(function(object, paths) { return object == null ? {} : _basePick(object, paths); }); var pick_1 = pick; /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, iteratee(value, key, object), value); }); return result; } var mapKeys_1 = mapKeys; /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } var mapValues_1 = mapValues; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var encode = utils.encode; function recursiveEncode(input) { if (isPlainObject_1(input)) { return mapValues_1(input, recursiveEncode); } if (isArray_1(input)) { return map_1(input, recursiveEncode); } if (isString_1(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ var getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var partialStateWithPrefix = lib$1.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys_1( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters_1._parseNumbers(partialState); return pick_1(partialStateWithParsedNumbers, SearchParameters_1.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ var getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var foreignConfig = {}; var config = lib$1.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach_1(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach_1(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ var getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert_1(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys_1( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (!isEmpty_1(moreAttributes)) { var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = lib$1.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return lib$1.stringify(encodedState, {encode: safe, sort: sort}); }; var url = { getStateFromQueryString: getStateFromQueryString, getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString, getQueryStringFromState: getQueryStringFromState }; var version$1 = '2.22.0'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {SearchParameters} state the parameters used for this search * it is the first search. * @property {string} facet the facet searched into * @property {string} query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(state, facet, query) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {SearchParameters} state the parameters used for this search * it is the first search. * @example * helper.on('searchOnce', function(state) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Event triggered when the queue of queries have been depleted (with any result or outdated queries) * @event AlgoliaSearchHelper#event:searchQueueEmpty * @example * helper.on('searchQueueEmpty', function() { * console.log('No more search pending'); * // This is received before the result event if we're not expecting new results * }); * * helper.search(); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version$1); this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters_1.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; this._currentNbQueries = 0; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder_1._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occurred it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder_1._getQueries(tempState.index, tempState); var self = this; this._currentNbQueries++; this.emit('searchOnce', tempState); if (cb) { return this.client.search( queries, function(err, content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); if (err) cb(err, null, tempState); else cb(err, new SearchResults_1(tempState, content.results), tempState); } ); } return this.client.search(queries).then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); return { content: new SearchResults_1(tempState, content.results), state: tempState, _originalResponse: content }; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurrence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {object} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query inside the engine */ /** * Search for facet values based on an query and the name of a faceted attribute. This * triggers a search and will return a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed down to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} facet the name of the faceted attribute * @param {string} query the string query for the search * @param {number} maxFacetHits the maximum number values returned. Should be > 0 and <= 100 * @return {promise<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits) { var state = this.state; var index = this.client.initIndex(this.state.index); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, this.state); this._currentNbQueries++; var self = this; this.emit('searchForFacetValues', state, facet, query); return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); content.facetHits = forEach_1(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this.state = this.state.setPage(0).setQuery(q); this._change(); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this.state = this.state.setPage(0).clearRefinements(name); this._change(); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this.state = this.state.setPage(0).clearTags(); this._change(); return this; }; /** * Adds a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value); this._change(); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Adds a filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).addExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this.state = this.state.setPage(0).addTagRefinement(tag); this._change(); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optional, triggering different behavior: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Removes a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet); this._change(); return this; }; /** * Removes a filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).removeExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this.state = this.state.setPage(0).removeTagRefinement(tag); this._change(); return this; }; /** * Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable * @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { return this.toggleFacetRefinement(facet, value); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).toggleFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleFacetRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this.state = this.state.setPage(0).toggleTagRefinement(tag); this._change(); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this.state = this.state.setPage(page); this._change(); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this.state = this.state.setPage(0).setIndex(name); this._change(); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { var newState = this.state.setPage(0).setQueryParameter(parameter, value); if (this.state === newState) return this; this.state = newState; this._change(); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this.state = SearchParameters_1.make(newState); this._change(); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optional filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optional parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters_1(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleFacetRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty_1(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific faceted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for faceting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach_1(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach_1(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach_1(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach_1(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder_1._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten_1(derivedQueries)); var queryId = this._queryId++; this._currentNbQueries++; this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId)); }; /** * Transform the responses as sent by the server and transform them into a user * usable object that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {Error} err error if any, null otherwise * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) { // FIXME remove the number of outdated queries discarded instead of just one if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= (queryId - this._lastQueryIdReceived); this._lastQueryIdReceived = queryId; if (err) { this.emit('error', err); if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); } else { if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); var results = content.results; forEach_1(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults); helper.emit('result', formattedResponse, state); }); } }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function() { this.emit('change', this.state, this.lastResults); }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version$1); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `result` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper_1(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * This method returns true if there is currently at least one on-going search. * @return {boolean} true if there is a search pending */ AlgoliaSearchHelper.prototype.hasPendingRequests = function() { return this._currentNbQueries > 0; }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the faceting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ /* * This function tests if the _ua parameter of the client * already contains the JS Helper UA */ function doesClientAgentContainsHelper(client) { // this relies on JS Client internal variable, this might break if implementation changes var currentAgent = client._ua; return !currentAgent ? false : currentAgent.indexOf('JS Helper') !== -1; } var algoliasearch_helper = AlgoliaSearchHelper; /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new algoliasearch_helper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = version$1; /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters_1; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults_1; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = url; var algoliasearchHelper_1 = algoliasearchHelper; var algoliasearchHelper_4 = algoliasearchHelper_1.SearchParameters; // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function isSpecialClick(event) { var isMiddleClick = event.button === 1; return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey); } function capitalize(key) { return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1); } function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; } var resolved = Promise.resolve(); var defer = function defer(f) { resolved.then(f); }; function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (isEmpty_1(value) && isPlainObject_1(value)) { delete obj[key]; } else if (isPlainObject_1(value)) { removeEmptyKey(value); } }); return obj; } function createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; defer(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } var highlightTags = { highlightPreTag: "<ais-highlight-0000000000>", highlightPostTag: "</ais-highlight-0000000000>" }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; 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; }; }(); var defineProperty$2 = function (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 _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (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 objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; 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 toConsumableArray = function (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); } }; /** * Creates a new instance of the InstantSearchManager which controls the widgets and * trigger the search when the widgets are updated. * @param {string} indexName - the main index name * @param {object} initialState - initial widget state * @param {object} SearchParameters - optional additional parameters to send to the algolia API * @param {number} stalledSearchDelay - time (in ms) after the search is stalled * @return {InstantSearchManager} a new instance of InstantSearchManager */ function createInstantSearchManager(_ref) { var indexName = _ref.indexName, _ref$initialState = _ref.initialState, initialState = _ref$initialState === undefined ? {} : _ref$initialState, algoliaClient = _ref.algoliaClient, resultsState = _ref.resultsState, stalledSearchDelay = _ref.stalledSearchDelay; var baseSP = new algoliasearchHelper_4(_extends({ index: indexName }, highlightTags)); var stalledSearchTimer = null; var helper = algoliasearchHelper_1(algoliaClient, indexName, baseSP); helper.on('result', handleSearchSuccess); helper.on('error', handleSearchError); helper.on('search', handleNewSearch); var derivedHelpers = {}; var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used. var initialSearchParameters = helper.state; var widgetsManager = createWidgetsManager(onWidgetsUpdate); var store = createStore({ widgets: initialState, metadata: [], results: resultsState || null, error: null, searching: false, isSearchStalled: true, searchingForFacetValues: false }); var skip = false; function skipSearch() { skip = true; } function updateClient(client) { helper.setClient(client); search(); } function clearCache() { helper.clearCache(); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { indexMapping = {}; var sharedParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return !widget.context.multiIndexContext && (widget.props.indexName === indexName || !widget.props.indexName); }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); indexMapping[sharedParameters.index] = indexName; var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex !== indexName || widget.props.indexName && widget.props.indexName !== indexName; }).reduce(function (indices, widget) { var targetedIndex = widget.context.multiIndexContext ? widget.context.multiIndexContext.targetedIndex : widget.props.indexName; var index = indices.find(function (i) { return i.targetedIndex === targetedIndex; }); if (index) { index.widgets.push(widget); } else { indices.push({ targetedIndex: targetedIndex, widgets: [widget] }); } return indices; }, []); var mainIndexParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex === indexName || widget.props.indexName && widget.props.indexName === indexName; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); indexMapping[mainIndexParameters.index] = indexName; return { sharedParameters: sharedParameters, mainIndexParameters: mainIndexParameters, derivatedWidgets: derivatedWidgets }; } function search() { if (!skip) { var _getSearchParameters = getSearchParameters(helper.state), sharedParameters = _getSearchParameters.sharedParameters, mainIndexParameters = _getSearchParameters.mainIndexParameters, derivatedWidgets = _getSearchParameters.derivatedWidgets; Object.keys(derivedHelpers).forEach(function (key) { return derivedHelpers[key].detach(); }); derivedHelpers = {}; helper.setState(sharedParameters); derivatedWidgets.forEach(function (derivatedSearchParameters) { var index = derivatedSearchParameters.targetedIndex; var derivedHelper = helper.derive(function () { var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); indexMapping[parameters.index] = index; return parameters; }); derivedHelper.on('result', handleSearchSuccess); derivedHelper.on('error', handleSearchError); derivedHelpers[index] = derivedHelper; }); helper.setState(mainIndexParameters); helper.search(); } } function handleSearchSuccess(content) { var state = store.getState(); var results = state.results ? state.results : {}; /* if switching from mono index to multi index and vice versa, results needs to reset to {}*/ results = !isEmpty_1(derivedHelpers) && results.getFacetByName ? {} : results; if (!isEmpty_1(derivedHelpers)) { results[indexMapping[content.index]] = content; } else { results = content; } var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); stalledSearchTimer = null; nextIsSearchStalled = false; } var nextState = omit_1(_extends({}, currentState, { results: results, isSearchStalled: nextIsSearchStalled, searching: false, error: null }), 'resultsFacetValues'); store.setState(nextState); } function handleSearchError(error) { var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); nextIsSearchStalled = false; } var nextState = omit_1(_extends({}, currentState, { isSearchStalled: nextIsSearchStalled, error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleNewSearch() { if (!stalledSearchTimer) { stalledSearchTimer = setTimeout(function () { var nextState = omit_1(_extends({}, store.getState(), { isSearchStalled: true }), 'resultsFacetValues'); store.setState(nextState); }, stalledSearchDelay); } } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_extends({}, store.getState(), { metadata: metadata, searching: true })); // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. search(); } function transitionState(nextSearchState) { var searchState = store.getState().widgets; return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.transitionState); }).reduce(function (res, widget) { return widget.transitionState(searchState, res); }, nextSearchState); } function onExternalStateUpdate(nextSearchState) { var metadata = getMetadata(nextSearchState); store.setState(_extends({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(_ref2) { var facetName = _ref2.facetName, query = _ref2.query, maxFacetHits = _ref2.maxFacetHits; store.setState(_extends({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(facetName, query, maxFacetHits).then(function (content) { var _babelHelpers$extends; store.setState(_extends({}, store.getState(), { resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_babelHelpers$extends = {}, defineProperty$2(_babelHelpers$extends, facetName, content.facetHits), defineProperty$2(_babelHelpers$extends, 'query', query), _babelHelpers$extends)), searchingForFacetValues: false })); }, function (error) { store.setState(_extends({}, store.getState(), { error: error, searchingForFacetValues: false })); }).catch(function (error) { // Since setState is synchronous, any error that occurs in the render of a // component will be swallowed by this promise. // This is a trick to make the error show up correctly in the console. // See http://stackoverflow.com/a/30741722/969302 setTimeout(function () { throw error; }); }); } function updateIndex(newIndex) { initialSearchParameters = initialSearchParameters.setIndex(newIndex); search(); } function getWidgetsIds() { return store.getState().metadata.reduce(function (res, meta) { return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res; }, []); } return { store: store, widgetsManager: widgetsManager, getWidgetsIds: getWidgetsIds, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, onSearchForFacetValues: onSearchForFacetValues, updateClient: updateClient, updateIndex: updateIndex, clearCache: clearCache, skipSearch: skipSearch }; } function validateNextProps(props, nextProps) { if (!props.searchState && nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled"); } else if (props.searchState && !nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled"); } } /* eslint valid-jsdoc: 0 */ /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @name <InstantSearch> * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {boolean} [refresh=false] - Flag to activate when the cache needs to be cleared so that the front-end is updated when a change occurs in the index. * @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @propType {SearchResults|SearchResults[]} [resultsState] - Use this to inject the results that will be used at first rendering. Those results are found by using the `findResultsState` function. Useful for [Server Side Rendering](guide/Server-side_rendering.html). * @propType {number} [stalledSearchDelay=200] - The amount of time before considering that the search takes too much time. The time is expressed in milliseconds. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import {InstantSearch, SearchBox, Hits} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch * appId="appId" * apiKey="apiKey" * indexName="indexName" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); * } */ var InstantSearch = function (_Component) { inherits(InstantSearch, _Component); function InstantSearch(props) { classCallCheck(this, InstantSearch); var _this = possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.isUnmounting = false; _this.aisManager = createInstantSearchManager({ indexName: props.indexName, algoliaClient: props.algoliaClient, initialState: initialState, resultsState: props.resultsState, stalledSearchDelay: props.stalledSearchDelay }); return _this; } createClass(InstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.props.refresh !== nextProps.refresh) { if (nextProps.refresh) { this.aisManager.clearCache(); } } if (this.props.algoliaClient !== nextProps.algoliaClient) { this.aisManager.updateClient(nextProps.algoliaClient); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.isUnmounting = true; this.aisManager.skipSearch(); } }, { key: 'getChildContext', value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this), onSearchParameters: this.onSearchParameters.bind(this) } }; } return { ais: _extends({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager, mainTargetedIndex: this.props.indexName }) }; } }, { key: 'createHrefForState', value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: 'onWidgetsInternalStateUpdate', value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: 'onSearchStateChange', value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange && !this.isUnmounting) { this.props.onSearchStateChange(searchState); } } }, { key: 'onSearchParameters', value: function onSearchParameters(getSearchParameters, context, props) { if (this.props.onSearchParameters) { var searchState = this.props.searchState ? this.props.searchState : {}; this.props.onSearchParameters(getSearchParameters, context, props, searchState); } } }, { key: 'onSearchForFacetValues', value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: 'getKnownKeys', value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: 'render', value: function render() { var childrenCount = React.Children.count(this.props.children); var _props$root = this.props.root, Root = _props$root.Root, props = _props$root.props; if (childrenCount === 0) return null;else return React__default.createElement( Root, props, this.props.children ); } }]); return InstantSearch; }(React.Component); InstantSearch.defaultProps = { stalledSearchDelay: 200 }; InstantSearch.propTypes = { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, algoliaClient: propTypes.object.isRequired, createURL: propTypes.func, refresh: propTypes.bool.isRequired, searchState: propTypes.object, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), children: propTypes.node, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]), props: propTypes.object }).isRequired, stalledSearchDelay: propTypes.number }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; var _name$version$descrip = { name: 'react-instantsearch', version: '5.0.0-beta.0', description: '\u26A1 Lightning-fast search for React and React Native apps, by Algolia', keywords: ['algolia', 'components', 'fast', 'instantsearch', 'react', 'react-native', 'search'], homepage: 'https://community.algolia.com/react-instantsearch', license: 'MIT', author: { name: 'Algolia, Inc.', url: 'https://www.algolia.com' }, main: 'index.js', module: 'es/index.js', repository: { type: 'git', url: 'https://github.com/algolia/react-instantsearch' }, scripts: { build: './scripts/build.sh', 'build-and-publish': './scripts/build-and-publish.sh' }, dependencies: { algoliasearch: '^3.24.0', 'algoliasearch-helper': '^2.21.0', classnames: '^2.2.5', lodash: '^4.17.4', 'prop-types': '^15.5.10' }, devDependencies: { enzyme: '3.3.0', 'enzyme-adapter-react-16': '1.1.1', react: '16.2.0', 'react-dom': '16.2.0', 'react-native': '0.51.0', 'react-test-renderer': '16.2.0' } }; var version$4 = _name$version$descrip.version; /** * Creates a specialized root InstantSearch component. It accepts * an algolia client and a specification of the root Element. * @param {function} defaultAlgoliaClient - a function that builds an Algolia client * @param {object} root - the defininition of the root of an InstantSearch sub tree. * @returns {object} an InstantSearch root */ function createInstantSearch(defaultAlgoliaClient, root) { var _class, _temp; return _temp = _class = function (_Component) { inherits(CreateInstantSearch, _Component); function CreateInstantSearch() { var _ref; classCallCheck(this, CreateInstantSearch); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var _this = possibleConstructorReturn(this, (_ref = CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call.apply(_ref, [this].concat(args))); _this.client = _this.props.algoliaClient || defaultAlgoliaClient(_this.props.appId, _this.props.apiKey); _this.client.addAlgoliaAgent('react-instantsearch ' + version$4); return _this; } createClass(CreateInstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var props = this.props; if (nextProps.algoliaClient) { this.client = nextProps.algoliaClient; } else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) { this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey); } this.client.addAlgoliaAgent('react-instantsearch ' + version$4); } }, { key: 'render', value: function render() { return React__default.createElement( InstantSearch, { createURL: this.props.createURL, indexName: this.props.indexName, searchState: this.props.searchState, onSearchStateChange: this.props.onSearchStateChange, onSearchParameters: this.props.onSearchParameters, root: this.props.root, algoliaClient: this.client, refresh: this.props.refresh, resultsState: this.props.resultsState }, this.props.children ); } }]); return CreateInstantSearch; }(React.Component), _class.propTypes = { algoliaClient: propTypes.object, appId: propTypes.string, apiKey: propTypes.string, children: propTypes.oneOfType([propTypes.arrayOf(propTypes.node), propTypes.node]), indexName: propTypes.string.isRequired, createURL: propTypes.func, searchState: propTypes.object, refresh: propTypes.bool.isRequired, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]).isRequired, props: propTypes.object }) }, _class.defaultProps = { refresh: false, root: root }, _temp; } /* eslint valid-jsdoc: 0 */ /** * @description * `<Index>` is the component that allows you to apply widgets to a dedicated index. It's * useful if you want to build an interface that targets multiple indices. * @kind widget * @name <Index> * @propType {string} indexName - index in which to search. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import {InstantSearch, Index, SearchBox, Hits, Configure} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch appId="" apiKey="" indexName="index1"> <SearchBox/> <Configure hitsPerPage={1} /> <Index indexName="index1"> <Hits /> </Index> <Index indexName="index2"> <Hits /> </Index> </InstantSearch> * ); * } */ var Index = function (_Component) { inherits(Index, _Component); function Index(props, context) { classCallCheck(this, Index); var _this = possibleConstructorReturn(this, (Index.__proto__ || Object.getPrototypeOf(Index)).call(this, props)); var widgetsManager = context.ais.widgetsManager; /* we want <Index> to be seen as a regular widget. It means that with only <Index> present a new query will be sent to Algolia. That way you don't need a virtual hits widget to use the connectAutoComplete. */ _this.unregisterWidget = widgetsManager.registerWidget(_this); return _this; } createClass(Index, [{ key: 'componentWillMount', value: function componentWillMount() { this.context.ais.onSearchParameters(this.getSearchParameters, this.getChildContext(), this.props); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.props.indexName !== nextProps.indexName) { this.context.ais.widgetsManager.update(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unregisterWidget(); } }, { key: 'getChildContext', value: function getChildContext() { return { multiIndexContext: { targetedIndex: this.props.indexName } }; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters, props) { return searchParameters.setIndex(this.props ? this.props.indexName : props.indexName); } }, { key: 'render', value: function render() { var childrenCount = React.Children.count(this.props.children); var _props$root = this.props.root, Root = _props$root.Root, props = _props$root.props; if (childrenCount === 0) return null;else return React__default.createElement( Root, props, this.props.children ); } }]); return Index; }(React.Component); Index.propTypes = { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, children: propTypes.node, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]), props: propTypes.object }).isRequired }; Index.childContextTypes = { multiIndexContext: propTypes.object.isRequired }; Index.contextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; /** * Creates a specialized root Index component. It accepts * a specification of the root Element. * @param {object} defaultRoot - the defininition of the root of an Index sub tree. * @return {object} a Index root */ var createIndex = function createIndex(defaultRoot) { var CreateIndex = function CreateIndex(_ref) { var indexName = _ref.indexName, root = _ref.root, children = _ref.children; return React__default.createElement( Index, { indexName: indexName, root: root }, children ); }; CreateIndex.propTypes = { indexName: propTypes.string.isRequired, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]).isRequired, props: propTypes.object }), children: propTypes.node }; CreateIndex.defaultProps = { root: defaultRoot }; return CreateIndex; }; var inherits_browser$2 = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var hasOwn = Object.prototype.hasOwnProperty; var toString$2 = Object.prototype.toString; var foreach = function forEach (obj, fn, ctx) { if (toString$2.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; // This file hosts our error definitions // We use custom error "types" so that we can act on them when we need it // e.g.: if error instanceof errors.UnparsableJSON then.. function AlgoliaSearchError(message, extraProperties) { var forEach = foreach; var error = this; // try to get a stacktrace if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old'; } this.name = 'AlgoliaSearchError'; this.message = message || 'Unknown error'; if (extraProperties) { forEach(extraProperties, function addToErrorObject(value, key) { error[key] = value; }); } } inherits_browser$2(AlgoliaSearchError, Error); function createCustomError(name, message) { function AlgoliaSearchCustomError() { var args = Array.prototype.slice.call(arguments, 0); // custom message not set, use default if (typeof args[0] !== 'string') { args.unshift(message); } AlgoliaSearchError.apply(this, args); this.name = 'AlgoliaSearch' + name + 'Error'; } inherits_browser$2(AlgoliaSearchCustomError, AlgoliaSearchError); return AlgoliaSearchCustomError; } // late exports to let various fn defs and inherits take place var errors = { AlgoliaSearchError: AlgoliaSearchError, UnparsableJSON: createCustomError( 'UnparsableJSON', 'Could not parse the incoming response as JSON, see err.more for details' ), RequestTimeout: createCustomError( 'RequestTimeout', 'Request timedout before getting a response' ), Network: createCustomError( 'Network', 'Network issue, see err.more for details' ), JSONPScriptFail: createCustomError( 'JSONPScriptFail', '<script> was loaded but did not call our provided callback' ), JSONPScriptError: createCustomError( 'JSONPScriptError', '<script> unable to load due to an `error` event on it' ), Unknown: createCustomError( 'Unknown', 'Unknown error occured' ) }; // Parse cloud does not supports setTimeout // We do not store a setTimeout reference in the client everytime // We only fallback to a fake setTimeout when not available // setTimeout cannot be override globally sadly var exitPromise = function exitPromise(fn, _setTimeout) { _setTimeout(fn, 0); }; var buildSearchMethod_1 = buildSearchMethod; /** * Creates a search method to be used in clients * @param {string} queryParam the name of the attribute used for the query * @param {string} url the url * @return {function} the search method */ function buildSearchMethod(queryParam, url) { /** * The search method. Prepares the data and send the query to Algolia. * @param {string} query the string used for query search * @param {object} args additional parameters to send with the search * @param {function} [callback] the callback to be called with the client gets the answer * @return {undefined|Promise} If the callback is not provided then this methods returns a Promise */ return function search(query, args, callback) { // warn V2 users on how to search if (typeof query === 'function' && typeof args === 'object' || typeof callback === 'object') { // .search(query, params, cb) // .search(cb, params) throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)'); } // Normalizing the function signature if (arguments.length === 0 || typeof query === 'function') { // Usage : .search(), .search(cb) callback = query; query = ''; } else if (arguments.length === 1 || typeof args === 'function') { // Usage : .search(query/args), .search(query, cb) callback = args; args = undefined; } // At this point we have 3 arguments with values // Usage : .search(args) // careful: typeof null === 'object' if (typeof query === 'object' && query !== null) { args = query; query = undefined; } else if (query === undefined || query === null) { // .search(undefined/null) query = ''; } var params = ''; if (query !== undefined) { params += queryParam + '=' + encodeURIComponent(query); } var additionalUA; if (args !== undefined) { if (args.additionalUA) { additionalUA = args.additionalUA; delete args.additionalUA; } // `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if params = this.as._getSearchParams(args, params); } return this._search(params, url, callback, additionalUA); }; } var deprecate = function deprecate(fn, message) { var warned = false; function deprecated() { if (!warned) { /* eslint no-console:0 */ console.warn(message); warned = true; } return fn.apply(this, arguments); } return deprecated; }; var deprecatedMessage = function deprecatedMessage(previousUsage, newUsage) { var githubAnchorLink = previousUsage.toLowerCase() .replace(/[\.\(\)]/g, ''); return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage + '`. Please see https://github.com/algolia/algoliasearch-client-javascript/wiki/Deprecated#' + githubAnchorLink; }; var merge$2 = function merge(destination/* , sources */) { var sources = Array.prototype.slice.call(arguments); foreach(sources, function(source) { for (var keyName in source) { if (source.hasOwnProperty(keyName)) { if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') { destination[keyName] = merge({}, destination[keyName], source[keyName]); } else if (source[keyName] !== undefined) { destination[keyName] = source[keyName]; } } } }); return destination; }; var clone = function clone(obj) { return JSON.parse(JSON.stringify(obj)); }; var toStr = Object.prototype.toString; var isArguments$2 = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; // modified from https://github.com/es-shims/es5-shim var has$1 = Object.prototype.hasOwnProperty; var toStr$1 = Object.prototype.toString; var slice = Array.prototype.slice; var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has$1.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr$1.call(object) === '[object Function]'; var isArguments = isArguments$2(object); var isString = isObject && toStr$1.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has$1.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has$1.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has$1.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArguments$2(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; var objectKeys = keysShim; var omit$2 = function omit(obj, test) { var keys = objectKeys; var foreach$$1 = foreach; var filtered = {}; foreach$$1(keys(obj), function doFilter(keyName) { if (test(keyName) !== true) { filtered[keyName] = obj[keyName]; } }); return filtered; }; var toString$3 = {}.toString; var isarray = Array.isArray || function (arr) { return toString$3.call(arr) == '[object Array]'; }; var map$2 = function map(arr, fn) { var newArr = []; foreach(arr, function(item, itemIndex) { newArr.push(fn(item, itemIndex, arr)); }); return newArr; }; var IndexCore_1 = IndexCore; /* * Index class constructor. * You should not use this method directly but use initIndex() function */ function IndexCore(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; // make sure every index instance has it's own cache this.cache = {}; } /* * Clear all queries in cache */ IndexCore.prototype.clearCache = function() { this.cache = {}; }; /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the full text query * @param {object} [args] (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, * to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes * you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use an array (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all * values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you * want to highlight according to the query. * Attributes are separated by a comma. You can also use an array (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. * By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. * Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside * the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use an array (Example: attributesToSnippet: ['name:10','content:10']). * By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word * to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking * information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given * latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) * and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of * less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points * of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to * apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. * Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use an array (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]] * means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute * of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use an array (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Comma separated list: `"category,author"` or array `['category','author']` * Only attributes that have been added in **attributesForFaceting** index setting * can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should * be considered as optional when found in the query. * Comma separated and array are accepted. * - distinct: If set to 1, enable the distinct feature (disabled by default) * if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled * in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have * the same value for show_name, then only the best * one is kept and others are removed. * - restrictSearchableAttributes: List of attributes you want to use for * textual search (must be a subset of the attributesToIndex index setting) * either comma separated or as an array * @param {function} [callback] the result callback called with two arguments: * error: null or Error('message'). If false, the content contains the error. * content: the server answer that contains the list of results. */ IndexCore.prototype.search = buildSearchMethod_1('query'); /* * -- BETA -- * Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the similar query * @param {object} [args] (optional) if set, contains an object with query parameters. * All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters * are the two most useful to restrict the similar results and get more relevant content */ IndexCore.prototype.similarSearch = buildSearchMethod_1('similarQuery'); /* * Browse index content. The response content will have a `cursor` property that you can use * to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browse('cool songs', { * tagFilters: 'public,comments', * hitsPerPage: 500 * }, callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browse = function(query, queryParameters, callback) { var merge = merge$2; var indexObj = this; var page; var hitsPerPage; // we check variadic calls that are not the one defined // .browse()/.browse(fn) // => page = 0 if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') { page = 0; callback = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'number') { // .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn) page = arguments[0]; if (typeof arguments[1] === 'number') { hitsPerPage = arguments[1]; } else if (typeof arguments[1] === 'function') { callback = arguments[1]; hitsPerPage = undefined; } query = undefined; queryParameters = undefined; } else if (typeof arguments[0] === 'object') { // .browse(queryParameters)/.browse(queryParameters, cb) if (typeof arguments[1] === 'function') { callback = arguments[1]; } queryParameters = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') { // .browse(query, cb) callback = arguments[1]; queryParameters = undefined; } // otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb) // get search query parameters combining various possible calls // to .browse(); queryParameters = merge({}, queryParameters || {}, { page: page, hitsPerPage: hitsPerPage, query: query }); var params = this.as._getSearchParams(queryParameters, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse', body: {params: params}, hostType: 'read', callback: callback }); }; /* * Continue browsing from a previous position (cursor), obtained via a call to `.browse()`. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browseFrom('14lkfsakl32', callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browseFrom = function(cursor, callback) { return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse', body: {cursor: cursor}, hostType: 'read', callback: callback }); }; /* * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * * @param {string} params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} params.facetQuery Query for the facet search * @param {string} [params.*] Any search parameter of Algolia, * see https://www.algolia.com/doc/api-client/javascript/search#search-parameters * Pagination is not supported. The page and hitsPerPage parameters will be ignored. * @param callback (optional) */ IndexCore.prototype.searchForFacetValues = function(params, callback) { var clone$$1 = clone; var omit = omit$2; var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])'; if (params.facetName === undefined || params.facetQuery === undefined) { throw new Error(usage); } var facetName = params.facetName; var filteredParams = omit(clone$$1(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = this.as._getSearchParams(filteredParams, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters}, callback: callback }); }; IndexCore.prototype.searchFacet = deprecate(function(params, callback) { return this.searchForFacetValues(params, callback); }, deprecatedMessage( 'index.searchFacet(params[, callback])', 'index.searchForFacetValues(params[, callback])' )); IndexCore.prototype._search = function(params, url, callback, additionalUA) { return this.as._jsonRequest({ cache: this.cache, method: 'POST', url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: {params: params}, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: {params: params} }, callback: callback, additionalUA: additionalUA }); }; /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attrs (optional) if set, contains the array of attribute names to retrieve * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the object to retrieve or the error message if a failure occured */ IndexCore.prototype.getObject = function(objectID, attrs, callback) { var indexObj = this; if (arguments.length === 1 || typeof attrs === 'function') { callback = attrs; attrs = undefined; } var params = ''; if (attrs !== undefined) { params = '?attributes='; for (var i = 0; i < attrs.length; ++i) { if (i !== 0) { params += ','; } params += attrs[i]; } } return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params, hostType: 'read', callback: callback }); }; /* * Get several objects from this index * * @param objectIDs the array of unique identifier of objects to retrieve */ IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) { var isArray = isarray; var map = map$2; var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])'; if (!isArray(objectIDs)) { throw new Error(usage); } var indexObj = this; if (arguments.length === 1 || typeof attributesToRetrieve === 'function') { callback = attributesToRetrieve; attributesToRetrieve = undefined; } var body = { requests: map(objectIDs, function prepareRequest(objectID) { var request = { indexName: indexObj.indexName, objectID: objectID }; if (attributesToRetrieve) { request.attributesToRetrieve = attributesToRetrieve.join(','); } return request; }) }; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/*/objects', hostType: 'read', body: body, callback: callback }); }; IndexCore.prototype.as = null; IndexCore.prototype.indexName = null; IndexCore.prototype.typeAheadArgs = null; IndexCore.prototype.typeAheadValueOption = null; /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ var ms = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse$3(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse$3(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } var debug = createCommonjsModule(function (module, exports) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = ms; /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms$$1 = curr - (prevTime || curr); self.diff = ms$$1; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }); var debug_1 = debug.coerce; var debug_2 = debug.disable; var debug_3 = debug.enable; var debug_4 = debug.enabled; var debug_5 = debug.humanize; var debug_6 = debug.names; var debug_7 = debug.skips; var debug_8 = debug.formatters; var browser$1 = createCommonjsModule(function (module, exports) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } }); var browser_1 = browser$1.log; var browser_2 = browser$1.formatArgs; var browser_3 = browser$1.save; var browser_4 = browser$1.load; var browser_5 = browser$1.useColors; var browser_6 = browser$1.storage; var browser_7 = browser$1.colors; var debug$2 = browser$1('algoliasearch:src/hostIndexState.js'); var localStorageNamespace = 'algoliasearch-client-js'; var store; var moduleStore = { state: {}, set: function(key, data) { this.state[key] = data; return this.state[key]; }, get: function(key) { return this.state[key] || null; } }; var localStorageStore = { set: function(key, data) { moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure try { var namespace = JSON.parse(commonjsGlobal.localStorage[localStorageNamespace]); namespace[key] = data; commonjsGlobal.localStorage[localStorageNamespace] = JSON.stringify(namespace); return namespace[key]; } catch (e) { return localStorageFailure(key, e); } }, get: function(key) { try { return JSON.parse(commonjsGlobal.localStorage[localStorageNamespace])[key] || null; } catch (e) { return localStorageFailure(key, e); } } }; function localStorageFailure(key, e) { debug$2('localStorage failed with', e); cleanup(); store = moduleStore; return store.get(key); } store = supportsLocalStorage() ? localStorageStore : moduleStore; var store_1 = { get: getOrSet, set: getOrSet, supportsLocalStorage: supportsLocalStorage }; function getOrSet(key, data) { if (arguments.length === 1) { return store.get(key); } return store.set(key, data); } function supportsLocalStorage() { try { if ('localStorage' in commonjsGlobal && commonjsGlobal.localStorage !== null) { if (!commonjsGlobal.localStorage[localStorageNamespace]) { // actual creation of the namespace commonjsGlobal.localStorage.setItem(localStorageNamespace, JSON.stringify({})); } return true; } return false; } catch (_) { return false; } } // In case of any error on localStorage, we clean our own namespace, this should handle // quota errors when a lot of keys + data are used function cleanup() { try { commonjsGlobal.localStorage.removeItem(localStorageNamespace); } catch (_) { // nothing to do } } var AlgoliaSearchCore_1 = AlgoliaSearchCore; // We will always put the API KEY in the JSON body in case of too long API KEY, // to avoid query string being too long and failing in various conditions (our server limit, browser limit, // proxies limit) var MAX_API_KEY_LENGTH = 500; var RESET_APP_DATA_TIMER = process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) || 60 * 2 * 1000; // after 2 minutes reset to first host /* * Algolia Search library initialization * https://www.algolia.com/ * * @param {string} applicationID - Your applicationID, found in your dashboard * @param {string} apiKey - Your API key, found in your dashboard * @param {Object} [opts] * @param {number} [opts.timeout=2000] - The request timeout set in milliseconds, * another request will be issued after this timeout * @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API. * Set to 'https:' to force using https. * Default to document.location.protocol in browsers * @param {Object|Array} [opts.hosts={ * read: [this.applicationID + '-dsn.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]), * write: [this.applicationID + '.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]) - The hosts to use for Algolia Search API. * If you provide them, you will less benefit from our HA implementation */ function AlgoliaSearchCore(applicationID, apiKey, opts) { var debug = browser$1('algoliasearch'); var clone$$1 = clone; var isArray = isarray; var map = map$2; var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)'; if (opts._allowEmptyCredentials !== true && !applicationID) { throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage); } if (opts._allowEmptyCredentials !== true && !apiKey) { throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage); } this.applicationID = applicationID; this.apiKey = apiKey; this.hosts = { read: [], write: [] }; opts = opts || {}; var protocol = opts.protocol || 'https:'; this._timeouts = opts.timeouts || { connect: 1 * 1000, // 500ms connect is GPRS latency read: 2 * 1000, write: 30 * 1000 }; // backward compat, if opts.timeout is passed, we use it to configure all timeouts like before if (opts.timeout) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout; } // while we advocate for colon-at-the-end values: 'http:' for `opts.protocol` // we also accept `http` and `https`. It's a common error. if (!/:$/.test(protocol)) { protocol = protocol + ':'; } if (opts.protocol !== 'http:' && opts.protocol !== 'https:') { throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)'); } this._checkAppIdData(); if (!opts.hosts) { var defaultHosts = map(this._shuffleResult, function(hostNumber) { return applicationID + '-' + hostNumber + '.algolianet.com'; }); // no hosts given, compute defaults this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts); this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts); } else if (isArray(opts.hosts)) { // when passing custom hosts, we need to have a different host index if the number // of write/read hosts are different. this.hosts.read = clone$$1(opts.hosts); this.hosts.write = clone$$1(opts.hosts); } else { this.hosts.read = clone$$1(opts.hosts.read); this.hosts.write = clone$$1(opts.hosts.write); } // add protocol and lowercase hosts this.hosts.read = map(this.hosts.read, prepareHost(protocol)); this.hosts.write = map(this.hosts.write, prepareHost(protocol)); this.extraHeaders = {}; // In some situations you might want to warm the cache this.cache = opts._cache || {}; this._ua = opts._ua; this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache; this._useFallback = opts.useFallback === undefined ? true : opts.useFallback; this._setTimeout = opts._setTimeout; debug('init done, %j', this); } /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ AlgoliaSearchCore.prototype.initIndex = function(indexName) { return new IndexCore_1(this, indexName); }; /** * Add an extra field to the HTTP request * * @param name the header field name * @param value the header field value */ AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) { this.extraHeaders[name.toLowerCase()] = value; }; /** * Get the value of an extra HTTP header * * @param name the header field name */ AlgoliaSearchCore.prototype.getExtraHeader = function(name) { return this.extraHeaders[name.toLowerCase()]; }; /** * Remove an extra field from the HTTP request * * @param name the header field name */ AlgoliaSearchCore.prototype.unsetExtraHeader = function(name) { delete this.extraHeaders[name.toLowerCase()]; }; /** * Augment sent x-algolia-agent with more data, each agent part * is automatically separated from the others by a semicolon; * * @param algoliaAgent the agent to add */ AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) { if (this._ua.indexOf(';' + algoliaAgent) === -1) { this._ua += ';' + algoliaAgent; } }; /* * Wrapper that try all hosts to maximize the quality of service */ AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) { this._checkAppIdData(); var requestDebug = browser$1('algoliasearch:' + initialOpts.url); var body; var additionalUA = initialOpts.additionalUA || ''; var cache = initialOpts.cache; var client = this; var tries = 0; var usingFallback = false; var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback; var headers; if ( this.apiKey.length > MAX_API_KEY_LENGTH && initialOpts.body !== undefined && (initialOpts.body.params !== undefined || // index.search() initialOpts.body.requests !== undefined) // client.search() ) { initialOpts.body.apiKey = this.apiKey; headers = this._computeRequestHeaders(additionalUA, false); } else { headers = this._computeRequestHeaders(additionalUA); } if (initialOpts.body !== undefined) { body = safeJSONStringify(initialOpts.body); } requestDebug('request start'); var debugData = []; function doRequest(requester, reqOpts) { client._checkAppIdData(); var startTime = new Date(); var cacheID; if (client._useCache) { cacheID = initialOpts.url; } // as we sometime use POST requests to pass parameters (like query='aa'), // the cacheID must also include the body to be different between calls if (client._useCache && body) { cacheID += '_body_' + reqOpts.body; } // handle cache existence if (client._useCache && cache && cache[cacheID] !== undefined) { requestDebug('serving response from cache'); return client._promise.resolve(JSON.parse(cache[cacheID])); } // if we reached max tries if (tries >= client.hosts[initialOpts.hostType].length) { if (!hasFallback || usingFallback) { requestDebug('could not get any response'); // then stop return client._promise.reject(new errors.AlgoliaSearchError( 'Cannot connect to the AlgoliaSearch API.' + ' Send an email to [email protected] to report and resolve the issue.' + ' Application id was: ' + client.applicationID, {debugData: debugData} )); } requestDebug('switching to fallback'); // let's try the fallback starting from here tries = 0; // method, url and body are fallback dependent reqOpts.method = initialOpts.fallback.method; reqOpts.url = initialOpts.fallback.url; reqOpts.jsonBody = initialOpts.fallback.body; if (reqOpts.jsonBody) { reqOpts.body = safeJSONStringify(reqOpts.jsonBody); } // re-compute headers, they could be omitting the API KEY headers = client._computeRequestHeaders(additionalUA); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); client._setHostIndexByType(0, initialOpts.hostType); usingFallback = true; // the current request is now using fallback return doRequest(client._request.fallback, reqOpts); } var currentHost = client._getHostByType(initialOpts.hostType); var url = currentHost + reqOpts.url; var options = { body: reqOpts.body, jsonBody: reqOpts.jsonBody, method: reqOpts.method, headers: headers, timeouts: reqOpts.timeouts, debug: requestDebug }; requestDebug('method: %s, url: %s, headers: %j, timeouts: %d', options.method, url, options.headers, options.timeouts); if (requester === client._request.fallback) { requestDebug('using fallback'); } // `requester` is any of this._request or this._request.fallback // thus it needs to be called using the client as context return requester.call(client, url, options).then(success, tryFallback); function success(httpResponse) { // compute the status of the response, // // When in browser mode, using XDR or JSONP, we have no statusCode available // So we rely on our API response `status` property. // But `waitTask` can set a `status` property which is not the statusCode (it's the task status) // So we check if there's a `message` along `status` and it means it's an error // // That's the only case where we have a response.status that's not the http statusCode var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status || // this is important to check the request statusCode AFTER the body eventual // statusCode because some implementations (jQuery XDomainRequest transport) may // send statusCode 200 while we had an error httpResponse.statusCode || // When in browser mode, using XDR or JSONP // we default to success when no error (no response.status && response.message) // If there was a JSON.parse() error then body is null and it fails httpResponse && httpResponse.body && 200; requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j', httpResponse.statusCode, status, httpResponse.headers); var httpResponseOk = Math.floor(status / 100) === 2; var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime, statusCode: status }); if (httpResponseOk) { if (client._useCache && cache) { cache[cacheID] = httpResponse.responseText; } return httpResponse.body; } var shouldRetry = Math.floor(status / 100) !== 4; if (shouldRetry) { tries += 1; return retryRequest(); } requestDebug('unrecoverable error'); // no success and no retry => fail var unrecoverableError = new errors.AlgoliaSearchError( httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status} ); return client._promise.reject(unrecoverableError); } function tryFallback(err) { // error cases: // While not in fallback mode: // - CORS not supported // - network error // While in fallback mode: // - timeout // - network error // - badly formatted JSONP (script loaded, did not call our callback) // In both cases: // - uncaught exception occurs (TypeError) requestDebug('error: %s, stack: %s', err.message, err.stack); var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime }); if (!(err instanceof errors.AlgoliaSearchError)) { err = new errors.Unknown(err && err.message, err); } tries += 1; // stop the request implementation when: if ( // we did not generate this error, // it comes from a throw in some other piece of code err instanceof errors.Unknown || // server sent unparsable JSON err instanceof errors.UnparsableJSON || // max tries and already using fallback or no fallback tries >= client.hosts[initialOpts.hostType].length && (usingFallback || !hasFallback)) { // stop request implementation for this command err.debugData = debugData; return client._promise.reject(err); } // When a timeout occured, retry by raising timeout if (err instanceof errors.RequestTimeout) { return retryRequestWithHigherTimeout(); } return retryRequest(); } function retryRequest() { requestDebug('retrying request'); client._incrementHostIndex(initialOpts.hostType); return doRequest(requester, reqOpts); } function retryRequestWithHigherTimeout() { requestDebug('retrying request with higher timeout'); client._incrementHostIndex(initialOpts.hostType); client._incrementTimeoutMultipler(); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); return doRequest(requester, reqOpts); } } var promise = doRequest( client._request, { url: initialOpts.url, method: initialOpts.method, body: body, jsonBody: initialOpts.body, timeouts: client._getTimeoutsForRequest(initialOpts.hostType) } ); // either we have a callback // either we are using promises if (typeof initialOpts.callback === 'function') { promise.then(function okCb(content) { exitPromise(function() { initialOpts.callback(null, content); }, client._setTimeout || setTimeout); }, function nookCb(err) { exitPromise(function() { initialOpts.callback(err); }, client._setTimeout || setTimeout); }); } else { return promise; } }; /* * Transform search param object in query string * @param {object} args arguments to add to the current query string * @param {string} params current query string * @return {string} the final query string */ AlgoliaSearchCore.prototype._getSearchParams = function(args, params) { if (args === undefined || args === null) { return params; } for (var key in args) { if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) { params += params === '' ? '' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]); } } return params; }; AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) { var forEach = foreach; var ua = additionalUA ? this._ua + ';' + additionalUA : this._ua; var requestHeaders = { 'x-algolia-agent': ua, 'x-algolia-application-id': this.applicationID }; // browser will inline headers in the url, node.js will use http headers // but in some situations, the API KEY will be too long (big secured API keys) // so if the request is a POST and the KEY is very long, we will be asked to not put // it into headers but in the JSON body if (withAPIKey !== false) { requestHeaders['x-algolia-api-key'] = this.apiKey; } if (this.userToken) { requestHeaders['x-algolia-usertoken'] = this.userToken; } if (this.securityTags) { requestHeaders['x-algolia-tagfilters'] = this.securityTags; } forEach(this.extraHeaders, function addToRequestHeaders(value, key) { requestHeaders[key] = value; }); return requestHeaders; }; /** * Search through multiple indices at the same time * @param {Object[]} queries An array of queries you want to run. * @param {string} queries[].indexName The index name you want to target * @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params` * @param {Object} queries[].params Any search param like hitsPerPage, .. * @param {Function} callback Callback to be called * @return {Promise|undefined} Returns a promise if no callback given */ AlgoliaSearchCore.prototype.search = function(queries, opts, callback) { var isArray = isarray; var map = map$2; var usage = 'Usage: client.search(arrayOfQueries[, callback])'; if (!isArray(queries)) { throw new Error(usage); } if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } var client = this; var postObj = { requests: map(queries, function prepareRequest(query) { var params = ''; // allow query.query // so we are mimicing the index.search(query, params) method // {indexName:, query:, params:} if (query.query !== undefined) { params += 'query=' + encodeURIComponent(query.query); } return { indexName: query.indexName, params: client._getSearchParams(query.params, params) }; }) }; var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) { return requestId + '=' + encodeURIComponent( '/1/indexes/' + encodeURIComponent(request.indexName) + '?' + request.params ); }).join('&'); var url = '/1/indexes/*/queries'; if (opts.strategy !== undefined) { url += '?strategy=' + opts.strategy; } return this._jsonRequest({ cache: this.cache, method: 'POST', url: url, body: postObj, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/*', body: { params: JSONPParams } }, callback: callback }); }; /** * Set the extra security tagFilters header * @param {string|array} tags The list of tags defining the current security filters */ AlgoliaSearchCore.prototype.setSecurityTags = function(tags) { if (Object.prototype.toString.call(tags) === '[object Array]') { var strTags = []; for (var i = 0; i < tags.length; ++i) { if (Object.prototype.toString.call(tags[i]) === '[object Array]') { var oredTags = []; for (var j = 0; j < tags[i].length; ++j) { oredTags.push(tags[i][j]); } strTags.push('(' + oredTags.join(',') + ')'); } else { strTags.push(tags[i]); } } tags = strTags.join(','); } this.securityTags = tags; }; /** * Set the extra user token header * @param {string} userToken The token identifying a uniq user (used to apply rate limits) */ AlgoliaSearchCore.prototype.setUserToken = function(userToken) { this.userToken = userToken; }; /** * Clear all queries in client's cache * @return undefined */ AlgoliaSearchCore.prototype.clearCache = function() { this.cache = {}; }; /** * Set the number of milliseconds a request can take before automatically being terminated. * @deprecated * @param {Number} milliseconds */ AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) { if (milliseconds) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds; } }; /** * Set the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) { this._timeouts = timeouts; }; /** * Get the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.getTimeouts = function() { return this._timeouts; }; AlgoliaSearchCore.prototype._getAppIdData = function() { var data = store_1.get(this.applicationID); if (data !== null) this._cacheAppIdData(data); return data; }; AlgoliaSearchCore.prototype._setAppIdData = function(data) { data.lastChange = (new Date()).getTime(); this._cacheAppIdData(data); return store_1.set(this.applicationID, data); }; AlgoliaSearchCore.prototype._checkAppIdData = function() { var data = this._getAppIdData(); var now = (new Date()).getTime(); if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) { return this._resetInitialAppIdData(data); } return data; }; AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) { var newData = data || {}; newData.hostIndexes = {read: 0, write: 0}; newData.timeoutMultiplier = 1; newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]); return this._setAppIdData(newData); }; AlgoliaSearchCore.prototype._cacheAppIdData = function(data) { this._hostIndexes = data.hostIndexes; this._timeoutMultiplier = data.timeoutMultiplier; this._shuffleResult = data.shuffleResult; }; AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) { var foreach$$1 = foreach; var currentData = this._getAppIdData(); foreach$$1(newData, function(value, key) { currentData[key] = value; }); return this._setAppIdData(currentData); }; AlgoliaSearchCore.prototype._getHostByType = function(hostType) { return this.hosts[hostType][this._getHostIndexByType(hostType)]; }; AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() { return this._timeoutMultiplier; }; AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) { return this._hostIndexes[hostType]; }; AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) { var clone$$1 = clone; var newHostIndexes = clone$$1(this._hostIndexes); newHostIndexes[hostType] = hostIndex; this._partialAppIdDataUpdate({hostIndexes: newHostIndexes}); return hostIndex; }; AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) { return this._setHostIndexByType( (this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType ); }; AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() { var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4); return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier}); }; AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) { return { connect: this._timeouts.connect * this._timeoutMultiplier, complete: this._timeouts[hostType] * this._timeoutMultiplier }; }; function prepareHost(protocol) { return function prepare(host) { return protocol + '//' + host.toLowerCase(); }; } // Prototype.js < 1.7, a widely used library, defines a weird // Array.prototype.toJSON function that will fail to stringify our content // appropriately // refs: // - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q // - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c // - http://stackoverflow.com/a/3148441/147079 function safeJSONStringify(obj) { /* eslint no-extend-native:0 */ if (Array.prototype.toJSON === undefined) { return JSON.stringify(obj); } var toJSON = Array.prototype.toJSON; delete Array.prototype.toJSON; var out = JSON.stringify(obj); Array.prototype.toJSON = toJSON; return out; } function shuffle(array) { var currentIndex = array.length; var temporaryValue; var randomIndex; // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function removeCredentials(headers) { var newHeaders = {}; for (var headerName in headers) { if (Object.prototype.hasOwnProperty.call(headers, headerName)) { var value; if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') { value = '**hidden for security purposes**'; } else { value = headers[headerName]; } newHeaders[headerName] = value; } } return newHeaders; } var win; if (typeof window !== "undefined") { win = window; } else if (typeof commonjsGlobal !== "undefined") { win = commonjsGlobal; } else if (typeof self !== "undefined"){ win = self; } else { win = {}; } var window_1 = win; var es6Promise = createCommonjsModule(function (module, exports) { /*! * @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/stefanpenner/es6-promise/master/LICENSE * @version 4.1.1 */ (function (global, factory) { module.exports = factory(); }(commonjsGlobal, (function () { function objectOrFunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function isFunction(x) { return typeof x === 'function'; } var _isArray = undefined; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } var isArray = _isArray; var len = 0; var vertxNext = undefined; var customSchedulerFn = undefined; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, 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. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var r = commonjsRequire; var vertx = r('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && typeof commonjsRequire === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var _arguments = arguments; var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { (function () { var callback = _arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); })(); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve$1(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(16); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { try { then$$1.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then$$1) { asap(function (promise) { var sealed = false; var error = tryThen(then$$1, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return resolve(promise, value); }, function (reason) { return reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$1) { if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { handleOwnThenable(promise, maybeThenable); } else { if (then$$1 === GET_THEN_ERROR) { reject(promise, GET_THEN_ERROR.error); GET_THEN_ERROR.error = null; } else if (then$$1 === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$1)) { handleForeignThenable(promise, maybeThenable, then$$1); } else { fulfill(promise, maybeThenable); } } } function resolve(promise, value) { if (promise === value) { reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = undefined, callback = undefined, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = undefined, error = undefined, succeeded = undefined, failed = undefined; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value.error = null; } else { succeeded = true; } if (promise === value) { reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { resolve(promise, value); }, function rejectPromise(reason) { reject(promise, reason); }); } catch (e) { reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function Enumerator$1(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(input); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { reject(this.promise, validationError()); } } function validationError() { return new Error('Array Methods must be provided an Array'); } Enumerator$1.prototype._enumerate = function (input) { for (var i = 0; this._state === PENDING && i < input.length; i++) { this._eachEntry(input[i], i); } }; Enumerator$1.prototype._eachEntry = function (entry, i) { var c = this._instanceConstructor; var resolve$$1 = c.resolve; if (resolve$$1 === resolve$1) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise$2) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$1) { return resolve$$1(entry); }), i); } } else { this._willSettleAt(resolve$$1(entry), i); } }; Enumerator$1.prototype._settledAt = function (state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator$1.prototype._willSettleAt = function (promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all$1(entries) { return new Enumerator$1(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race$1(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject$1(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** 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 let 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){ let 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 Promise$2(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew(); } } Promise$2.all = all$1; Promise$2.race = race$1; Promise$2.resolve = resolve$1; Promise$2.reject = reject$1; Promise$2._setScheduler = setScheduler; Promise$2._setAsap = setAsap; Promise$2._asap = asap; Promise$2.prototype = { constructor: Promise$2, /** 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 let 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 let 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: then, /** `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 _catch(onRejection) { return this.then(null, onRejection); } }; /*global self*/ function polyfill$1() { var local = undefined; if (typeof commonjsGlobal !== 'undefined') { local = commonjsGlobal; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise$2; } // Strange compat.. Promise$2.polyfill = polyfill$1; Promise$2.Promise = Promise$2; return Promise$2; }))); }); // 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. var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; var encode$1 = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map$4(objectKeys$2(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray$2(obj[k])) { return map$4(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray$2 = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map$4 (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys$2 = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; var inlineHeaders_1 = inlineHeaders; function inlineHeaders(url, headers) { if (/\?/.test(url)) { url += '&'; } else { url += '?'; } return url + encode$1(headers); } var jsonpRequest_1 = jsonpRequest; var JSONPCounter = 0; function jsonpRequest(url, opts, cb) { if (opts.method !== 'GET') { cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.')); return; } opts.debug('JSONP: start'); var cbCalled = false; var timedOut = false; JSONPCounter += 1; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); var cbName = 'algoliaJSONP_' + JSONPCounter; var done = false; window[cbName] = function(data) { removeGlobals(); if (timedOut) { opts.debug('JSONP: Late answer, ignoring'); return; } cbCalled = true; clean(); cb(null, { body: data/* , // We do not send the statusCode, there's no statusCode in JSONP, it will be // computed using data.status && data.message like with XDR statusCode*/ }); }; // add callback by hand url += '&callback=' + cbName; // add body params manually if (opts.jsonBody && opts.jsonBody.params) { url += '&' + opts.jsonBody.params; } var ontimeout = setTimeout(timeout, opts.timeouts.complete); // script onreadystatechange needed only for // <= IE8 // https://github.com/angular/angular.js/issues/4523 script.onreadystatechange = readystatechange; script.onload = success; script.onerror = error; script.async = true; script.defer = true; script.src = url; head.appendChild(script); function success() { opts.debug('JSONP: success'); if (done || timedOut) { return; } done = true; // script loaded but did not call the fn => script loading error if (!cbCalled) { opts.debug('JSONP: Fail. Script loaded but did not call the callback'); clean(); cb(new errors.JSONPScriptFail()); } } function readystatechange() { if (this.readyState === 'loaded' || this.readyState === 'complete') { success(); } } function clean() { clearTimeout(ontimeout); script.onload = null; script.onreadystatechange = null; script.onerror = null; head.removeChild(script); } function removeGlobals() { try { delete window[cbName]; delete window[cbName + '_loaded']; } catch (e) { window[cbName] = window[cbName + '_loaded'] = undefined; } } function timeout() { opts.debug('JSONP: Script timeout'); timedOut = true; clean(); cb(new errors.RequestTimeout()); } function error() { opts.debug('JSONP: Script error'); if (done || timedOut) { return; } clean(); cb(new errors.JSONPScriptError()); } } var places = createPlacesClient; function createPlacesClient(algoliasearch) { return function places(appID, apiKey, opts) { var cloneDeep = clone; opts = opts && cloneDeep(opts) || {}; opts.hosts = opts.hosts || [ 'places-dsn.algolia.net', 'places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com' ]; // allow initPlaces() no arguments => community rate limited if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) { appID = ''; apiKey = ''; opts._allowEmptyCredentials = true; } var client = algoliasearch(appID, apiKey, opts); var index = client.initIndex('places'); index.search = buildSearchMethod_1('query', '/1/places/query'); index.getObject = function(objectID, callback) { return this.as._jsonRequest({ method: 'GET', url: '/1/places/' + encodeURIComponent(objectID), hostType: 'read', callback: callback }); }; return index; }; } var getDocumentProtocol_1 = getDocumentProtocol; function getDocumentProtocol() { var protocol = window.document.location.protocol; // when in `file:` mode (local html file), default to `http:` if (protocol !== 'http:' && protocol !== 'https:') { protocol = 'http:'; } return protocol; } var version$5 = '3.24.5'; var Promise$3 = window_1.Promise || es6Promise.Promise; // This is the standalone browser build entry point // Browser implementation of the Algolia Search JavaScript client, // using XMLHttpRequest, XDomainRequest and JSONP as fallback var createAlgoliasearch = function createAlgoliasearch(AlgoliaSearch, uaSuffix) { var inherits = inherits_browser$2; var errors$$1 = errors; var inlineHeaders = inlineHeaders_1; var jsonpRequest = jsonpRequest_1; var places$$1 = places; uaSuffix = uaSuffix || ''; function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = clone; var getDocumentProtocol = getDocumentProtocol_1; opts = cloneDeep(opts || {}); if (opts.protocol === undefined) { opts.protocol = getDocumentProtocol(); } opts._ua = opts._ua || algoliasearch.ua; return new AlgoliaSearchBrowser(applicationID, apiKey, opts); } algoliasearch.version = version$5; algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version; algoliasearch.initPlaces = places$$1(algoliasearch); // we expose into window no matter how we are used, this will allow // us to easily debug any website running algolia window_1.__algolia = { debug: browser$1, algoliasearch: algoliasearch }; var support = { hasXMLHttpRequest: 'XMLHttpRequest' in window_1, hasXDomainRequest: 'XDomainRequest' in window_1 }; if (support.hasXMLHttpRequest) { support.cors = 'withCredentials' in new XMLHttpRequest(); } function AlgoliaSearchBrowser() { // call AlgoliaSearch constructor AlgoliaSearch.apply(this, arguments); } inherits(AlgoliaSearchBrowser, AlgoliaSearch); AlgoliaSearchBrowser.prototype._request = function request(url, opts) { return new Promise$3(function wrapRequest(resolve, reject) { // no cors or XDomainRequest, no request if (!support.cors && !support.hasXDomainRequest) { // very old browser, not supported reject(new errors$$1.Network('CORS not supported')); return; } url = inlineHeaders(url, opts.headers); var body = opts.body; var req = support.cors ? new XMLHttpRequest() : new XDomainRequest(); var reqTimeout; var timedOut; var connected = false; reqTimeout = setTimeout(onTimeout, opts.timeouts.connect); // we set an empty onprogress listener // so that XDomainRequest on IE9 is not aborted // refs: // - https://github.com/algolia/algoliasearch-client-js/issues/76 // - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment req.onprogress = onProgress; if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange; req.onload = onLoad; req.onerror = onError; // do not rely on default XHR async flag, as some analytics code like hotjar // breaks it and set it to false by default if (req instanceof XMLHttpRequest) { req.open(opts.method, url, true); } else { req.open(opts.method, url); } // headers are meant to be sent after open if (support.cors) { if (body) { if (opts.method === 'POST') { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests req.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); } else { req.setRequestHeader('content-type', 'application/json'); } } req.setRequestHeader('accept', 'application/json'); } req.send(body); // event object not received in IE8, at least // but we do not use it, still important to note function onLoad(/* event */) { // When browser does not supports req.timeout, we can // have both a load and timeout event, since handled by a dumb setTimeout if (timedOut) { return; } clearTimeout(reqTimeout); var out; try { out = { body: JSON.parse(req.responseText), responseText: req.responseText, statusCode: req.status, // XDomainRequest does not have any response headers headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {} }; } catch (e) { out = new errors$$1.UnparsableJSON({ more: req.responseText }); } if (out instanceof errors$$1.UnparsableJSON) { reject(out); } else { resolve(out); } } function onError(event) { if (timedOut) { return; } clearTimeout(reqTimeout); // error event is trigerred both with XDR/XHR on: // - DNS error // - unallowed cross domain request reject( new errors$$1.Network({ more: event }) ); } function onTimeout() { timedOut = true; req.abort(); reject(new errors$$1.RequestTimeout()); } function onConnect() { connected = true; clearTimeout(reqTimeout); reqTimeout = setTimeout(onTimeout, opts.timeouts.complete); } function onProgress() { if (!connected) onConnect(); } function onReadyStateChange() { if (!connected && req.readyState > 1) onConnect(); } }); }; AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) { url = inlineHeaders(url, opts.headers); return new Promise$3(function wrapJsonpRequest(resolve, reject) { jsonpRequest(url, opts, function jsonpRequestDone(err, content) { if (err) { reject(err); return; } resolve(content); }); }); }; AlgoliaSearchBrowser.prototype._promise = { reject: function rejectPromise(val) { return Promise$3.reject(val); }, resolve: function resolvePromise(val) { return Promise$3.resolve(val); }, delay: function delayPromise(ms) { return new Promise$3(function resolveOnTimeout(resolve/* , reject*/) { setTimeout(resolve, ms); }); } }; return algoliasearch; }; var algoliasearchLite = createAlgoliasearch(AlgoliaSearchCore_1, '(lite) '); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE$1 = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = _arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = _arrayMap(values, _baseUnary(iteratee)); } if (comparator) { includes = _arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE$1) { includes = _cacheHas; isCommon = false; values = new _SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } var _baseDifference = baseDifference; /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = _baseRest(function(array, values) { return isArrayLikeObject_1(array) ? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true)) : []; }); var difference_1 = difference; /** Used for built-in method references. */ var objectProto$20 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$18 = objectProto$20.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty$18.call(object, key); } var _baseHas = baseHas; /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has$2(object, path) { return object != null && _hasPath(object, path, _baseHas); } var has_1 = has$2; /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = has_1(connectorDesc, 'refine'); var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters'); var hasMetadata = has_1(connectorDesc, 'getMetadata'); var hasTransitionState = has_1(connectorDesc, 'transitionState'); var hasCleanUp = has_1(connectorDesc, 'cleanUp'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { inherits(Connector, _Component); function Connector(props, context) { classCallCheck(this, Connector); var _this = possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais, store = _context$ais.store, widgetsManager = _context$ais.widgetsManager; var canRender = false; _this.state = { props: _this.getProvidedProps(_extends({}, props, { canRender: canRender })), canRender: canRender // use to know if a component is rendered (browser), or not (server). }; _this.unsubscribe = store.subscribe(function () { if (_this.state.canRender) { _this.setState({ props: _this.getProvidedProps(_extends({}, _this.props, { canRender: _this.state.canRender })) }); } }); if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget(_this); } return _this; } createClass(Connector, [{ key: 'getMetadata', value: function getMetadata(nextWidgetsState) { if (hasMetadata) { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters) { if (hasSearchParameters) { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets); } return null; } }, { key: 'transitionState', value: function transitionState(prevWidgetsState, nextWidgetsState) { if (hasTransitionState) { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: 'componentDidMount', value: function componentDidMount() { this.setState({ canRender: true }); } }, { key: 'componentWillMount', value: function componentWillMount() { if (connectorDesc.getSearchParameters) { this.context.ais.onSearchParameters(connectorDesc.getSearchParameters, this.context, this.props); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!isEqual_1(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); // will schedule an update if (hasCleanUp) { var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onSearchStateChange(removeEmptyKey(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = shallowEqual(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.props, nextState.props); } }, { key: 'render', value: function render() { if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues } : {}; return React__default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component), _class.displayName = connectorDesc.displayName + '(' + getDisplayName(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: propTypes.object.isRequired, multiIndexContext: propTypes.object }, _initialiseProps = function _initialiseProps() { var _this2 = this; this.getProvidedProps = function (props) { var store = _this2.context.ais.store; var _store$getState = store.getState(), results = _store$getState.results, searching = _store$getState.searching, error = _store$getState.error, widgets = _store$getState.widgets, metadata = _store$getState.metadata, resultsFacetValues = _store$getState.resultsFacetValues, searchingForFacetValues = _store$getState.searchingForFacetValues, isSearchStalled = _store$getState.isSearchStalled; var searchResults = { results: results, searching: searching, error: error, searchingForFacetValues: searchingForFacetValues, isSearchStalled: isSearchStalled }; return connectorDesc.getProvidedProps.call(_this2, props, widgets, searchResults, metadata, resultsFacetValues); }; this.refine = function () { var _connectorDesc$refine; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this2.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this2.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this2.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { var _connectorDesc$cleanU; for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this2].concat(args)); }; }, _temp; }; } function getIndex(context) { return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results && !searchResults.results.hits) { return searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null; } else { return searchResults.results ? searchResults.results : null; } } function hasMultipleIndex(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndex(context)) { return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage); } else { // When we have a multi index page with shared widgets we should also // reset their page to 1 if the resetPage is provided. Otherwise the // indices will always be reset // see: https://github.com/algolia/react-instantsearch/issues/310 // see: https://github.com/algolia/react-instantsearch/issues/637 if (searchState.indices && resetPage) { Object.keys(searchState.indices).forEach(function (targetedIndex) { searchState = refineValue(searchState, { page: 1 }, { multiIndexContext: { targetedIndex: targetedIndex } }, true, namespace); }); } return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage); } } function refineMultiIndex(searchState, nextRefinement, context, resetPage) { var page = resetPage ? { page: 1 } : undefined; var index = getIndex(context); var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, nextRefinement, page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) { var _babelHelpers$extends3; var index = getIndex(context); var page = resetPage ? { page: 1 } : undefined; var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], (_babelHelpers$extends3 = {}, defineProperty$2(_babelHelpers$extends3, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), defineProperty$2(_babelHelpers$extends3, 'page', 1), _babelHelpers$extends3)))) : _extends({}, searchState.indices, defineProperty$2({}, index, _extends(defineProperty$2({}, namespace, nextRefinement), page))); return _extends({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _extends({}, searchState, defineProperty$2({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page); } function getNamespaceAndAttributeName(id) { var parts = id.match(/^([^.]*)\.(.*)/); var namespace = parts && parts[1]; var attributeName = parts && parts[2]; return { namespace: namespace, attributeName: attributeName }; } // eslint-disable-next-line max-params function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) { var index = getIndex(context); var _getNamespaceAndAttri = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri.namespace, attributeName = _getNamespaceAndAttri.attributeName; var refinements = hasMultipleIndex(context) && searchState.indices && namespace && searchState.indices['' + index] && has_1(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && has_1(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && has_1(searchState[namespace], attributeName) || !hasMultipleIndex(context) && has_1(searchState, id); if (refinements) { var currentRefinement = void 0; if (hasMultipleIndex(context)) { currentRefinement = namespace ? get_1(searchState.indices['' + index][namespace], attributeName) : get_1(searchState.indices[index], id); } else { currentRefinement = namespace ? get_1(searchState[namespace], attributeName) : get_1(searchState, id); } return refinementsCallback(currentRefinement); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var index = getIndex(context); var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri2.namespace, attributeName = _getNamespaceAndAttri2.attributeName; if (hasMultipleIndex(context)) { return namespace ? _extends({}, searchState, { indices: _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], defineProperty$2({}, namespace, omit_1(searchState.indices[index][namespace], '' + attributeName))))) }) : omit_1(searchState, 'indices.' + index + '.' + id); } else { return namespace ? _extends({}, searchState, defineProperty$2({}, namespace, omit_1(searchState[namespace], '' + attributeName))) : omit_1(searchState, '' + id); } } function getId() { return 'configure'; } var connectConfigure = createConnector({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = omit_1(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = omit_1(props, 'children'); var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : []; this._props = props; var nextValue = defineProperty$2({}, id, _extends({}, omit_1(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var index = getIndex(this.context); var subState = hasMultipleIndex(this.context) && searchState.indices ? searchState.indices[index] : searchState; var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : []; var configureState = configureKeys.reduce(function (acc, item) { if (!props[item]) { acc[item] = subState[id][item]; } return acc; }, {}); var nextValue = defineProperty$2({}, id, configureState); return refineValue(searchState, nextValue, this.context); } }); var Configure = (function () { return null; }); /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * * import { Configure, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure distinct={1} /> * </InstantSearch> * ); * } */ var Configure$1 = connectConfigure(Configure); /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attribute: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attribute` and `currentRefinement` are metadata containing row values. * @providedPropType {string} query - the search query */ var connectCurrentRefinements = createConnector({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { if (typeof meta.items !== 'undefined') { if (!props.clearsQuery && meta.id === 'query') { return res; } else { if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') { return res; } return res.concat(meta.items.map(function (item) { return _extends({}, item, { id: meta.id, index: meta.index }); })); } } return res; }, []); return { items: props.transformItems ? props.transformItems(items) : items, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, items) { // `value` corresponds to our internal clear function computed in each connector metadata. var refinementsToClear = items instanceof Array ? items.map(function (item) { return item.value; }) : [items]; return refinementsToClear.reduce(function (res, clear) { return clear(res); }, searchState); } }); var PanelCallbackHandler = function (_Component) { inherits(PanelCallbackHandler, _Component); function PanelCallbackHandler() { classCallCheck(this, PanelCallbackHandler); return possibleConstructorReturn(this, (PanelCallbackHandler.__proto__ || Object.getPrototypeOf(PanelCallbackHandler)).apply(this, arguments)); } createClass(PanelCallbackHandler, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.setCanRefine) { this.context.setCanRefine(this.props.canRefine); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.context.setCanRefine && this.props.canRefine !== nextProps.canRefine) { this.context.setCanRefine(nextProps.canRefine); } } }, { key: 'render', value: function render() { return this.props.children; } }]); return PanelCallbackHandler; }(React.Component); PanelCallbackHandler.propTypes = { children: propTypes.node.isRequired, canRefine: propTypes.bool.isRequired }; PanelCallbackHandler.contextTypes = { setCanRefine: propTypes.func }; var classnames = createCommonjsModule(function (module) { /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if ('object' !== 'undefined' && module.exports) { module.exports = classNames; } else if (typeof undefined === 'function' && typeof undefined.amd === 'object' && undefined.amd) { // register as 'classnames', consistent with npm package name undefined('classnames', [], function () { return classNames; }); } else { window.classNames = classNames; } }()); }); var configManagerPropType = propTypes.shape({ register: propTypes.func.isRequired, swap: propTypes.func.isRequired, unregister: propTypes.func.isRequired }); var stateManagerPropType = propTypes.shape({ createURL: propTypes.func.isRequired, setState: propTypes.func.isRequired, getState: propTypes.func.isRequired, unlisten: propTypes.func.isRequired }); var withKeysPropType = function withKeysPropType(keys) { return function (props, propName, componentName) { var prop = props[propName]; if (prop) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var key = _step.value; if (keys.indexOf(key) === -1) { return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.')); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } return undefined; }; }; function translatable(defaultTranslations) { return function (Composed) { function Translatable(props) { var translations = props.translations, otherProps = objectWithoutProperties(props, ['translations']); var translate = function translate(key) { for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } var translation = translations && has_1(translations, key) ? translations[key] : defaultTranslations[key]; if (typeof translation === 'function') { return translation.apply(undefined, params); } return translation; }; return React__default.createElement(Composed, _extends({ translate: translate }, otherProps)); } Translatable.displayName = 'Translatable(' + getDisplayName(Composed) + ')'; Translatable.propTypes = { translations: withKeysPropType(Object.keys(defaultTranslations)) }; return Translatable; }; } var createClassNames = function createClassNames(block) { var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'ais'; return function () { for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) { elements[_key] = arguments[_key]; } var suitElements = elements.filter(function (element) { return element || element === ''; }).map(function (element) { var baseClassName = prefix + '-' + block; return element ? baseClassName + '-' + element : baseClassName; }); return classnames(suitElements); }; }; var cx = createClassNames('CurrentRefinements'); var CurrentRefinements = function CurrentRefinements(_ref) { var items = _ref.items, canRefine = _ref.canRefine, refine = _ref.refine, translate = _ref.translate, className = _ref.className; return React__default.createElement( 'div', { className: classnames(cx('', !canRefine && '-noRefinement'), className) }, React__default.createElement( 'ul', { className: cx('list', !canRefine && 'list--noRefinement') }, items.map(function (item) { return React__default.createElement( 'li', { key: item.label, className: cx('item') }, React__default.createElement( 'span', { className: cx('label') }, item.label ), item.items ? item.items.map(function (nest) { return React__default.createElement( 'span', { key: nest.label, className: cx('category') }, React__default.createElement( 'span', { className: cx('categoryLabel') }, nest.label ), React__default.createElement( 'button', { className: cx('delete'), onClick: function onClick() { return refine(nest.value); } }, translate('clearFilter', nest) ) ); }) : React__default.createElement( 'span', { className: cx('category') }, React__default.createElement( 'button', { className: cx('delete'), onClick: function onClick() { return refine(item.value); } }, translate('clearFilter', item) ) ) ); }) ) ); }; var itemPropTypes = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.func.isRequired, items: function items() { return itemPropTypes.apply(undefined, arguments); } })); CurrentRefinements.propTypes = { items: itemPropTypes.isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }; CurrentRefinements.defaultProps = { className: '' }; var CurrentRefinements$1 = translatable({ clearFilter: '✕' })(CurrentRefinements); /** * The CurrentRefinements widget displays the list of currently applied filters. * * It allows the user to selectively remove them. * @name CurrentRefinements * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-CurrentRefinements - the root div of the widget * @themeKey ais-CurrentRefinements--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-CurrentRefinements-list - the list of all refined items * @themeKey ais-CurrentRefinements-list--noRefinement - the list of all refined items when there is no refinement * @themeKey ais-CurrentRefinements-item - the refined list item * @themeKey ais-CurrentRefinements-button - the button of each refined list item * @themeKey ais-CurrentRefinements-label - the refined list label * @themeKey ais-CurrentRefinements-category - the category of each item * @themeKey ais-CurrentRefinements-categoryLabel - the label of each catgory * @themeKey ais-CurrentRefinements-delete - the delete button of each label * @translationKey clearFilter - the remove filter button label * @example * import React from 'react'; * * import { CurrentRefinements, RefinementList, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CurrentRefinements /> * <RefinementList attribute="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ var CurrentRefinementsWidget = function CurrentRefinementsWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(CurrentRefinements$1, props) ); }; var CurrentRefinements$2 = connectCurrentRefinements(CurrentRefinementsWidget); var getId$1 = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function getCurrentRefinement(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace + '.' + getId$1(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$2(path, props, searchState, context) { var id = props.id, attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement(props, searchState, context); var nextRefinement = void 0; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new algoliasearchHelper_4({ hierarchicalFacets: [{ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }] }); nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0]; } return nextRefinement; } function transformValue(value, props, searchState, context) { return value.map(function (v) { return { label: v.name, value: getValue$2(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue(v.data, props, searchState, context) }; }); } var truncate = function truncate() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return items.slice(0, limit).map(function () { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return Array.isArray(item.items) ? _extends({}, item, { items: truncate(item.items, limit) }) : item; }); }; function _refine(props, searchState, nextRefinement, context) { var id = getId$1(props); var nextValue = defineProperty$2({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace); } function _cleanUp(props, searchState, context) { return cleanUpValue(searchState, context, namespace + '.' + getId$1(props)); } var sortBy = ['name:asc']; /** * connectHierarchicalMenu connector provides the logic to build a widget that will * give the user the ability to explore a tree-like structure. * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * @name connectHierarchicalMenu * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limit and showMoreLimit. * @propType {number} [limit=10] - The maximum number of items displayed. * @propType {number} [showMoreLimit=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items. */ var connectHierarchicalMenu = createConnector({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, separator: propTypes.string, rootPath: propTypes.string, showParentLevel: propTypes.bool, defaultRefinement: propTypes.string, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func }, defaultProps: { showMore: false, limit: 10, showMoreLimit: 20, separator: ' > ', rootPath: null, showParentLevel: true }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var showMore = props.showMore, limit = props.limit, showMoreLimit = props.showMoreLimit; var id = getId$1(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: false }; } var itemsLimit = showMore ? showMoreLimit : limit; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue(value.data, props, searchState, this.context) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, itemsLimit), currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel, showMore = props.showMore, limit = props.limit, showMoreLimit = props.showMoreLimit; var id = getId$1(props); var itemsLimit = showMore ? showMoreLimit : limit; searchParameters = searchParameters.addHierarchicalFacet({ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }).setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, itemsLimit) }); var currentRefinement = getCurrentRefinement(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var rootAttribute = props.attributes[0]; var id = getId$1(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attribute: rootAttribute, value: function value(nextState) { return _refine(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); var cx$1 = createClassNames('SearchBox'); var defaultLoadingIndicator = React__default.createElement( 'svg', { width: '18', height: '18', viewBox: '0 0 38 38', xmlns: 'http://www.w3.org/2000/svg', stroke: '#444', className: cx$1('loadingIcon') }, React__default.createElement( 'g', { fill: 'none', fillRule: 'evenodd' }, React__default.createElement( 'g', { transform: 'translate(1 1)', strokeWidth: '2' }, React__default.createElement('circle', { strokeOpacity: '.5', cx: '18', cy: '18', r: '18' }), React__default.createElement( 'path', { d: 'M36 18c0-9.94-8.06-18-18-18' }, React__default.createElement('animateTransform', { attributeName: 'transform', type: 'rotate', from: '0 18 18', to: '360 18 18', dur: '1s', repeatCount: 'indefinite' }) ) ) ) ); var defaultReset = React__default.createElement( 'svg', { className: cx$1('resetIcon'), xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 20 20', width: '10', height: '10' }, React__default.createElement('path', { d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z' }) ); var defaultSubmit = React__default.createElement( 'svg', { className: cx$1('submitIcon'), xmlns: 'http://www.w3.org/2000/svg', width: '10', height: '10', viewBox: '0 0 40 40' }, React__default.createElement('path', { d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z' }) ); var SearchBox = function (_Component) { inherits(SearchBox, _Component); function SearchBox(props) { classCallCheck(this, SearchBox); var _this = possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this)); _this.getQuery = function () { return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query; }; _this.onInputMount = function (input) { _this.input = input; if (_this.props.__inputRef) { _this.props.__inputRef(input); } }; _this.onKeyDown = function (e) { if (!_this.props.focusShortcuts) { return; } var shortcuts = _this.props.focusShortcuts.map(function (key) { return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key; }); var elt = e.target || e.srcElement; var tagName = elt.tagName; if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') { // already in an input return; } var which = e.which || e.keyCode; if (shortcuts.indexOf(which) === -1) { // not the right shortcut return; } _this.input.focus(); e.stopPropagation(); e.preventDefault(); }; _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); _this.input.blur(); var _this$props = _this.props, refine = _this$props.refine, searchAsYouType = _this$props.searchAsYouType; if (!searchAsYouType) { refine(_this.getQuery()); } return false; }; _this.onChange = function (event) { var _this$props2 = _this.props, searchAsYouType = _this$props2.searchAsYouType, refine = _this$props2.refine, onChange = _this$props2.onChange; var value = event.target.value; if (searchAsYouType) { refine(value); } else { _this.setState({ query: value }); } if (onChange) { onChange(event); } }; _this.onReset = function (event) { var _this$props3 = _this.props, searchAsYouType = _this$props3.searchAsYouType, refine = _this$props3.refine, onReset = _this$props3.onReset; refine(''); _this.input.focus(); if (!searchAsYouType) { _this.setState({ query: '' }); } if (onReset) { onReset(event); } }; _this.state = { query: props.searchAsYouType ? null : props.currentRefinement }; return _this; } createClass(SearchBox, [{ key: 'componentDidMount', value: function componentDidMount() { document.addEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { document.removeEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // Reset query when the searchParameters query has changed. // This is kind of an anti-pattern (props in state), but it works here // since we know for sure that searchParameters having changed means a // new search has been triggered. if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) { this.setState({ query: nextProps.currentRefinement }); } } // From https://github.com/algolia/autocomplete.js/pull/86 }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, className = _props.className, translate = _props.translate, autoFocus = _props.autoFocus, loadingIndicator = _props.loadingIndicator, submit = _props.submit, reset = _props.reset; var query = this.getQuery(); var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) { if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) { return _extends({}, props, defineProperty$2({}, prop, _this2.props[prop])); } return props; }, {}); var isSearchStalled = this.props.showLoadingIndicator && this.props.isSearchStalled; /* eslint-disable max-len */ return React__default.createElement( 'div', { className: classnames(cx$1(''), className) }, React__default.createElement( 'form', { noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset, className: cx$1('form', isSearchStalled && 'form--stalledSearch'), action: '', role: 'search' }, React__default.createElement('input', _extends({ ref: this.onInputMount, type: 'search', placeholder: translate('placeholder'), autoFocus: autoFocus, autoComplete: 'off', autoCorrect: 'off', autoCapitalize: 'off', spellCheck: 'false', required: true, maxLength: '512', value: query, onChange: this.onChange }, searchInputEvents, { className: cx$1('input') })), React__default.createElement( 'button', { type: 'submit', title: translate('submitTitle'), className: cx$1('submit') }, submit ), React__default.createElement( 'button', { type: 'reset', title: translate('resetTitle'), className: cx$1('reset'), onClick: this.onReset, hidden: !query || isSearchStalled }, reset ), this.props.showLoadingIndicator && React__default.createElement( 'span', { hidden: !isSearchStalled, className: cx$1('loadingIndicator') }, loadingIndicator ) ) ); /* eslint-enable */ } }]); return SearchBox; }(React.Component); SearchBox.propTypes = { currentRefinement: propTypes.string, className: propTypes.string, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, loadingIndicator: propTypes.node, reset: propTypes.node, submit: propTypes.node, focusShortcuts: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), autoFocus: propTypes.bool, searchAsYouType: propTypes.bool, onSubmit: propTypes.func, onReset: propTypes.func, onChange: propTypes.func, isSearchStalled: propTypes.bool, showLoadingIndicator: propTypes.bool, // For testing purposes __inputRef: propTypes.func }; SearchBox.defaultProps = { currentRefinement: '', className: '', focusShortcuts: ['s', '/'], autoFocus: false, searchAsYouType: true, showLoadingIndicator: false, isSearchStalled: false, loadingIndicator: defaultLoadingIndicator, reset: defaultReset, submit: defaultSubmit }; var SearchBox$1 = translatable({ resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(SearchBox); var itemsPropType = propTypes.arrayOf(propTypes.shape({ value: propTypes.any, label: propTypes.node.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var List = function (_Component) { inherits(List, _Component); function List() { classCallCheck(this, List); var _this = possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this)); _this.onShowMoreClick = function () { _this.setState(function (state) { return { extended: !state.extended }; }); }; _this.getLimit = function () { var _this$props = _this.props, limit = _this$props.limit, showMoreLimit = _this$props.showMoreLimit; var extended = _this.state.extended; return extended ? showMoreLimit : limit; }; _this.resetQuery = function () { _this.setState({ query: '' }); }; _this.renderItem = function (item, resetQuery) { var items = item.items && React__default.createElement( 'ul', { className: _this.props.cx('list', 'list--child') }, item.items.slice(0, _this.getLimit()).map(function (child) { return _this.renderItem(child, item); }) ); return React__default.createElement( 'li', { key: item.key || item.label, className: _this.props.cx('item', item.isRefined && 'item--selected', item.noRefinement && 'item--noRefinement', items && 'item--parent') }, _this.props.renderItem(item, resetQuery), items ); }; _this.state = { extended: false, query: '' }; return _this; } createClass(List, [{ key: 'renderShowMore', value: function renderShowMore() { var _props = this.props, showMore = _props.showMore, translate = _props.translate, cx = _props.cx; var extended = this.state.extended; var disabled = this.props.limit >= this.props.items.length; if (!showMore) { return null; } return React__default.createElement( 'button', { disabled: disabled, className: cx('showMore', disabled && 'showMore--disabled'), onClick: this.onShowMoreClick }, translate('showMore', extended) ); } }, { key: 'renderSearchBox', value: function renderSearchBox() { var _this2 = this; var _props2 = this.props, cx = _props2.cx, searchForItems = _props2.searchForItems, isFromSearch = _props2.isFromSearch, translate = _props2.translate, items = _props2.items, selectItem = _props2.selectItem; var noResults = items.length === 0 && this.state.query !== '' ? React__default.createElement( 'div', { className: cx('noResults') }, translate('noResults') ) : null; return React__default.createElement( 'div', { className: cx('searchBox') }, React__default.createElement(SearchBox$1, { currentRefinement: this.state.query, refine: function refine(value) { _this2.setState({ query: value }); searchForItems(value); }, focusShortcuts: [], translate: translate, onSubmit: function onSubmit(e) { e.preventDefault(); e.stopPropagation(); if (isFromSearch) { selectItem(items[0], _this2.resetQuery); } } }), noResults ); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props, cx = _props3.cx, items = _props3.items, className = _props3.className, searchable = _props3.searchable, canRefine = _props3.canRefine; var searchBox = searchable ? this.renderSearchBox() : null; var rootClassName = classnames(cx('', !canRefine && '-noRefinement'), className); if (items.length === 0) { return React__default.createElement( 'div', { className: rootClassName }, searchBox ); } // Always limit the number of items we show on screen, since the actual // number of retrieved items might vary with the `maxValuesPerFacet` config // option. return React__default.createElement( 'div', { className: rootClassName }, searchBox, React__default.createElement( 'ul', { className: cx('list', !canRefine && 'list--noRefinement') }, items.slice(0, this.getLimit()).map(function (item) { return _this3.renderItem(item, _this3.resetQuery); }) ), this.renderShowMore() ); } }]); return List; }(React.Component); List.propTypes = { cx: propTypes.func.isRequired, // Only required with showMore. translate: propTypes.func, items: itemsPropType, renderItem: propTypes.func.isRequired, selectItem: propTypes.func, className: propTypes.string, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, show: propTypes.func, searchForItems: propTypes.func, searchable: propTypes.bool, isFromSearch: propTypes.bool, canRefine: propTypes.bool }; List.defaultProps = { className: '', isFromSearch: false }; var Link = function (_Component) { inherits(Link, _Component); function Link() { var _ref; var _temp, _this, _ret; classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) { if (isSpecialClick(e)) { return; } _this.props.onClick(); e.preventDefault(); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(Link, [{ key: 'render', value: function render() { return React__default.createElement('a', _extends({}, omit_1(this.props, 'onClick'), { onClick: this.onClick })); } }]); return Link; }(React.Component); Link.propTypes = { onClick: propTypes.func.isRequired }; var cx$2 = createClassNames('HierarchicalMenu'); var itemsPropType$1 = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string, count: propTypes.number.isRequired, items: function items() { return itemsPropType$1.apply(undefined, arguments); } })); var HierarchicalMenu = function (_Component) { inherits(HierarchicalMenu, _Component); function HierarchicalMenu() { var _ref; var _temp, _this, _ret; classCallCheck(this, HierarchicalMenu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props, createURL = _this$props.createURL, refine = _this$props.refine; return React__default.createElement( Link, { className: cx$2('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, React__default.createElement( 'span', { className: cx$2('label') }, item.label ), ' ', React__default.createElement( 'span', { className: cx$2('count') }, item.count ) ); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(HierarchicalMenu, [{ key: 'render', value: function render() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, cx: cx$2 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isEmpty', 'canRefine', 'className']))); } }]); return HierarchicalMenu; }(React.Component); HierarchicalMenu.propTypes = { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired, items: itemsPropType$1, showMore: propTypes.bool, className: propTypes.string, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func }; HierarchicalMenu.defaultProps = { className: '' }; var HierarchicalMenu$1 = translatable({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; } })(HierarchicalMenu); /** * The hierarchical menu lets the user browse attributes using a tree-like structure. * * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * * @name HierarchicalMenu * @kind widget * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * [{ * "objectID": "321432", * "name": "lemon", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }, * { * "objectID": "8976987", * "name": "orange", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }] * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "objectID": "321432", * "name": "lemon", * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limit and showMoreLimit. * @propType {number} [limit=10] - The maximum number of items displayed. * @propType {number} [showMoreLimit=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HierarchicalMenu - the root div of the widget * @themeKey ais-HierarchicalMenu-noRefinement - the root div of the widget when there is no refinement * @themeKey ais-HierarchicalMenu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-HierarchicalMenu-list - the list of menu items * @themeKey ais-HierarchicalMenu-list--child - the child list of menu items * @themeKey ais-HierarchicalMenu-item - the menu list item * @themeKey ais-HierarchicalMenu-item--selected - the selected menu list item * @themeKey ais-HierarchicalMenu-item--parent - the menu list item containing children * @themeKey ais-HierarchicalMenu-link - the clickable menu element * @themeKey ais-HierarchicalMenu-label - the label of each item * @themeKey ais-HierarchicalMenu-count - the count of values for each item * @themeKey ais-HierarchicalMenu-showMore - the button used to display more categories * @themeKey ais-HierarchicalMenu-showMore--disabled - the disabled button used to display more categories * @translationKey showMore - The label of the show more button. Accepts one parameter, a boolean that is true if the values are expanded * @example * import React from 'react'; * import { HierarchicalMenu, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HierarchicalMenu * attributes={[ * 'category', * 'sub_category', * 'sub_sub_category', * ]} * /> * </InstantSearch> * ); * } */ var HierarchicalMenuWidget = function HierarchicalMenuWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(HierarchicalMenu$1, props) ); }; var HierarchicalMenu$2 = connectHierarchicalMenu(HierarchicalMenuWidget); /** * Find an highlighted attribute given an `attribute` and an `highlightProperty`, parses it, * and provided an array of objects with the string value and a boolean if this * value is highlighted. * * In order to use this feature, highlight must be activated in the configuration of * the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and * highligtPostTag in Algolia configuration. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightProperty - the property that contains the highlight structure in the results * @param {string} attribute - the highlighted attribute to look for * @param {object} hit - the actual hit returned by Algolia. * @return {object[]} - An array of {value: string, isHighlighted: boolean}. */ function parseAlgoliaHit(_ref) { var _ref$preTag = _ref.preTag, preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag, _ref$postTag = _ref.postTag, postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag, highlightProperty = _ref.highlightProperty, attribute = _ref.attribute, hit = _ref.hit; if (!hit) throw new Error('`hit`, the matching record, must be provided'); var highlightObject = get_1(hit[highlightProperty], attribute, {}); if (Array.isArray(highlightObject)) { return highlightObject.map(function (item) { return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: item.value }); }); } return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightObject.value }); } /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseHighlightedAttribute(_ref2) { var preTag = _ref2.preTag, postTag = _ref2.postTag, _ref2$highlightedValu = _ref2.highlightedValue, highlightedValue = _ref2$highlightedValu === undefined ? '' : _ref2$highlightedValu; var splitByPreTag = highlightedValue.split(preTag); var firstValue = splitByPreTag.shift(); var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }]; if (postTag === preTag) { var isHighlighted = true; splitByPreTag.forEach(function (split) { elements.push({ value: split, isHighlighted: isHighlighted }); isHighlighted = !isHighlighted; }); } else { splitByPreTag.forEach(function (split) { var splitByPostTag = split.split(postTag); elements.push({ value: splitByPostTag[0], isHighlighted: true }); if (splitByPostTag[1] !== '') { elements.push({ value: splitByPostTag[1], isHighlighted: false }); } }); } return elements; } var highlight = function highlight(_ref) { var attribute = _ref.attribute, hit = _ref.hit, highlightProperty = _ref.highlightProperty; return parseAlgoliaHit({ attribute: attribute, hit: hit, preTag: highlightTags.highlightPreTag, postTag: highlightTags.highlightPostTag, highlightProperty: highlightProperty }); }; /** * connectHighlight connector provides the logic to create an highlighter * component that will retrieve, parse and render an highlighted attribute * from an Algolia hit. * @name connectHighlight * @kind connector * @category connector * @providedPropType {function} highlight - function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: `highlightProperty` which is the property that contains the highlight structure from the records, `attribute` which is the name of the attribute (it can be either a string or an array of strings) to look for and `hit` which is the hit from Algolia. It returns an array of objects `{value: string, isHighlighted: boolean}`. If the element that corresponds to the attribute is an array of strings, it will return a nested array of objects. * @example * import React from 'react'; * import { connectHighlight } from 'react-instantsearch/connectors'; * import { InstantSearch, Hits } from 'react-instantsearch/dom'; * * const CustomHighlight = connectHighlight( * ({ highlight, attribute, hit, highlightProperty }) => { * const parsedHit = highlight({ attribute, hit, highlightProperty: '_highlightResult' }); * const highlightedHits = parsedHit.map(part => { * if (part.isHighlighted) return <mark>{part.value}</mark>; * return part.value; * }); * return <div>{highlightedHits}</div>; * } * ); * * const Hit = ({hit}) => * <p> * <CustomHighlight attribute="description" hit={hit} /> * </p>; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea"> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); * } */ var connectHighlight = createConnector({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); function generateKey(i, value) { return 'split-' + i + '-' + value; } var Highlight = function Highlight(_ref) { var cx = _ref.cx, value = _ref.value, highlightedTagName = _ref.highlightedTagName, isHighlighted = _ref.isHighlighted, nonHighlightedTagName = _ref.nonHighlightedTagName; var TagName = isHighlighted ? highlightedTagName : nonHighlightedTagName; var className = isHighlighted ? 'highlighted' : 'nonHighlighted'; return React__default.createElement( TagName, { className: cx(className) }, value ); }; Highlight.propTypes = { cx: propTypes.func.isRequired, value: propTypes.string.isRequired, isHighlighted: propTypes.bool.isRequired, highlightedTagName: propTypes.string.isRequired, nonHighlightedTagName: propTypes.string.isRequired }; var Highlighter = function Highlighter(_ref2) { var cx = _ref2.cx, hit = _ref2.hit, attribute = _ref2.attribute, highlight = _ref2.highlight, highlightProperty = _ref2.highlightProperty, tagName = _ref2.tagName, nonHighlightedTagName = _ref2.nonHighlightedTagName, separator = _ref2.separator, className = _ref2.className; var parsedHighlightedValue = highlight({ hit: hit, attribute: attribute, highlightProperty: highlightProperty }); return React__default.createElement( 'span', { className: classnames(cx(''), className) }, parsedHighlightedValue.map(function (item, i) { if (Array.isArray(item)) { var isLast = i === parsedHighlightedValue.length - 1; return React__default.createElement( 'span', { key: generateKey(i, hit[attribute][i]) }, item.map(function (element, index) { return React__default.createElement(Highlight, { cx: cx, key: generateKey(index, element.value), value: element.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: element.isHighlighted }); }), !isLast && React__default.createElement( 'span', { className: cx('separator') }, separator ) ); } return React__default.createElement(Highlight, { cx: cx, key: generateKey(i, item.value), value: item.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: item.isHighlighted }); }) ); }; Highlighter.propTypes = { cx: propTypes.func.isRequired, hit: propTypes.object.isRequired, attribute: propTypes.string.isRequired, highlight: propTypes.func.isRequired, highlightProperty: propTypes.string.isRequired, tagName: propTypes.string, nonHighlightedTagName: propTypes.string, className: propTypes.string, separator: propTypes.node }; Highlighter.defaultProps = { tagName: 'em', nonHighlightedTagName: 'span', className: '', separator: ', ' }; var cx$3 = createClassNames('Highlight'); var Highlight$1 = function Highlight$$1(props) { return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: '_highlightResult', cx: cx$3 })); }; /** * Renders any attribute from a hit into its highlighted form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Highlight * @kind widget * @propType {string} attribute - location of the highlighted attribute in the hit (the corresponding element can be either a string or an array of strings) * @propType {object} hit - hit object containing the highlighted attribute * @propType {string} [tagName='em'] - tag to be used for highlighted parts of the hit * @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted * @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings. * @themeKey ais-Highlight - root of the component * @themeKey ais-Highlight-highlighted - part of the text which is highlighted * @themeKey ais-Highlight-nonHighlighted - part of the text that is not highlighted * @example * import React from 'react'; * * import { connectHits, Highlight, InstantSearch } from 'react-instantsearch/dom'; * * const CustomHits = connectHits(({ hits }) => * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attribute="description" hit={hit} /> * </p> * )} * </div> * ); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ var Highlight$3 = connectHighlight(Highlight$1); var cx$4 = createClassNames('Snippet'); var Snippet = function Snippet(props) { return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: '_snippetResult', cx: cx$4 })); }; /** * Renders any attribute from an hit into its highlighted snippet form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Snippet * @kind widget * @requirements To use this widget, the attribute name passed to the `attribute` prop must be * present in "Attributes to snippet" on the Algolia dashboard or configured as `attributesToSnippet` * via a set settings call to the Algolia API. * @propType {string} attribute - location of the highlighted snippet attribute in the hit (the corresponding element can be either a string or an array of strings) * @propType {object} hit - hit object containing the highlighted snippet attribute * @propType {string} [tagName='em'] - tag to be used for highlighted parts of the attribute * @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted * @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings. * @themeKey ais-Snippet - the root span of the widget * @themeKey ais-Snippet-highlighted - the highlighted text * @themeKey ais-Snippet-nonHighlighted - the normal text * @example * import React from 'react'; * import { Snippet, InstantSearch, Hits } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Hits * hitComponent={({ hit }) => ( * <p key={hit.objectID}> * <Snippet attribute="description" hit={hit} /> * </p> * )} * /> * </InstantSearch> * ); * } */ var Snippet$2 = connectHighlight(Snippet); /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * * **Warning:** you will need to use the **objectID** property available on every hit as a key * when iterating over them. This will ensure you have the best possible UI experience * especially on slow networks. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @example * import React from 'react'; * * import { Highlight, InstantSearch } from 'react-instantsearch/dom'; * import { connectHits } from 'react-instantsearch/connectors'; * const CustomHits = connectHits(({ hits }) => * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attribute="description" hit={hit} /> * </p> * )} * </div> * ); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ var connectHits = createConnector({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); var hits = results ? results.hits : []; return { hits: hits }; }, /* Hits needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); var cx$5 = createClassNames('Hits'); var Hits = function Hits(_ref) { var hits = _ref.hits, className = _ref.className, HitComponent = _ref.hitComponent; return ( // Spread the hit on HitComponent instead of passing the full object. BC. // ex: <HitComponent {...hit} key={hit.objectID} /> React__default.createElement( 'div', { className: classnames(cx$5(''), className) }, React__default.createElement( 'ul', { className: cx$5('list') }, hits.map(function (hit) { return React__default.createElement( 'li', { className: cx$5('item'), key: hit.objectID }, React__default.createElement(HitComponent, { hit: hit }) ); }) ) ) ); }; Hits.propTypes = { hits: propTypes.arrayOf(propTypes.object).isRequired, className: propTypes.string, hitComponent: propTypes.func }; Hits.defaultProps = { className: '', hitComponent: function hitComponent(props) { return React__default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px', wordBreak: 'break-all' } }, JSON.stringify(props).slice(0, 100), '...' ); } }; /** * Displays a list of hits. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name Hits * @kind widget * @propType {Component} [hitComponent] - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey ais-Hits - the root div of the widget * @themeKey ais-Hits-list - the list of results * @themeKey ais-Hits-item - the hit list item * @example * import React from 'react'; * import { Hits, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Hits /> * </InstantSearch> * ); * } */ var Hits$2 = connectHits(Hits); function getId$2() { return 'hitsPerPage'; } function getCurrentRefinement$1(props, searchState, context) { var id = getId$2(); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * connectHitsPerPage connector provides the logic to create connected * components that will allow a user to choose to display more or less results from Algolia. * @name connectHitsPerPage * @kind connector * @propType {number} defaultRefinement - The number of items selected by default * @propType {{value: number, label: string}[]} items - List of hits per page options. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectHitsPerPage = createConnector({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: propTypes.number.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.number.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$1(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$2(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$2()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$1(props, searchState, this.context)); }, getMetadata: function getMetadata() { return { id: getId$2() }; } }); var Select = function (_Component) { inherits(Select, _Component); function Select() { var _ref; var _temp, _this, _ret; classCallCheck(this, Select); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.onSelect(e.target.value); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(Select, [{ key: 'render', value: function render() { var _props = this.props, cx = _props.cx, items = _props.items, selectedItem = _props.selectedItem; return React__default.createElement( 'select', { className: cx('select'), value: selectedItem, onChange: this.onChange }, items.map(function (item) { return React__default.createElement( 'option', { className: cx('option'), key: has_1(item, 'key') ? item.key : item.value, disabled: item.disabled, value: item.value }, has_1(item, 'label') ? item.label : item.value ); }) ); } }]); return Select; }(React.Component); Select.propTypes = { cx: propTypes.func.isRequired, onSelect: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ value: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired, key: propTypes.oneOfType([propTypes.string, propTypes.number]), label: propTypes.string, disabled: propTypes.bool })).isRequired, selectedItem: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired }; var cx$6 = createClassNames('HitsPerPage'); var HitsPerPage = function (_Component) { inherits(HitsPerPage, _Component); function HitsPerPage() { classCallCheck(this, HitsPerPage); return possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments)); } createClass(HitsPerPage, [{ key: 'render', value: function render() { var _props = this.props, items = _props.items, currentRefinement = _props.currentRefinement, refine = _props.refine, className = _props.className; return React__default.createElement( 'div', { className: classnames(cx$6(''), className) }, React__default.createElement(Select, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx$6 }) ); } }]); return HitsPerPage; }(React.Component); HitsPerPage.propTypes = { items: propTypes.arrayOf(propTypes.shape({ value: propTypes.number.isRequired, label: propTypes.string })).isRequired, currentRefinement: propTypes.number.isRequired, refine: propTypes.func.isRequired, className: propTypes.string }; HitsPerPage.defaultProps = { className: '' }; /** * The HitsPerPage widget displays a dropdown menu to let the user change the number * of displayed hits. * * If you only want to configure the number of hits per page without * displaying a widget, you should use the `<Configure hitsPerPage={20} />` widget. See [`<Configure />` documentation](widgets/Configure.html) * * @name HitsPerPage * @kind widget * @propType {{value: number, label: string}[]} items - List of available options. * @propType {number} defaultRefinement - The number of items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HitsPerPage - the root div of the widget * @themeKey ais-HitsPerPage-select - the select * @themeKey ais-HitsPerPage-option - the select option * @example * import React from 'react'; * import { HitsPerPage, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HitsPerPage * defaultRefinement={20} * items={[{value: 20, label: 'Show 20 hits'}, {value: 50, label: 'Show 50 hits'}]} * /> * </InstantSearch> * ); * } */ var HitsPerPage$2 = connectHitsPerPage(HitsPerPage); function getId$3() { return 'page'; } function getCurrentRefinement$2(props, searchState, context) { var id = getId$3(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { currentRefinement = parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * InfiniteHits connector provides the logic to create connected * components that will render an continuous list of results retrieved from * Algolia. This connector provides a function to load more results. * @name connectInfiniteHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @providedPropType {boolean} hasMore - indicates if there are more pages to load * @providedPropType {function} refine - call to load more results */ var connectInfiniteHits = createConnector({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { this._allResults = []; return { hits: this._allResults, hasMore: false }; } var hits = results.hits, page = results.page, nbPages = results.nbPages; // If it is the same page we do not touch the page result list if (page === 0) { this._allResults = hits; } else if (page > this.previousPage) { this._allResults = [].concat(toConsumableArray(this._allResults), toConsumableArray(hits)); } else if (page < this.previousPage) { this._allResults = hits; } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; this.previousPage = page; return { hits: this._allResults, hasMore: hasMore }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement$2(props, searchState, this.context) - 1 }); }, refine: function refine(props, searchState) { var id = getId$3(); var nextPage = getCurrentRefinement$2(props, searchState, this.context) + 1; var nextValue = defineProperty$2({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, this.context, resetPage); } }); var cx$7 = createClassNames('InfiniteHits'); var InfiniteHits = function (_Component) { inherits(InfiniteHits, _Component); function InfiniteHits() { classCallCheck(this, InfiniteHits); return possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments)); } createClass(InfiniteHits, [{ key: 'render', value: function render() { var _props = this.props, HitComponent = _props.hitComponent, hits = _props.hits, hasMore = _props.hasMore, refine = _props.refine, translate = _props.translate, className = _props.className; return React__default.createElement( 'div', { className: classnames(cx$7(''), className) }, React__default.createElement( 'ul', { className: cx$7('list') }, hits.map(function (hit) { return React__default.createElement( 'li', { key: hit.objectID, className: cx$7('item') }, React__default.createElement(HitComponent, { hit: hit }) ); }) ), React__default.createElement( 'button', { className: cx$7('loadMore', !hasMore && 'loadMore--disabled'), onClick: function onClick() { return refine(); }, disabled: !hasMore }, translate('loadMore') ) ); } }]); return InfiniteHits; }(React.Component); InfiniteHits.propTypes = { hits: propTypes.arrayOf(propTypes.object).isRequired, hasMore: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string, hitComponent: propTypes.oneOfType([propTypes.string, propTypes.func]) }; InfiniteHits.defaultProps = { className: '', hitComponent: function hitComponent(hit) { return React__default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px', wordBreak: 'break-all' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; var InfiniteHits$1 = translatable({ loadMore: 'Load more' })(InfiniteHits); /** * Displays an infinite list of hits along with a **load more** button. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name InfiniteHits * @kind widget * @propType {Component} [hitComponent] - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey ais-InfiniteHits - the root div of the widget * @themeKey ais-InfiniteHits-list - the list of hits * @themeKey ais-InfiniteHits-item - the hit list item * @themeKey ais-InfiniteHits-loadMore - the button used to display more results * @themeKey ais-InfiniteHits-loadMore--disabled - the disabled button used to display more results * @translationKey loadMore - the label of load more button * @example * import React from 'react'; * import { InfiniteHits, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <InfiniteHits /> * </InstantSearch> * ); * } */ var InfiniteHits$2 = connectInfiniteHits(InfiniteHits$1); var namespace$1 = 'menu'; function getId$4(props) { return props.attribute; } function getCurrentRefinement$3(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$1 + '.' + getId$4(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$3(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$3(props, searchState, context); return name === currentRefinement ? '' : name; } function getLimit(_ref) { var showMore = _ref.showMore, limit = _ref.limit, showMoreLimit = _ref.showMoreLimit; return showMore ? showMoreLimit : limit; } function _refine$1(props, searchState, nextRefinement, context) { var id = getId$4(props); var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$1); } function _cleanUp$1(props, searchState, context) { return cleanUpValue(searchState, context, namespace$1 + '.' + getId$4(props)); } var sortBy$1 = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user the ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of diplayed items * @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [searchable=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var connectMenu = createConnector({ displayName: 'AlgoliaMenu', propTypes: { attribute: propTypes.string.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.string, transformItems: propTypes.func, searchable: propTypes.bool }, defaultProps: { showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$3(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$3(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$1 }).map(function (v) { return { label: v.name, value: getValue$3(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = searchable && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, getLimit(props)), currentRefinement: getCurrentRefinement$3(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props)) }); searchParameters = searchParameters.addDisjunctiveFacet(attribute); var currentRefinement = getCurrentRefinement$3(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this2 = this; var id = getId$4(props); var currentRefinement = getCurrentRefinement$3(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: props.attribute + ': ' + currentRefinement, attribute: props.attribute, value: function value(nextState) { return _refine$1(props, nextState, '', _this2.context); }, currentRefinement: currentRefinement }] }; } }); var cx$8 = createClassNames('Menu'); var Menu = function (_Component) { inherits(Menu, _Component); function Menu() { var _ref; var _temp, _this, _ret; classCallCheck(this, Menu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item, resetQuery) { var createURL = _this.props.createURL; var label = _this.props.isFromSearch ? React__default.createElement(Highlight$3, { attribute: 'label', hit: item }) : item.label; return React__default.createElement( Link, { className: cx$8('link'), onClick: function onClick() { return _this.selectItem(item, resetQuery); }, href: createURL(item.value) }, React__default.createElement( 'span', { className: cx$8('label') }, label ), ' ', React__default.createElement( 'span', { className: cx$8('count') }, item.count ) ); }, _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(Menu, [{ key: 'render', value: function render() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$8 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isFromSearch', 'searchForItems', 'searchable', 'canRefine', 'className']))); } }]); return Menu; }(React.Component); Menu.propTypes = { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, searchForItems: propTypes.func.isRequired, searchable: propTypes.bool, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired, count: propTypes.number.isRequired, isRefined: propTypes.bool.isRequired })), isFromSearch: propTypes.bool.isRequired, canRefine: propTypes.bool.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func, className: propTypes.string }; Menu.defaultProps = { className: '' }; var Menu$1 = translatable({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(Menu); /** * The Menu component displays a menu that lets the user choose a single value for a specific attribute. * @name Menu * @kind widget * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * If you are using the `searchable` prop, you'll also need to make the attribute searchable using * the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values). * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of diplayed items * @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/). * @themeKey ais-Menu - the root div of the widget * @themeKey ais-Menu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-Menu-list - the list of all menu items * @themeKey ais-Menu-item - the menu list item * @themeKey ais-Menu-item--selected - the selected menu list item * @themeKey ais-Menu-link - the clickable menu element * @themeKey ais-Menu-label - the label of each item * @themeKey ais-Menu-count - the count of values for each item * @themeKey ais-Menu-noResults - the div displayed when there are no results * @themeKey ais-Menu-showMore - the button used to display more categories * @themeKey ais-Menu-showMore--disabled - the disabled button used to display more categories * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @example * import React from 'react'; * * import { Menu, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Menu attribute="category" /> * </InstantSearch> * ); * } */ var MenuWidget = function MenuWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(Menu$1, props) ); }; var Menu$2 = connectMenu(MenuWidget); var cx$9 = createClassNames('MenuSelect'); var MenuSelect = function (_Component) { inherits(MenuSelect, _Component); function MenuSelect() { var _ref; var _temp, _this, _ret; classCallCheck(this, MenuSelect); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = MenuSelect.__proto__ || Object.getPrototypeOf(MenuSelect)).call.apply(_ref, [this].concat(args))), _this), _this.handleSelectChange = function (_ref2) { var value = _ref2.target.value; _this.props.refine(value === 'ais__see__all__option' ? '' : value); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(MenuSelect, [{ key: 'render', value: function render() { var _props = this.props, items = _props.items, canRefine = _props.canRefine, translate = _props.translate, className = _props.className; return React__default.createElement( 'div', { className: classnames(cx$9('', !canRefine && '-noRefinement'), className) }, React__default.createElement( 'select', { value: this.selectedValue, onChange: this.handleSelectChange, className: cx$9('select') }, React__default.createElement( 'option', { value: 'ais__see__all__option', className: cx$9('option') }, translate('seeAllOption') ), items.map(function (item) { return React__default.createElement( 'option', { key: item.value, value: item.value, className: cx$9('option') }, item.label, ' (', item.count, ')' ); }) ) ); } }, { key: 'selectedValue', get: function get() { var _ref3 = find_1(this.props.items, { isRefined: true }) || { value: 'ais__see__all__option' }, value = _ref3.value; return value; } }]); return MenuSelect; }(React.Component); MenuSelect.propTypes = { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired, count: propTypes.oneOfType([propTypes.number.isRequired, propTypes.string.isRequired]), isRefined: propTypes.bool.isRequired })).isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }; MenuSelect.defaultProps = { className: '' }; var MenuSelect$1 = translatable({ seeAllOption: 'See all' })(MenuSelect); /** * The MenuSelect component displays a select that lets the user choose a single value for a specific attribute. * @name MenuSelect * @kind widget * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attribute - the name of the attribute in the record * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-MenuSelect - the root div of the widget * @themeKey ais-MenuSelect-noRefinement - the root div of the widget when there is no refinement * @themeKey ais-MenuSelect-select - the `<select>` * @themeKey ais-MenuSelect-option - the select `<option>` * @translationkey seeAllOption - The label of the option to select to remove the refinement * @example * import React from 'react'; * * import { MenuSelect, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <MenuSelect attribute="category" /> * </InstantSearch> * ); * } */ var MenuSelectWidget = function MenuSelectWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(MenuSelect$1, props) ); }; var MenuSelect$2 = connectMenu(MenuSelectWidget); function stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return (item.start ? item.start : '') + ':' + (item.end ? item.end : ''); } function parseItem(value) { if (value.length === 0) { return { start: null, end: null }; } var _value$split = value.split(':'), _value$split2 = slicedToArray(_value$split, 2), startStr = _value$split2[0], endStr = _value$split2[1]; return { start: startStr.length > 0 ? parseInt(startStr, 10) : null, end: endStr.length > 0 ? parseInt(endStr, 10) : null }; } var namespace$2 = 'multiRange'; function getId$5(props) { return props.attribute; } function getCurrentRefinement$4(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$2 + '.' + getId$5(props), '', function (currentRefinement) { if (currentRefinement === '') { return ''; } return currentRefinement; }); } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attribute, results, value) { var stats = results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } function _refine$2(props, searchState, nextRefinement, context) { var nextValue = defineProperty$2({}, getId$5(props, searchState), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$2); } function _cleanUp$2(props, searchState, context) { return cleanUpValue(searchState, context, namespace$2 + '.' + getId$5(props)); } /** * connectNumericMenu connector provides the logic to build a widget that will * give the user the ability to select a range value for a numeric attribute. * Ranges are defined statically. * @name connectNumericMenu * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @kind connector * @propType {string} attribute - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string. * @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the NumericMenu can display. */ var connectNumericMenu = createConnector({ displayName: 'AlgoliaNumericMenu', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node, start: propTypes.number, end: propTypes.number })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute; var currentRefinement = getCurrentRefinement$4(props, searchState, this.context); var results = getResults(searchResults, this.context); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: results ? itemHasRefinement(getId$5(props), results, value) : false }; }); var stats = results && results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var refinedItem = find_1(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: isEmpty_1(refinedItem), noRefinement: !stats, label: 'All' }); } return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement, canRefine: items.length > 0 && items.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$2(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; var _parseItem = parseItem(getCurrentRefinement$4(props, searchState, this.context)), start = _parseItem.start, end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attribute); if (start) { searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$5(props); var value = getCurrentRefinement$4(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (value !== '') { var _find2 = find_1(props.items, function (item) { return stringifyItem(item) === value; }), label = _find2.label; items.push({ label: props.attribute + ': ' + label, attribute: props.attribute, currentRefinement: label, value: function value(nextState) { return _refine$2(props, nextState, '', _this.context); } }); } return { id: id, index: index, items: items }; } }); var cx$10 = createClassNames('NumericMenu'); var NumericMenu = function (_Component) { inherits(NumericMenu, _Component); function NumericMenu() { var _ref; var _temp, _this, _ret; classCallCheck(this, NumericMenu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = NumericMenu.__proto__ || Object.getPrototypeOf(NumericMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props, refine = _this$props.refine, translate = _this$props.translate; return React__default.createElement( 'label', { className: cx$10('label') }, React__default.createElement('input', { className: cx$10('radio'), type: 'radio', checked: item.isRefined, disabled: item.noRefinement, onChange: function onChange() { return refine(item.value); } }), React__default.createElement( 'span', { className: cx$10('labelText') }, item.value === '' ? translate('all') : item.label ) ); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(NumericMenu, [{ key: 'render', value: function render() { var _props = this.props, items = _props.items, canRefine = _props.canRefine, className = _props.className; return React__default.createElement(List, { renderItem: this.renderItem, showMore: false, canRefine: canRefine, cx: cx$10, items: items.map(function (item) { return _extends({}, item, { key: item.value }); }), className: className }); } }]); return NumericMenu; }(React.Component); NumericMenu.propTypes = { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node.isRequired, value: propTypes.string.isRequired, isRefined: propTypes.bool.isRequired, noRefinement: propTypes.bool.isRequired })).isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }; NumericMenu.defaultProps = { className: '' }; var NumericMenu$1 = translatable({ all: 'All' })(NumericMenu); /** * NumericMenu is a widget used for selecting the range value of a numeric attribute. * @name NumericMenu * @kind widget * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @propType {string} attribute - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the format "min:max". * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-NumericMenu - the root div of the widget * @themeKey ais-NumericMenu--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-NumericMenu-list - the list of all refinement items * @themeKey ais-NumericMenu-item - the refinement list item * @themeKey ais-NumericMenu-item--selected - the selected refinement list item * @themeKey ais-NumericMenu-label - the label of each refinement item * @themeKey ais-NumericMenu-radio - the radio input of each refinement item * @themeKey ais-NumericMenu-labelText - the label text of each refinement item * @translationkey all - The label of the largest range added automatically by react instantsearch * @example * import React from 'react'; * * import { NumericMenu, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <NumericMenu * attribute="price" * items={[ * { end: 10, label: '<$10' }, * { start: 10, end: 100, label: '$10-$100' }, * { start: 100, end: 500, label: '$100-$500' }, * { start: 500, label: '>$500' }, * ]} * /> * </InstantSearch> * ); * } */ var NumericMenuWidget = function NumericMenuWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(NumericMenu$1, props) ); }; var NumericMenu$2 = connectNumericMenu(NumericMenuWidget); function getId$6() { return 'page'; } function getCurrentRefinement$5(props, searchState, context) { var id = getId$6(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } function _refine$3(props, searchState, nextPage, context) { var id = getId$6(); var nextValue = defineProperty$2({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, context, resetPage); } /** * connectPagination connector provides the logic to build a widget that will * let the user displays hits corresponding to a certain page. * @name connectPagination * @kind connector * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [padding=3] - How many page links to display around the current page. * @propType {number} [totalPages=Infinity] - Maximum number of pages to display. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {number} nbPages - the total of existing pages * @providedPropType {number} currentRefinement - the page refinement currently applied */ var connectPagination = createConnector({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$5(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$3(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$6()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$5(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId$6() }; } }); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil; var nativeMax$7 = Math.max; /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax$7(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } var _baseRange = baseRange; /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && _isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite_1(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite_1(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite_1(step); return _baseRange(start, end, step, fromRight); }; } var _createRange = createRange; /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = _createRange(); var range_1 = range; var LinkList = function (_Component) { inherits(LinkList, _Component); function LinkList() { classCallCheck(this, LinkList); return possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments)); } createClass(LinkList, [{ key: 'render', value: function render() { var _props = this.props, cx = _props.cx, createURL = _props.createURL, items = _props.items, onSelect = _props.onSelect, canRefine = _props.canRefine; return React__default.createElement( 'ul', { className: cx('list', !canRefine && 'list--noRefinement') }, items.map(function (item) { return React__default.createElement( 'li', { key: has_1(item, 'key') ? item.key : item.value, className: cx('item', item.selected && !item.disabled && 'item--selected', item.disabled && 'item--disabled', item.modifier) }, item.disabled ? React__default.createElement( 'span', { className: cx('link') }, has_1(item, 'label') ? item.label : item.value ) : React__default.createElement( Link, { className: cx('link', item.selected && 'link--selected'), 'aria-label': item.ariaLabel, href: createURL(item.value), onClick: function onClick() { return onSelect(item.value); } }, has_1(item, 'label') ? item.label : item.value ) ); }) ); } }]); return LinkList; }(React.Component); LinkList.propTypes = { cx: propTypes.func.isRequired, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ value: propTypes.oneOfType([propTypes.string, propTypes.number, propTypes.object]).isRequired, key: propTypes.oneOfType([propTypes.string, propTypes.number]), label: propTypes.node, modifier: propTypes.string, ariaLabel: propTypes.string, disabled: propTypes.bool })), onSelect: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired }; var cx$11 = createClassNames('Pagination'); // Determines the size of the widget (the number of pages displayed - that the user can directly click on) function calculateSize(padding, maxPages) { return Math.min(2 * padding + 1, maxPages); } function calculatePaddingLeft(currentPage, padding, maxPages, size) { if (currentPage <= padding) { return currentPage; } if (currentPage >= maxPages - padding) { return size - (maxPages - currentPage); } return padding + 1; } // Retrieve the correct page range to populate the widget function getPages(currentPage, maxPages, padding) { var size = calculateSize(padding, maxPages); // If the widget size is equal to the max number of pages, return the entire page range if (size === maxPages) return range_1(1, maxPages + 1); var paddingLeft = calculatePaddingLeft(currentPage, padding, maxPages, size); var paddingRight = size - paddingLeft; var first = currentPage - paddingLeft; var last = currentPage + paddingRight; return range_1(first + 1, last + 1); } var Pagination = function (_Component) { inherits(Pagination, _Component); function Pagination() { classCallCheck(this, Pagination); return possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments)); } createClass(Pagination, [{ key: 'getItem', value: function getItem(modifier, translationKey, value) { var _props = this.props, nbPages = _props.nbPages, totalPages = _props.totalPages, translate = _props.translate; return { key: modifier + '.' + value, modifier: modifier, disabled: value < 1 || value >= Math.min(totalPages, nbPages), label: translate(translationKey, value), value: value, ariaLabel: translate('aria' + capitalize(translationKey), value) }; } }, { key: 'render', value: function render() { var _props2 = this.props, ListComponent = _props2.listComponent, nbPages = _props2.nbPages, totalPages = _props2.totalPages, currentRefinement = _props2.currentRefinement, padding = _props2.padding, showFirst = _props2.showFirst, showPrevious = _props2.showPrevious, showNext = _props2.showNext, showLast = _props2.showLast, refine = _props2.refine, createURL = _props2.createURL, canRefine = _props2.canRefine, translate = _props2.translate, className = _props2.className, otherProps = objectWithoutProperties(_props2, ['listComponent', 'nbPages', 'totalPages', 'currentRefinement', 'padding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'canRefine', 'translate', 'className']); var maxPages = Math.min(nbPages, totalPages); var lastPage = maxPages; var items = []; if (showFirst) { items.push({ key: 'first', modifier: 'item--firstPage', disabled: currentRefinement === 1, label: translate('first'), value: 1, ariaLabel: translate('ariaFirst') }); } if (showPrevious) { items.push({ key: 'previous', modifier: 'item--previousPage', disabled: currentRefinement === 1, label: translate('previous'), value: currentRefinement - 1, ariaLabel: translate('ariaPrevious') }); } items = items.concat(getPages(currentRefinement, maxPages, padding).map(function (value) { return { key: value, modifier: 'item--page', label: translate('page', value), value: value, selected: value === currentRefinement, ariaLabel: translate('ariaPage', value) }; })); if (showNext) { items.push({ key: 'next', modifier: 'item--nextPage', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('next'), value: currentRefinement + 1, ariaLabel: translate('ariaNext') }); } if (showLast) { items.push({ key: 'last', modifier: 'item--lastPage', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('last'), value: lastPage, ariaLabel: translate('ariaLast') }); } return React__default.createElement( 'div', { className: classnames(cx$11('', !canRefine && '-noRefinement'), className) }, React__default.createElement(ListComponent, _extends({}, otherProps, { cx: cx$11, items: items, onSelect: refine, createURL: createURL, canRefine: canRefine })) ); } }]); return Pagination; }(React.Component); Pagination.propTypes = { nbPages: propTypes.number.isRequired, currentRefinement: propTypes.number.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired, translate: propTypes.func.isRequired, listComponent: propTypes.func, showFirst: propTypes.bool, showPrevious: propTypes.bool, showNext: propTypes.bool, showLast: propTypes.bool, padding: propTypes.number, totalPages: propTypes.number, className: propTypes.string }; Pagination.defaultProps = { listComponent: LinkList, showFirst: true, showPrevious: true, showNext: true, showLast: false, padding: 3, totalPages: Infinity, className: '' }; var Pagination$1 = translatable({ previous: '‹', next: '›', first: '«', last: '»', page: function page(currentRefinement) { return currentRefinement.toString(); }, ariaPrevious: 'Previous page', ariaNext: 'Next page', ariaFirst: 'First page', ariaLast: 'Last page', ariaPage: function ariaPage(currentRefinement) { return 'Page ' + currentRefinement.toString(); } })(Pagination); /** * The Pagination widget displays a simple pagination system allowing the user to * change the current page. * @name Pagination * @kind widget * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [padding=3] - How many page links to display around the current page. * @propType {number} [totalPages=Infinity] - Maximum number of pages to display. * @themeKey ais-Pagination - the root div of the widget * @themeKey ais-Pagination--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-Pagination-list - the list of all pagination items * @themeKey ais-Pagination-list--noRefinement - the list of all pagination items when there is no refinement * @themeKey ais-Pagination-item - the pagination list item * @themeKey ais-Pagination-item--firstPage - the "first" pagination list item * @themeKey ais-Pagination-item--lastPage - the "last" pagination list item * @themeKey ais-Pagination-item--previousPage - the "previous" pagination list item * @themeKey ais-Pagination-item--nextPage - the "next" pagination list item * @themeKey ais-Pagination-item--page - the "page" pagination list item * @themeKey ais-Pagination-item--selected - the selected pagination list item * @themeKey ais-Pagination-item--disabled - the disabled pagination list item * @themeKey ais-Pagination-link - the pagination clickable element * @translationKey previous - Label value for the previous page link * @translationKey next - Label value for the next page link * @translationKey first - Label value for the first page link * @translationKey last - Label value for the last page link * @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string * @translationKey ariaPrevious - Accessibility label value for the previous page link * @translationKey ariaNext - Accessibility label value for the next page link * @translationKey ariaFirst - Accessibility label value for the first page link * @translationKey ariaLast - Accessibility label value for the last page link * @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string * @example * import React from 'react'; * * import { Pagination, InstantSearch } from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Pagination /> * </InstantSearch> * ); * } */ var PaginationWidget = function PaginationWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(Pagination$1, props) ); }; var Pagination$2 = connectPagination(PaginationWidget); /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ var connectPoweredBy = createConnector({ displayName: 'AlgoliaPoweredBy', propTypes: {}, getProvidedProps: function getProvidedProps(props) { var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + (props.canRender ? location.hostname : '') + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); var cx$12 = createClassNames('PoweredBy'); /* eslint-disable max-len */ var AlgoliaLogo = function AlgoliaLogo() { return React__default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', baseProfile: 'basic', viewBox: '0 0 1366 362', width: '100', height: '27', className: cx$12('logo') }, React__default.createElement( 'linearGradient', { id: 'g', x1: '428.258', x2: '434.145', y1: '404.15', y2: '409.85', gradientUnits: 'userSpaceOnUse', gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)' }, React__default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }), React__default.createElement('stop', { offset: '1', stopColor: '#3369E7' }) ), React__default.createElement('path', { d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z', fill: 'url(#g)' }), React__default.createElement('path', { d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z', fill: '#FFFFFF' }), React__default.createElement('path', { d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-10-3-16.7-3c-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1s19.5-2.6 30.3-2.6zm3.3 141.9c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18 5.9 3.6 13.7 5.3 23.6 5.3zM512.9 103c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4 5.3 5.8 8.9 13.5 11.1 21.7 2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6-12.2 1.8-25.9 2.7-41.1 2.7-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8 4.7.5 9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2-4.4-1.7-10-3-16.7-3-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1 9.4-1.8 19.5-2.6 30.3-2.6zm3.4 142c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z', fill: '#182359' }) ); }; /* eslint-enable max-len */ var PoweredBy = function (_Component) { inherits(PoweredBy, _Component); function PoweredBy() { classCallCheck(this, PoweredBy); return possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments)); } createClass(PoweredBy, [{ key: 'render', value: function render() { var _props = this.props, url = _props.url, translate = _props.translate, className = _props.className; return React__default.createElement( 'div', { className: classnames(cx$12(''), className) }, React__default.createElement( 'span', { className: cx$12('text') }, translate('searchBy') ), ' ', React__default.createElement( 'a', { href: url, target: '_blank', className: cx$12('link'), 'aria-label': 'Algolia' }, React__default.createElement(AlgoliaLogo, null) ) ); } }]); return PoweredBy; }(React.Component); PoweredBy.propTypes = { url: propTypes.string.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }; var PoweredByComponent = translatable({ searchBy: 'Search by' })(PoweredBy); /** * PoweredBy displays an Algolia logo. * * Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing). * @name PoweredBy * @kind widget * @themeKey ais-PoweredBy - the root div of the widget * @themeKey ais-PoweredBy-text - the text of the widget * @themeKey ais-PoweredBy-link - the link of the logo * @themeKey ais-PoweredBy-logo - the logo of the widget * @translationKey searchBy - Label value for the powered by * @example * import React from 'react'; * * import { PoweredBy, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <PoweredBy /> * </InstantSearch> * ); * } */ var PoweredBy$1 = connectPoweredBy(PoweredByComponent); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = _root.isFinite; /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite$1(value) { return typeof value == 'number' && nativeIsFinite(value); } var _isFinite = isFinite$1; /** * connectRange connector provides the logic to create connected * components that will give the ability for a user to refine results using * a numeric range. * @name connectRange * @kind connector * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @propType {string} attribute - Name of the attribute for faceting * @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {number} [precision=0] - Number of digits after decimal point to use. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {number} min - the minimum value available. * @providedPropType {number} max - the maximum value available. * @providedPropType {number} precision - Number of digits after decimal point to use. */ function getId$7(props) { return props.attribute; } var namespace$3 = 'range'; function getCurrentRange(boundaries, stats, precision) { var pow = Math.pow(10, precision); var min = void 0; if (_isFinite(boundaries.min)) { min = boundaries.min; } else if (_isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max = void 0; if (_isFinite(boundaries.max)) { max = boundaries.max; } else if (_isFinite(stats.max)) { max = stats.max; } else { max = undefined; } return { min: min !== undefined ? Math.floor(min * pow) / pow : min, max: max !== undefined ? Math.ceil(max * pow) / pow : max }; } function getCurrentRefinement$6(props, searchState, currentRange, context) { var refinement = getCurrentRefinementValue(props, searchState, context, namespace$3 + '.' + getId$7(props), {}, function (currentRefinement) { var min = currentRefinement.min, max = currentRefinement.max; if (typeof min === 'string') { min = parseInt(min, 10); } if (typeof max === 'string') { max = parseInt(max, 10); } return { min: min, max: max }; }); var hasMinBound = props.min !== undefined; var hasMaxBound = props.max !== undefined; var hasMinRefinment = refinement.min !== undefined; var hasMaxRefinment = refinement.max !== undefined; if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) { throw Error("You can't provide min value lower than range."); } if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) { throw Error("You can't provide max value greater than range."); } if (hasMinBound && !hasMinRefinment) { refinement.min = currentRange.min; } if (hasMaxBound && !hasMaxRefinment) { refinement.max = currentRange.max; } return refinement; } function nextValueForRefinement(hasBound, isReset, range, value) { var next = void 0; if (!hasBound && range === value) { next = undefined; } else if (hasBound && isReset) { next = range; } else { next = value; } return next; } function _refine$4(props, searchState, nextRefinement, currentRange, context) { var nextMin = nextRefinement.min, nextMax = nextRefinement.max; var currentMinRange = currentRange.min, currentMaxRange = currentRange.max; var isMinReset = nextMin === undefined || nextMin === ''; var isMaxReset = nextMax === undefined || nextMax === ''; var nextMinAsNumber = !isMinReset ? parseFloat(nextMin) : undefined; var nextMaxAsNumber = !isMaxReset ? parseFloat(nextMax) : undefined; var isNextMinValid = isMinReset || _isFinite(nextMinAsNumber); var isNextMaxValid = isMaxReset || _isFinite(nextMaxAsNumber); if (!isNextMinValid || !isNextMaxValid) { throw Error("You can't provide non finite values to the range connector."); } if (nextMinAsNumber < currentMinRange) { throw Error("You can't provide min value lower than range."); } if (nextMaxAsNumber > currentMaxRange) { throw Error("You can't provide max value greater than range."); } var id = getId$7(props); var resetPage = true; var nextValue = defineProperty$2({}, id, { min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber), max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber) }); return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$3(props, searchState, context) { return cleanUpValue(searchState, context, namespace$3 + '.' + getId$7(props)); } var connectRange = createConnector({ displayName: 'AlgoliaRange', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, defaultRefinement: propTypes.shape({ min: propTypes.number.isRequired, max: propTypes.number.isRequired }), min: propTypes.number, max: propTypes.number, precision: propTypes.number, header: propTypes.node, footer: propTypes.node }, defaultProps: { precision: 0 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute, precision = props.precision, minBound = props.min, maxBound = props.max; var results = getResults(searchResults, this.context); var hasFacet = results && results.getFacetByName(attribute); var stats = hasFacet ? results.getFacetStats(attribute) || {} : {}; var facetValues = hasFacet ? results.getFacetValues(attribute) : []; var count = facetValues.map(function (v) { return { value: v.name, count: v.count }; }); var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision), rangeMin = _getCurrentRange.min, rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example // when we set boundaries on the first render the searchState don't have // the correct refinement. If this behaviour change in the upcoming version // we could store the range inside the searchState instead of rely on `this`. this._currentRange = { min: rangeMin, max: rangeMax }; var _getCurrentRefinement = getCurrentRefinement$6(props, searchState, this._currentRange, this.context), valueMin = _getCurrentRefinement.min, valueMax = _getCurrentRefinement.max; return { min: rangeMin, max: rangeMax, canRefine: count.length > 0, currentRefinement: { min: valueMin === undefined ? rangeMin : valueMin, max: valueMax === undefined ? rangeMax : valueMax }, count: count, precision: precision }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$4(props, searchState, nextRefinement, this._currentRange, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attribute = props.attribute; var _getCurrentRefinement2 = getCurrentRefinement$6(props, searchState, this._currentRange, this.context), min = _getCurrentRefinement2.min, max = _getCurrentRefinement2.max; params = params.addDisjunctiveFacet(attribute); if (min !== undefined) { params = params.addNumericRefinement(attribute, '>=', min); } if (max !== undefined) { params = params.addNumericRefinement(attribute, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var _currentRange = this._currentRange, minRange = _currentRange.min, maxRange = _currentRange.max; var _getCurrentRefinement3 = getCurrentRefinement$6(props, searchState, this._currentRange, this.context), minValue = _getCurrentRefinement3.min, maxValue = _getCurrentRefinement3.max; var items = []; var hasMin = minValue !== undefined; var hasMax = maxValue !== undefined; var shouldDisplayMinLabel = hasMin && minValue !== minRange; var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange; if (shouldDisplayMinLabel || shouldDisplayMaxLabel) { var fragments = [hasMin ? minValue + ' <= ' : '', props.attribute, hasMax ? ' <= ' + maxValue : '']; items.push({ label: fragments.join(''), attribute: props.attribute, value: function value(nextState) { return _refine$4(props, nextState, {}, _this._currentRange, _this.context); }, currentRefinement: { min: minValue, max: maxValue } }); } return { id: getId$7(props), index: getIndex(this.context), items: items }; } }); var cx$13 = createClassNames('RangeInput'); var RawRangeInput = function (_Component) { inherits(RawRangeInput, _Component); function RawRangeInput(props) { classCallCheck(this, RawRangeInput); var _this = possibleConstructorReturn(this, (RawRangeInput.__proto__ || Object.getPrototypeOf(RawRangeInput)).call(this, props)); _this.onSubmit = function (e) { e.preventDefault(); _this.props.refine({ min: _this.state.from, max: _this.state.to }); }; _this.state = _this.normalizeStateForRendering(props); return _this; } createClass(RawRangeInput, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // In [email protected] the call to setState on the inputs trigger this lifecycle hook // because the context has changed (for react). I don't think that the bug is related // to react because I failed to reproduce it with a simple hierarchy of components. // The workaround here is to check the differences between previous & next props in order // to avoid to override current state when values are not yet refined. In the react documentation, // they DON'T categorically say that setState never run componentWillReceiveProps. // see: https://reactjs.org/docs/react-component.html#componentwillreceiveprops if (nextProps.canRefine && (this.props.canRefine !== nextProps.canRefine || this.props.currentRefinement.min !== nextProps.currentRefinement.min || this.props.currentRefinement.max !== nextProps.currentRefinement.max)) { this.setState(this.normalizeStateForRendering(nextProps)); } } }, { key: 'normalizeStateForRendering', value: function normalizeStateForRendering(props) { var canRefine = props.canRefine, rangeMin = props.min, rangeMax = props.max; var _props$currentRefinem = props.currentRefinement, valueMin = _props$currentRefinem.min, valueMax = _props$currentRefinem.max; return { from: canRefine && valueMin !== undefined && valueMin !== rangeMin ? valueMin : '', to: canRefine && valueMax !== undefined && valueMax !== rangeMax ? valueMax : '' }; } }, { key: 'normalizeRangeForRendering', value: function normalizeRangeForRendering(_ref) { var canRefine = _ref.canRefine, min = _ref.min, max = _ref.max; var hasMin = min !== undefined; var hasMax = max !== undefined; return { min: canRefine && hasMin && hasMax ? min : '', max: canRefine && hasMin && hasMax ? max : '' }; } }, { key: 'render', value: function render() { var _this2 = this; var _state = this.state, from = _state.from, to = _state.to; var _props = this.props, precision = _props.precision, translate = _props.translate, canRefine = _props.canRefine, className = _props.className; var _normalizeRangeForRen = this.normalizeRangeForRendering(this.props), min = _normalizeRangeForRen.min, max = _normalizeRangeForRen.max; var step = 1 / Math.pow(10, precision); return React__default.createElement( 'div', { className: classnames(cx$13('', !canRefine && '-noRefinement'), className) }, React__default.createElement( 'form', { className: cx$13('form'), onSubmit: this.onSubmit }, React__default.createElement('input', { className: cx$13('input', 'input--min'), type: 'number', min: min, max: max, value: from, step: step, placeholder: min, disabled: !canRefine, onChange: function onChange(e) { return _this2.setState({ from: e.currentTarget.value }); } }), React__default.createElement( 'span', { className: cx$13('separator') }, translate('separator') ), React__default.createElement('input', { className: cx$13('input', 'input--max'), type: 'number', min: min, max: max, value: to, step: step, placeholder: max, disabled: !canRefine, onChange: function onChange(e) { return _this2.setState({ to: e.currentTarget.value }); } }), React__default.createElement( 'button', { className: cx$13('submit'), type: 'submit' }, translate('submit') ) ) ); } }]); return RawRangeInput; }(React.Component); RawRangeInput.propTypes = { canRefine: propTypes.bool.isRequired, precision: propTypes.number.isRequired, translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, min: propTypes.number, max: propTypes.number, currentRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), className: propTypes.string }; RawRangeInput.defaultProps = { currentRefinement: {}, className: '' }; var RangeInput = translatable({ submit: 'ok', separator: 'to' })(RawRangeInput); /** * RangeInput allows a user to select a numeric range using a minimum and maximum input. * @name RangeInput * @kind widget * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @propType {string} attribute - the name of the attribute in the record * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {number} [precision=0] - Number of digits after decimal point to use. * @themeKey ais-RangeInput - the root div of the widget * @themeKey ais-RangeInput-form - the wrapping form * @themeKey ais-RangeInput-label - the label wrapping inputs * @themeKey ais-RangeInput-input - the input (number) * @themeKey ais-RangeInput-input--min - the minimum input * @themeKey ais-RangeInput-input--max - the maximum input * @themeKey ais-RangeInput-separator - the separator word used between the two inputs * @themeKey ais-RangeInput-button - the submit button * @translationKey submit - Label value for the submit button * @translationKey separator - Label value for the input separator * @example * import React from 'react'; * * import { RangeInput, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RangeInput attribute="price" /> * </InstantSearch> * ); * } */ var RangeInputWidget = function RangeInputWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(RangeInput, props) ); }; var RangeInput$1 = connectRange(RangeInputWidget); /** * Since a lot of sliders already exist, we did not include one by default. * However you can easily connect React InstantSearch to an existing one * using the [connectRange connector](connectors/connectRange.html). * * @name RangeSlider * @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values. * @kind widget * @example * * // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the * // range connector import PropTypes from 'prop-types'; import React, {Component} from 'react'; import {connectRange} from 'react-instantsearch/connectors'; import Rheostat from 'rheostat'; class Range extends React.Component { static propTypes = { min: PropTypes.number, max: PropTypes.number, currentRefinement: PropTypes.object, refine: PropTypes.func.isRequired, canRefine: PropTypes.bool.isRequired }; state = { currentValues: { min: this.props.min, max: this.props.max } }; componentWillReceiveProps(sliderState) { if (sliderState.canRefine) { this.setState({ currentValues: { min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max } }); } } onValuesUpdated = sliderState => { this.setState({ currentValues: { min: sliderState.values[0], max: sliderState.values[1] } }); }; onChange = sliderState => { if ( this.props.currentRefinement.min !== sliderState.values[0] || this.props.currentRefinement.max !== sliderState.values[1] ) { this.props.refine({ min: sliderState.values[0], max: sliderState.values[1] }); } }; render() { const { min, max, currentRefinement } = this.props; const { currentValues } = this.state; return min !== max ? ( <div> <Rheostat className="ais-RangeSlider" min={min} max={max} values={[currentRefinement.min, currentRefinement.max]} onChange={this.onChange} onValuesUpdated={this.onValuesUpdated} /> <div style={{ display: "flex", justifyContent: "space-between" }}> <div>{currentValues.min}</div> <div>{currentValues.max}</div> </div> </div> ) : null; } } const ConnectedRange = connectRange(Range); */ var RangeSlider = (function () { return React__default.createElement( "div", null, "We do not provide any Slider, see the documentation to learn how to connect one easily:", React__default.createElement( "a", { target: "_blank", rel: "noopener noreferrer", href: "https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html" }, "https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html" ) ); }); var cx$14 = createClassNames('RatingMenu'); var RatingMenu = function (_Component) { inherits(RatingMenu, _Component); function RatingMenu() { classCallCheck(this, RatingMenu); return possibleConstructorReturn(this, (RatingMenu.__proto__ || Object.getPrototypeOf(RatingMenu)).apply(this, arguments)); } createClass(RatingMenu, [{ key: 'onClick', value: function onClick(min, max, e) { e.preventDefault(); e.stopPropagation(); if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) { this.props.refine({ min: this.props.min, max: this.props.max }); } else { this.props.refine({ min: min, max: max }); } } }, { key: 'buildItem', value: function buildItem(_ref) { var max = _ref.max, lowerBound = _ref.lowerBound, count = _ref.count, translate = _ref.translate, createURL = _ref.createURL, isLastSelectableItem = _ref.isLastSelectableItem; var disabled = !count; var isCurrentMinLower = this.props.currentRefinement.min < lowerBound; var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max; var icons = []; var rating = 0; for (var icon = 0; icon < max; icon++) { if (icon < lowerBound) { rating++; } icons.push([React__default.createElement( 'svg', { key: icon, className: cx$14('starIcon', icon >= lowerBound ? 'starIcon--empty' : 'starIcon--full'), 'aria-hidden': 'true', width: '24', height: '24' }, React__default.createElement('use', { xlinkHref: '#' + cx$14(icon >= lowerBound ? 'starEmptySymbol' : 'starSymbol') }) ), ' ']); } // The last item of the list (the default item), should not // be clickable if it is selected. var isLastAndSelect = isLastSelectableItem && selected; var onClickHandler = disabled || isLastAndSelect ? {} : { href: createURL({ min: lowerBound, max: max }), onClick: this.onClick.bind(this, lowerBound, max) }; return React__default.createElement( 'li', { key: lowerBound, className: cx$14('item', selected && 'item--selected', disabled && 'item--disabled') }, React__default.createElement( 'a', _extends({ className: cx$14('link'), 'aria-label': '' + rating + translate('ratingLabel') }, onClickHandler), icons, React__default.createElement( 'span', { className: cx$14('label'), 'aria-hidden': 'true' }, translate('ratingLabel') ), ' ', React__default.createElement( 'span', { className: cx$14('count') }, count ) ) ); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, translate = _props.translate, refine = _props.refine, min = _props.min, max = _props.max, count = _props.count, createURL = _props.createURL, canRefine = _props.canRefine, className = _props.className; var items = []; var _loop = function _loop(i) { var hasCount = !isEmpty_1(count.filter(function (item) { return Number(item.value) === i; })); var lastSelectableItem = count.reduce(function (acc, item) { return item.value < acc.value || !acc.value && hasCount ? item : acc; }, {}); var itemCount = count.reduce(function (acc, item) { return item.value >= i && hasCount ? acc + item.count : acc; }, 0); items.push(_this2.buildItem({ cx: cx$14, lowerBound: i, max: max, refine: refine, count: itemCount, translate: translate, createURL: createURL, isLastSelectableItem: i === Number(lastSelectableItem.value) })); }; for (var i = max; i >= min; i--) { _loop(i); } return React__default.createElement( 'div', { className: classnames(cx$14('', !canRefine && '-noRefinement'), className) }, React__default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } }, React__default.createElement( 'symbol', { id: cx$14('starSymbol'), viewBox: '0 0 24 24' }, React__default.createElement('path', { d: 'M12 .288l2.833 8.718h9.167l-7.417 5.389 2.833 8.718-7.416-5.388-7.417 5.388 2.833-8.718-7.416-5.389h9.167z' }) ), React__default.createElement( 'symbol', { id: cx$14('starEmptySymbol'), viewBox: '0 0 24 24' }, React__default.createElement('path', { d: 'M12 6.76l1.379 4.246h4.465l-3.612 2.625 1.379 4.246-3.611-2.625-3.612 2.625 1.379-4.246-3.612-2.625h4.465l1.38-4.246zm0-6.472l-2.833 8.718h-9.167l7.416 5.389-2.833 8.718 7.417-5.388 7.416 5.388-2.833-8.718 7.417-5.389h-9.167l-2.833-8.718z' }) ) ), React__default.createElement( 'ul', { className: cx$14('list', !canRefine && 'list--noRefinement') }, items ) ); } }]); return RatingMenu; }(React.Component); RatingMenu.propTypes = { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, min: propTypes.number, max: propTypes.number, currentRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), count: propTypes.arrayOf(propTypes.shape({ value: propTypes.string, count: propTypes.number })), canRefine: propTypes.bool.isRequired, className: propTypes.string }; RatingMenu.defaultProps = { className: '' }; var RatingMenu$1 = translatable({ ratingLabel: ' & Up' })(RatingMenu); /** * RatingMenu lets the user refine search results by clicking on stars. * * The stars are based on the selected `attribute`. * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @name RatingMenu * @kind widget * @propType {string} attribute - the name of the attribute in the record * @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating. * @themeKey ais-RatingMenu - the root div of the widget * @themeKey ais-RatingMenu--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-RatingMenu-list - the list of ratings * @themeKey ais-RatingMenu-list--noRefinement - the list of ratings when there is no refinement * @themeKey ais-RatingMenu-item - the rating list item * @themeKey ais-RatingMenu-item--selected - the selected rating list item * @themeKey ais-RatingMenu-item--disabled - the disabled rating list item * @themeKey ais-RatingMenu-link - the rating clickable item * @themeKey ais-RatingMenu-starIcon - the star icon * @themeKey ais-RatingMenu-starIcon--full - the filled star icon * @themeKey ais-RatingMenu-starIcon--empty - the empty star icon * @themeKey ais-RatingMenu-label - the label used after the stars * @themeKey ais-RatingMenu-count - the count of ratings for a specific item * @translationKey ratingLabel - Label value for the rating link * @example * import React from 'react'; * * import { RatingMenu, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RatingMenu attribute="rating" /> * </InstantSearch> * ); * } */ var RatingMenuWidget = function RatingMenuWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(RatingMenu$1, props) ); }; var RatingMenu$2 = connectRange(RatingMenuWidget); var namespace$4 = 'refinementList'; function getId$8(props) { return props.attribute; } function getCurrentRefinement$7(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$4 + '.' + getId$8(props), [], function (currentRefinement) { if (typeof currentRefinement === 'string') { // All items were unselected if (currentRefinement === '') { return []; } // Only one item was in the searchState but we know it should be an array return [currentRefinement]; } return currentRefinement; }); } function getValue$4(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$7(props, searchState, context); var isAnewValue = currentRefinement.indexOf(name) === -1; var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates : currentRefinement.filter(function (selectedValue) { return selectedValue !== name; }); // cannot use .splice(), it mutates return nextRefinement; } function getLimit$1(_ref) { var showMore = _ref.showMore, limit = _ref.limit, showMoreLimit = _ref.showMoreLimit; return showMore ? showMoreLimit : limit; } function _refine$5(props, searchState, nextRefinement, context) { var id = getId$8(props); // Setting the value to an empty string ensures that it is persisted in // the URL as an empty value. // This is necessary in the case where `defaultRefinement` contains one // item and we try to deselect it. `nextSelected` would be an empty array, // which would not be persisted to the URL. // {foo: ['bar']} => "foo[0]=bar" // {foo: []} => "" var nextValue = defineProperty$2({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$4); } function _cleanUp$4(props, searchState, context) { return cleanUpValue(searchState, context, namespace$4 + '.' + getId$8(props)); } /** * connectRefinementList connector provides the logic to build a widget that will * give the user the ability to choose multiple values for a specific facet. * @name connectRefinementList * @kind connector * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [searchable=false] - allow search inside values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of displayed items * @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var sortBy$2 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnector({ displayName: 'AlgoliaRefinementList', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, operator: propTypes.oneOf(['and', 'or']), showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), searchable: propTypes.bool, transformItems: propTypes.func }, defaultProps: { operator: 'or', showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$7(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, searchable: searchable }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$4(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$2 }).map(function (v) { return { label: v.name, value: getValue$4(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit$1(props)), currentRefinement: getCurrentRefinement$7(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$5(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit$1(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, operator = props.operator; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = addKey + 'Refinement'; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props)) }); searchParameters = searchParameters[addKey](attribute); return getCurrentRefinement$7(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attribute, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$8(props); var context = this.context; return { id: id, index: getIndex(this.context), items: getCurrentRefinement$7(props, searchState, context).length > 0 ? [{ attribute: props.attribute, label: props.attribute + ': ', currentRefinement: getCurrentRefinement$7(props, searchState, context), value: function value(nextState) { return _refine$5(props, nextState, [], context); }, items: getCurrentRefinement$7(props, searchState, context).map(function (item) { return { label: '' + item, value: function value(nextState) { var nextSelectedItems = getCurrentRefinement$7(props, nextState, context).filter(function (other) { return other !== item; }); return _refine$5(props, searchState, nextSelectedItems, context); } }; }) }] : [] }; } }); var cx$15 = createClassNames('RefinementList'); var RefinementList$3 = function (_Component) { inherits(RefinementList, _Component); function RefinementList() { var _ref; var _temp, _this, _ret; classCallCheck(this, RefinementList); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call.apply(_ref, [this].concat(args))), _this), _this.state = { query: '' }, _this.selectItem = function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }, _this.renderItem = function (item, resetQuery) { var label = _this.props.isFromSearch ? React__default.createElement(Highlight$3, { attribute: 'label', hit: item }) : item.label; return React__default.createElement( 'label', { className: cx$15('label') }, React__default.createElement('input', { className: cx$15('checkbox'), type: 'checkbox', checked: item.isRefined, onChange: function onChange() { return _this.selectItem(item, resetQuery); } }), React__default.createElement( 'span', { className: cx$15('labelText') }, label ), ' ', React__default.createElement( 'span', { className: cx$15('count') }, item.count.toLocaleString() ) ); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(RefinementList, [{ key: 'render', value: function render() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$15 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isFromSearch', 'searchForItems', 'searchable', 'canRefine', 'className']), { query: this.state.query })); } }]); return RefinementList; }(React.Component); RefinementList$3.propTypes = { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, searchForItems: propTypes.func.isRequired, searchable: propTypes.bool, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.arrayOf(propTypes.string).isRequired, count: propTypes.number.isRequired, isRefined: propTypes.bool.isRequired })), isFromSearch: propTypes.bool.isRequired, canRefine: propTypes.bool.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func, className: propTypes.string }; RefinementList$3.defaultProps = { className: '' }; var RefinementList$4 = translatable({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(RefinementList$3); /** * The RefinementList component displays a list that let the end user choose multiple values for a specific facet. * @name RefinementList * @kind widget * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/). * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of displayed items * @propType {number} [showMoreLimit=20] - the maximum number of displayed items. Only used when showMore is set to `true` * @propType {string[]} [defaultRefinement] - the values of the items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-RefinementList - the root div of the widget * @themeKey ais-RefinementList--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-RefinementList-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-RefinementList-list - the list of refinement items * @themeKey ais-RefinementList-item - the refinement list item * @themeKey ais-RefinementList-item--selected - the refinement selected list item * @themeKey ais-RefinementList-label - the label of each refinement item * @themeKey ais-RefinementList-checkbox - the checkbox input of each refinement item * @themeKey ais-RefinementList-labelText - the label text of each refinement item * @themeKey ais-RefinementList-count - the count of values for each item * @themeKey ais-RefinementList-noResults - the div displayed when there are no results * @themeKey ais-RefinementList-showMore - the button used to display more categories * @themeKey ais-RefinementList-showMore--disabled - the disabled button used to display more categories * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * If you are using the `searchable` prop, you'll also need to make the attribute searchable using * the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values). * @example * import React from 'react'; * * import { RefinementList, InstantSearch } from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RefinementList attribute="colors" /> * </InstantSearch> * ); * } */ var RefinementListWidget = function RefinementListWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(RefinementList$4, props) ); }; var RefinementList$5 = connectRefinementList(RefinementListWidget); var cx$16 = createClassNames('ClearRefinements'); var ClearRefinements = function (_Component) { inherits(ClearRefinements, _Component); function ClearRefinements() { classCallCheck(this, ClearRefinements); return possibleConstructorReturn(this, (ClearRefinements.__proto__ || Object.getPrototypeOf(ClearRefinements)).apply(this, arguments)); } createClass(ClearRefinements, [{ key: 'render', value: function render() { var _props = this.props, items = _props.items, canRefine = _props.canRefine, refine = _props.refine, translate = _props.translate, className = _props.className; return React__default.createElement( 'div', { className: classnames(cx$16(''), className) }, React__default.createElement( 'button', { className: cx$16('button', !canRefine && 'button--disabled'), onClick: function onClick() { return refine(items); }, disabled: !canRefine }, translate('reset') ) ); } }]); return ClearRefinements; }(React.Component); ClearRefinements.propTypes = { items: propTypes.arrayOf(propTypes.object).isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }; ClearRefinements.defaultProps = { className: '' }; var ClearRefinements$1 = translatable({ reset: 'Clear all filters' })(ClearRefinements); /** * The ClearRefinements widget displays a button that lets the user clean every refinement applied * to the search. * @name ClearRefinements * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [clearsQuery=false] - Pass true to also clear the search query * @themeKey ais-ClearRefinements - the root div of the widget * @themeKey ais-ClearRefinements-button - the clickable button * @themeKey ais-ClearRefinements-button--disabled - the disabled clickable button * @translationKey reset - the clear all button value * @example * import React from 'react'; * * import { ClearRefinements, RefinementList, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ClearRefinements /> * <RefinementList attribute="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ var ClearRefinementsWidget = function ClearRefinementsWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(ClearRefinements$1, props) ); }; var ClearRefinements$2 = connectCurrentRefinements(ClearRefinementsWidget); /** * connectScrollTo connector provides the logic to build a widget that will * let the page scroll to a certain point. * @name connectScrollTo * @kind connector * @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget. * @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo * @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default) */ var connectScrollTo = createConnector({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, this.context, id, null, function (currentRefinement) { return currentRefinement; }); if (!this._prevSearchState) { this._prevSearchState = {}; } /* Get the subpart of the state that interest us*/ if (hasMultipleIndex(this.context)) { var index = getIndex(this.context); searchState = searchState.indices ? searchState.indices[index] : {}; } /* if there is a change in the app that has been triggered by another element than "props.scrollOn (id) or the Configure widget, we need to keep track of the search state to know if there's a change in the app that was not triggered by the props.scrollOn (id) or the Configure widget. This is useful when using ScrollTo in combination of Pagination. As pagination can be change by every widget, we want to scroll only if it cames from the pagination widget itself. We also remove the configure key from the search state to do this comparaison because for now configure values are not present in the search state before a first refinement has been made and will false the results. See: https://github.com/algolia/react-instantsearch/issues/164 */ var cleanedSearchState = omit_1(omit_1(searchState, 'configure'), id); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); var cx$17 = createClassNames('ScrollTo'); var ScrollTo = function (_Component) { inherits(ScrollTo, _Component); function ScrollTo() { classCallCheck(this, ScrollTo); return possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments)); } createClass(ScrollTo, [{ key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { var _props = this.props, value = _props.value, hasNotChanged = _props.hasNotChanged; if (value !== prevProps.value && hasNotChanged) { this.el.scrollIntoView(); } } }, { key: 'render', value: function render() { var _this2 = this; return React__default.createElement( 'div', { ref: function ref(_ref) { return _this2.el = _ref; }, className: cx$17('') }, this.props.children ); } }]); return ScrollTo; }(React.Component); ScrollTo.propTypes = { value: propTypes.any, children: propTypes.node, hasNotChanged: propTypes.bool }; /** * The ScrollTo component will make the page scroll to the component wrapped by it when one of the * [search state](guide/Search_state.html) prop is updated. By default when the page number changes, * the scroll goes to the wrapped component. * * @name ScrollTo * @kind widget * @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes. * @themeKey ais-ScrollTo - the root div of the widget * @example * import React from 'react'; * * import { ScrollTo, Hits, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ScrollTo> * <Hits /> * </ScrollTo> * </InstantSearch> * ); * } */ var ScrollTo$1 = connectScrollTo(ScrollTo); function getId$9() { return 'query'; } function getCurrentRefinement$8(props, searchState, context) { var id = getId$9(props); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function _refine$6(props, searchState, nextRefinement, context) { var id = getId$9(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp$5(props, searchState, context) { return cleanUpValue(searchState, context, getId$9()); } /** * connectSearchBox connector provides the logic to build a widget that will * let the user search for a query. * @name connectSearchBox * @kind connector * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the query to search for. * @providedPropType {boolean} isSearchStalled - a flag that indicates if react-is has detected that searches are stalled. */ var connectSearchBox = createConnector({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { currentRefinement: getCurrentRefinement$8(props, searchState, this.context), isSearchStalled: searchResults.isSearchStalled }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$6(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$8(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$9(props); var currentRefinement = getCurrentRefinement$8(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: id + ': ' + currentRefinement, value: function value(nextState) { return _refine$6(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); /** * The SearchBox component displays a search box that lets the user search for a specific query. * @name SearchBox * @kind widget * @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes. * @propType {boolean} [autoFocus=false] - Should the search box be focused on render? * @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused. * @propType {function} [onSubmit] - Intercept submit event sent from the SearchBox form container. * @propType {function} [onReset] - Listen to `reset` event sent from the SearchBox form container. * @propType {function} [on*] - Listen to any events sent form the search input itself. * @propType {node} [submit] - Change the apparence of the default submit button (magnifying glass). * @propType {node} [reset] - Change the apparence of the default reset button (cross). * @propType {node} [loadingIndicator] - Change the apparence of the default loading indicator (spinning circle). * @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted. * @propType {boolean} [showLoadingIndicator=false] - Display that the search is loading. This only happens after a certain amount of time to avoid a blinking effect. This timer can be configured with `stalledSearchDelay` props on <InstantSearch>. By default, the value is 200ms. * @themeKey ais-SearchBox - the root div of the widget * @themeKey ais-SearchBox-form - the wrapping form * @themeKey ais-SearchBox-input - the search input * @themeKey ais-SearchBox-submit - the submit button * @themeKey ais-SearchBox-submitIcon - the default magnifier icon used with the search input * @themeKey ais-SearchBox-reset - the reset button used to clear the content of the input * @themeKey ais-SearchBox-resetIcon - the default reset icon used inside the reset button * @themeKey ais-SearchBox-loadingIndicator - the loading indicator container * @themeKey ais-SearchBox-loadingIcon - the default loading icon * @translationkey submitTitle - The submit button title * @translationkey resetTitle - The reset button title * @translationkey placeholder - The label of the input placeholder * @example * import React from 'react'; * * import { SearchBox, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * </InstantSearch> * ); * } */ var SearchBox$2 = connectSearchBox(SearchBox$1); function getId$10() { return 'sortBy'; } function getCurrentRefinement$9(props, searchState, context) { var id = getId$10(props); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return null; }); } /** * The connectSortBy connector provides the logic to build a widget that will * display a list of indices. This allows a user to change how the hits are being sorted. * @name connectSortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind connector * @propType {string} defaultRefinement - The default selected index. * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectSortBy = createConnector({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: propTypes.string, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$9(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$10(); var nextValue = defineProperty$2({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$10()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$9(props, searchState, this.context); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId$10() }; } }); var cx$18 = createClassNames('SortBy'); var SortBy = function (_Component) { inherits(SortBy, _Component); function SortBy() { classCallCheck(this, SortBy); return possibleConstructorReturn(this, (SortBy.__proto__ || Object.getPrototypeOf(SortBy)).apply(this, arguments)); } createClass(SortBy, [{ key: 'render', value: function render() { var _props = this.props, items = _props.items, currentRefinement = _props.currentRefinement, refine = _props.refine, className = _props.className; return React__default.createElement( 'div', { className: classnames(cx$18(''), className) }, React__default.createElement(Select, { cx: cx$18, items: items, selectedItem: currentRefinement, onSelect: refine }) ); } }]); return SortBy; }(React.Component); SortBy.propTypes = { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, currentRefinement: propTypes.string.isRequired, refine: propTypes.func.isRequired, className: propTypes.string }; SortBy.defaultProps = { className: '' }; /** * The SortBy component displays a list of indexes allowing a user to change the hits are sorting. * @name SortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind widget * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {string} defaultRefinement - The default selected index. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-SortBy - the root div of the widget * @themeKey ais-SortBy-select - the select * @themeKey ais-SortBy-option - the select option * @example * import React from 'react'; * * import { SortBy, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SortBy * items={[ * { value: 'ikea', label: 'Featured' }, * { value: 'ikea_price_asc', label: 'Price asc.' }, * { value: 'ikea_price_desc', label: 'Price desc.' }, * ]} * defaultRefinement="ikea" * /> * </InstantSearch> * ); * } */ var SortBy$2 = connectSortBy(SortBy); /** * connectStats connector provides the logic to build a widget that will * displays algolia search statistics (hits number and processing time). * @name connectStats * @kind connector * @providedPropType {number} nbHits - number of hits returned by Algolia. * @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results. */ var connectStats = createConnector({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); var cx$19 = createClassNames('Stats'); var Stats = function (_Component) { inherits(Stats, _Component); function Stats() { classCallCheck(this, Stats); return possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments)); } createClass(Stats, [{ key: 'render', value: function render() { var _props = this.props, translate = _props.translate, nbHits = _props.nbHits, processingTimeMS = _props.processingTimeMS, className = _props.className; return React__default.createElement( 'div', { className: classnames(cx$19(''), className) }, React__default.createElement( 'span', { className: cx$19('text') }, translate('stats', nbHits, processingTimeMS) ) ); } }]); return Stats; }(React.Component); Stats.propTypes = { translate: propTypes.func.isRequired, nbHits: propTypes.number.isRequired, processingTimeMS: propTypes.number.isRequired, className: propTypes.string }; Stats.defaultProps = { className: '' }; var Stats$1 = translatable({ stats: function stats(n, ms) { return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms'; } })(Stats); /** * The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server). * @name Stats * @kind widget * @themeKey ais-Stats - the root div of the widget * @themeKey ais-Stats-text - the text of the widget - the count of items for each item * @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time. * @example * import React from 'react'; * * import { Stats, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Stats /> * </InstantSearch> * ); * } */ var Stats$2 = connectStats(Stats$1); function getId$11(props) { return props.attribute; } var namespace$5 = 'toggle'; function getCurrentRefinement$10(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$5 + '.' + getId$11(props), false, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return false; }); } function _refine$7(props, searchState, nextRefinement, context) { var id = getId$11(props); var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$5); } function _cleanUp$6(props, searchState, context) { return cleanUpValue(searchState, context, namespace$5 + '.' + getId$11(props)); } /** * connectToggleRefinement connector provides the logic to build a widget that will * provides an on/off filtering feature based on an attribute value. * @name connectToggleRefinement * @kind connector * @requirements To use this widget, you'll need an attribute to toggle on. * * You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an * extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details. * * @propType {string} attribute - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attribute`. * @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default? * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise */ var connectToggleRefinement = createConnector({ displayName: 'AlgoliaToggle', propTypes: { label: propTypes.string, filter: propTypes.func, attribute: propTypes.string, value: propTypes.any, defaultRefinement: propTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$10(props, searchState, this.context); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$7(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, value = props.value, filter = props.filter; var checked = getCurrentRefinement$10(props, searchState, this.context); if (checked) { if (attribute) { searchParameters = searchParameters.addFacet(attribute).addFacetRefinement(attribute, value); } if (filter) { searchParameters = filter(searchParameters); } } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$11(props); var checked = getCurrentRefinement$10(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (checked) { items.push({ label: props.label, currentRefinement: checked, attribute: props.attribute, value: function value(nextState) { return _refine$7(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); var cx$20 = createClassNames('ToggleRefinement'); var ToggleRefinement = function ToggleRefinement(_ref) { var currentRefinement = _ref.currentRefinement, label = _ref.label, refine = _ref.refine, className = _ref.className; return React__default.createElement( 'div', { className: classnames(cx$20(''), className) }, React__default.createElement( 'label', { className: cx$20('label') }, React__default.createElement('input', { className: cx$20('checkbox'), type: 'checkbox', checked: currentRefinement, onChange: function onChange(event) { return refine(event.target.checked); } }), React__default.createElement( 'span', { className: cx$20('labelText') }, label ) ) ); }; ToggleRefinement.propTypes = { currentRefinement: propTypes.bool.isRequired, label: propTypes.string.isRequired, refine: propTypes.func.isRequired, className: propTypes.string }; ToggleRefinement.defaultProps = { className: '' }; /** * The ToggleRefinement provides an on/off filtering feature based on an attribute value. * @name ToggleRefinement * @kind widget * @requirements To use this widget, you'll need an attribute to toggle on. * * You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an * extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details. * * @propType {string} attribute - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {any} value - Value of the refinement to apply on `attribute` when checked. * @propType {boolean} [defaultRefinement=false] - Default state of the widget. Should the toggle be checked by default? * @themeKey ais-ToggleRefinement - the root div of the widget * @themeKey ais-ToggleRefinement-list - the list of toggles * @themeKey ais-ToggleRefinement-item - the toggle list item * @themeKey ais-ToggleRefinement-label - the label of each toggle item * @themeKey ais-ToggleRefinement-checkbox - the checkbox input of each toggle item * @themeKey ais-ToggleRefinement-labelText - the label text of each toggle item * @themeKey ais-ToggleRefinement-count - the count of items for each item * @example * import React from 'react'; * * import { ToggleRefinement, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ToggleRefinement * attribute="materials" * label="Made with solid pine" * value="Solid pine" * /> * </InstantSearch> * ); * } */ var ToggleRefinement$2 = connectToggleRefinement(ToggleRefinement); var cx$21 = createClassNames('Panel'); var Panel = function (_Component) { inherits(Panel, _Component); function Panel() { var _ref; var _temp, _this, _ret; classCallCheck(this, Panel); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Panel.__proto__ || Object.getPrototypeOf(Panel)).call.apply(_ref, [this].concat(args))), _this), _this.state = { canRefine: true }, _this.setCanRefine = function (nextCanRefine) { _this.setState({ canRefine: nextCanRefine }); }, _temp), possibleConstructorReturn(_this, _ret); } createClass(Panel, [{ key: 'getChildContext', value: function getChildContext() { return { setCanRefine: this.setCanRefine }; } }, { key: 'render', value: function render() { var _props = this.props, children = _props.children, className = _props.className, header = _props.header, footer = _props.footer; var canRefine = this.state.canRefine; return React__default.createElement( 'div', { className: classnames(cx$21('', !canRefine && '-noRefinement'), className) }, header && React__default.createElement( 'div', { className: cx$21('header') }, header ), React__default.createElement( 'div', { className: cx$21('body') }, children ), footer && React__default.createElement( 'div', { className: cx$21('footer') }, footer ) ); } }]); return Panel; }(React.Component); Panel.propTypes = { children: propTypes.node.isRequired, className: propTypes.string, header: propTypes.node, footer: propTypes.node }; Panel.childContextTypes = { setCanRefine: propTypes.func.isRequired }; Panel.defaultProps = { className: '', header: null, footer: null }; var getId$12 = function getId(props) { return props.attributes[0]; }; var namespace$6 = 'hierarchicalMenu'; function _refine$8(props, searchState, nextRefinement, context) { var id = getId$12(props); var nextValue = defineProperty$2({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$6); } function transformValue$1(values) { return values.reduce(function (acc, item) { if (item.isRefined) { acc.push({ label: item.name, // If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label // If dealing with the first level, "value" is equal to the current label value: item.path }); // Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one if (item.data) { acc = acc.concat(transformValue$1(item.data, acc)); } } return acc; }, []); } /** * The breadcrumb component is s a type of secondary navigation scheme that * reveals the user’s location in a website or web application. * * @name connectBreadcrumb * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a Breadcrumb of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display. */ var connectBreadcrumb = createConnector({ displayName: 'AlgoliaBreadcrumb', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var id = getId$12(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], canRefine: false }; } var values = results.getFacetValues(id); var items = values.data ? transformValue$1(values.data) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { canRefine: transformedItems.length > 0, items: transformedItems }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, this.context); } }); var cx$22 = createClassNames('Breadcrumb'); var itemsPropType$2 = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired })); var Breadcrumb = function (_Component) { inherits(Breadcrumb, _Component); function Breadcrumb() { classCallCheck(this, Breadcrumb); return possibleConstructorReturn(this, (Breadcrumb.__proto__ || Object.getPrototypeOf(Breadcrumb)).apply(this, arguments)); } createClass(Breadcrumb, [{ key: 'render', value: function render() { var _props = this.props, canRefine = _props.canRefine, createURL = _props.createURL, items = _props.items, refine = _props.refine, rootURL = _props.rootURL, separator = _props.separator, translate = _props.translate, className = _props.className; var rootPath = canRefine ? React__default.createElement( 'li', { className: cx$22('item') }, React__default.createElement( Link, { className: cx$22('link'), onClick: function onClick() { return !rootURL ? refine() : null; }, href: rootURL ? rootURL : createURL() }, translate('rootLabel') ) ) : null; var breadcrumb = items.map(function (item, idx) { var isLast = idx === items.length - 1; return React__default.createElement( 'li', { className: cx$22('item', isLast && 'item--selected'), key: idx }, React__default.createElement( 'span', { className: cx$22('separator') }, separator ), !isLast ? React__default.createElement( Link, { className: cx$22('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, item.label ) : item.label ); }); return React__default.createElement( 'div', { className: classnames(cx$22('', !canRefine && '-noRefinement'), className) }, React__default.createElement( 'ul', { className: cx$22('list') }, rootPath, breadcrumb ) ); } }]); return Breadcrumb; }(React.Component); Breadcrumb.propTypes = { canRefine: propTypes.bool.isRequired, createURL: propTypes.func.isRequired, items: itemsPropType$2, refine: propTypes.func.isRequired, rootURL: propTypes.string, separator: propTypes.node, translate: propTypes.func.isRequired, className: propTypes.string }; Breadcrumb.defaultProps = { rootURL: null, separator: ' > ', className: '' }; var Breadcrumb$1 = translatable({ rootLabel: 'Home' })(Breadcrumb); /** * A breadcrumb is a secondary navigation scheme that allows the user to see where the current page * is in relation to the website or web application’s hierarchy. * In terms of usability, using a breadcrumb reduces the number of actions a visitor needs to take in * order to get to a higher-level page. * * If you want to select a specific refinement for your Breadcrumb component, you will need to * use a [Virtual Hierarchical Menu](https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html) * and set its defaultRefinement that will be then used by the Breadcrumb. * * @name Breadcrumb * @kind widget * @requirements Breadcrumbs are used for websites with a large amount of content organised in a hierarchical manner. * The typical example is an e-commerce website which has a large variety of products grouped into logical categories * (with categories, subcategories which also have subcategories).To use this widget, your attributes must be formatted in a specific way. * * Keep in mind that breadcrumbs shouldn’t replace effective primary navigation menus: * it is only an alternative way to navigate around the website. * * If, for instance, you would like to have a breadcrumb of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow * @propType {node} [separator='>'] - Symbol used for separating hyperlinks * @propType {string} [rootURL=null] - The originating page (homepage) * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return * @themeKey ais-Breadcrumb - the root div of the widget * @themeKey ais-Breadcrumb--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-Breadcrumb-list - the list of all breadcrumb items * @themeKey ais-Breadcrumb-item - the breadcrumb navigation item * @themeKey ais-Breadcrumb-item--selected - the selected breadcrumb item * @themeKey ais-Breadcrumb-separator - the separator of each breadcrumb item * @themeKey ais-Breadcrumb-link - the clickable breadcrumb element * @translationKey rootLabel - The root's label. Accepts a string * @example * import React from 'react'; * import { Breadcrumb, InstantSearch } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Breadcrumb * attributes={[ * 'category', * 'sub_category', * 'sub_sub_category', * ]} * /> * </InstantSearch> * ); * } */ var BreadcrumbWidget = function BreadcrumbWidget(props) { return React__default.createElement( PanelCallbackHandler, props, React__default.createElement(Breadcrumb$1, props) ); }; var Breadcrumb$2 = connectBreadcrumb(BreadcrumbWidget); var InstantSearch$2 = createInstantSearch(algoliasearchLite, { Root: 'div', props: { className: 'ais-InstantSearch__root' } }); var Index$2 = createIndex({ Root: 'div', props: { className: 'ais-MultiIndex__root' } }); exports.InstantSearch = InstantSearch$2; exports.Index = Index$2; exports.Configure = Configure$1; exports.CurrentRefinements = CurrentRefinements$2; exports.HierarchicalMenu = HierarchicalMenu$2; exports.Highlight = Highlight$3; exports.Snippet = Snippet$2; exports.Hits = Hits$2; exports.HitsPerPage = HitsPerPage$2; exports.InfiniteHits = InfiniteHits$2; exports.Menu = Menu$2; exports.MenuSelect = MenuSelect$2; exports.NumericMenu = NumericMenu$2; exports.Pagination = Pagination$2; exports.PoweredBy = PoweredBy$1; exports.RangeInput = RangeInput$1; exports.RangeSlider = RangeSlider; exports.RatingMenu = RatingMenu$2; exports.RefinementList = RefinementList$5; exports.ClearRefinements = ClearRefinements$2; exports.ScrollTo = ScrollTo$1; exports.SearchBox = SearchBox$2; exports.SortBy = SortBy$2; exports.Stats = Stats$2; exports.ToggleRefinement = ToggleRefinement$2; exports.Panel = Panel; exports.Breadcrumb = Breadcrumb$2; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=Dom.js.map
App/db/entities/content/Events/Theatre.js
nthbr/mamasound.fr
/* * Copyright (c) 2017. Caipi Labs. All rights reserved. * * This File is part of Caipi. 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, either version 3 of the * License, or (at your option) any later version. * This program 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/>. * This project is dual licensed under AGPL and Commercial Licence. * * @author : Nathanael Braun * @contact : [email protected] */ /** * @author Nathanael BRAUN * * Date: 24/11/2015 * Time: 19:18 */ import React from 'react'; import {types, validate} from 'App/db/field'; export default { ...require("../Event"), label : "Piece de Theatre", targetCollection : "Event", disallowCreate : false,//Can't create pure events so we must enable editing when inheriting... adminRoute : "Événements/Theatre", // apiRoute : "dates", wwwRoute : "Theatre" };
src/scripts/main.js
needcash/real-estate-lead-generation
import React from 'react'; import ReactDOM from 'react-dom'; import Website from './components/Website'; import style from '../styles/main.scss'; ReactDOM.render(<Website />, document.getElementById('app'));
src/client-scripts/admin-client.js
thegazelle-ad/gazelle-front-end
/* eslint-disable react/jsx-filename-extension */ // Emil hacking because he can't find a babel plugin that does it for some reason if (!Array.prototype.flatten) { // eslint-disable-next-line Array.prototype.flatten = function flatten() { return this.reduce((acc, cur) => acc.concat(cur), []); }; } import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; import falcor from 'falcor'; import routes from 'routes/admin-routes'; import { injectModelCreateElement } from 'lib/falcor/falcor-utilities'; import { ModalProvider } from 'components/admin/hocs/modals/ModalProvider'; import HttpDataSource from 'falcor-http-datasource'; import { MuiThemeProvider } from 'material-ui'; import { Provider as FalcorProvider } from 'react-falcor'; /** We need to initialize the logger */ import { initializeLogger } from 'lib/logger'; // We start with window.alert as our alert function but later will replace // it with our alert function from ModalProvider initializeLogger(true, window.alert); const clientModel = new falcor.Model({ source: new HttpDataSource('/model.json'), }); ReactDOM.render( <MuiThemeProvider> <FalcorProvider falcor={clientModel}> <ModalProvider> <Router history={browserHistory} routes={routes} createElement={injectModelCreateElement(clientModel)} /> </ModalProvider> </FalcorProvider> </MuiThemeProvider>, document.getElementById('main'), );
packages/material-ui-icons/lib/CloudSharp.js
mbrookes/material-ui
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("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.96z" }), 'CloudSharp'); exports.default = _default;
src/js/components/ui/Banner/Banner.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import styles from './Banner.scss'; export default class Banner extends Component { static propTypes = { onClickHandler: PropTypes.func.isRequired, onSkipHandler : PropTypes.func.isRequired, title : PropTypes.string.isRequired, description : PropTypes.string.isRequired, buttonText : PropTypes.string.isRequired, skipText : PropTypes.string.isRequired, icon : PropTypes.string }; handleClick() { this.props.onClickHandler(); } handleSkip() { this.props.onSkipHandler(); } render() { const {title, description, buttonText, skipText, icon} = this.props; return ( <div className={styles.banner}> <div className={styles.textWrapper} onClick={this.handleClick.bind(this)}> <h2 className={styles.title}>{title}</h2> <p className={styles.description}>{description}</p> </div> {icon ? <span className={styles.icon + ' icon icon-' + icon} onClick={this.handleClick.bind(this)}/> : null } <div className={styles.buttonWrapper} onClick={this.handleClick.bind(this)}> <div className={styles.button}>{buttonText}</div> </div> <div className={styles.skipLink} onClick={this.handleSkip.bind(this)}>{skipText}</div> </div> ); } }
app/webpack/observations/show/containers/map_container.js
calonso-conabio/inaturalist
import { connect } from "react-redux"; import Map from "../components/map"; function mapStateToProps( state ) { return { observation: state.observation, observationPlaces: state.observationPlaces }; } const MapContainer = connect( mapStateToProps )( Map ); export default MapContainer;
src/svg-icons/device/battery-charging-80.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryCharging80 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z"/> </SvgIcon> ); DeviceBatteryCharging80 = pure(DeviceBatteryCharging80); DeviceBatteryCharging80.displayName = 'DeviceBatteryCharging80'; DeviceBatteryCharging80.muiName = 'SvgIcon'; export default DeviceBatteryCharging80;
app/javascript/mastodon/containers/compose_container.js
vahnj/mastodon
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from '../store/configureStore'; import { hydrateStore } from '../actions/store'; import { IntlProvider, addLocaleData } from 'react-intl'; import { getLocale } from '../locales'; import Compose from '../features/standalone/compose'; import initialState from '../initial_state'; const { localeData, messages } = getLocale(); addLocaleData(localeData); const store = configureStore(); if (initialState) { store.dispatch(hydrateStore(initialState)); } export default class TimelineContainer extends React.PureComponent { static propTypes = { locale: PropTypes.string.isRequired, }; render () { const { locale } = this.props; return ( <IntlProvider locale={locale} messages={messages}> <Provider store={store}> <Compose /> </Provider> </IntlProvider> ); } }
src/App/views/Settings/index.js
hajjiTarik/SolarNews
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { ScrollView, StyleSheet } from 'react-native'; import Sites from './components/Sites'; import FontSize from './components/FontSize'; import NotificationAlarm from './components/NotificationAlarm'; import { persist, setActiveSite, setDefaultSettings, setFontSize, setNotificationDate, toggleAlarmAction } from '../../store/actions'; import { getFromStorage } from '../../utils/cacheManager'; import constants from '../../config/appConstants'; class Settings extends Component { constructor(props) { super(props); } async componentWillMount() { const fontSizeCached = await getFromStorage(constants.FONT_SIZE); const notificationDateCached = await getFromStorage(constants.NOTIFICATION_DATE); const sitesCached = await getFromStorage(constants.SITES); this.props.setActiveSite(sitesCached[constants.SITES] || this.props.activeSite); this.props.setFontSize(fontSizeCached[constants.FONT_SIZE] || this.props.fontSize); this.props.setNotificationDate(notificationDateCached[constants.NOTIFICATION_DATE] || this.props.notificationDate); } render() { return ( <ScrollView style={styles.sitesContainer}> <Sites activeSite={this.props.activeSite} setActiveSite={this.props.setActiveSite} persist={this.props.persist} /> <FontSize fontSize={this.props.fontSize} setFontSize={this.props.setFontSize} persist={this.props.persist} /> <NotificationAlarm notificationDate={this.props.notificationDate} setNotificationDate={this.props.setNotificationDate} persist={this.props.persist} toggleAlarm={this.props.toggleAlarm} toggleAlarmAction={this.props.toggleAlarmAction} /> </ScrollView> ) } } const styles = StyleSheet.create({ sitesContainer: { backgroundColor: '#f8f9fa', paddingBottom: 60 } }); const mapStateToProps = ({ appReducer }) => { return { activeSite: appReducer.activeSite, notificationDate: appReducer.notificationDate, fontSize: appReducer.fontSize, toggleAlarm: appReducer.toggleAlarm } }; const mapDispatchToProps = dispatch => { return { setActiveSite: bindActionCreators(setActiveSite, dispatch), setNotificationDate: bindActionCreators(setNotificationDate, dispatch), setFontSize: bindActionCreators(setFontSize, dispatch), persist: bindActionCreators(persist, dispatch), setDefaultSettings: bindActionCreators(setDefaultSettings, dispatch), toggleAlarmAction: bindActionCreators(toggleAlarmAction, dispatch) } }; export default connect(mapStateToProps, mapDispatchToProps)(Settings);
src/svg-icons/content/clear.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let 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 = pure(ContentClear); ContentClear.displayName = 'ContentClear'; ContentClear.muiName = 'SvgIcon'; export default ContentClear;
app/components/Product/index.js
abakusbackup/abacash-client
// @flow import React from 'react'; import Style from './Product.css'; import Products from './Products'; type Props = { product: Object, select: (product: Object) => void, }; const Product = (props: Props) => ( <div className={Style.product} onClick={() => props.select(props.product)} key={props.product.id} > <span className={Style.productName}>{props.product.name}</span> <span className={Style.productPrice}>{props.product.price} kr</span> </div> ); export default Product; export { Products };
modules/RouteContext.js
hgezim/react-router
import React from 'react' const { object } = React.PropTypes /** * The RouteContext mixin provides a convenient way for route * components to set the route in context. This is needed for * routes that render elements that want to use the Lifecycle * mixin to prevent transitions. */ const RouteContext = { propTypes: { route: object.isRequired }, childContextTypes: { route: object.isRequired }, getChildContext() { return { route: this.props.route } } } export default RouteContext
templates/rubix/demo/src/common/timeline.js
jeffthemaximum/jeffline
import React from 'react'; import { Grid, Row, Col, Button, TimelineView, TimelineItem, TimelineBody, TimelineHeader, TimelineAvatar, TimelineTitle, } from '@sketchpixy/rubix'; export default class TimelineComponent extends React.Component { render() { return ( <div> <Grid> <Row> <Col xs={12} collapseLeft collapseRight> <TimelineView className='border-black50 tl-blue'> <TimelineItem> <TimelineHeader> <TimelineAvatar src='/imgs/app/avatars/avatar5.png' className='border-blue' /> <TimelineTitle> Jordyn Ouellet </TimelineTitle> </TimelineHeader> <TimelineBody> <ul> <li> <div> <div className='fg-lightgray'><small><strong>Aug 10, 2014</strong></small></div> <div><small>Sent you a friend request!</small></div> </div> <br/> <div className='text-center'> <Button xs outlined bsStyle='darkgreen45'> Accept </Button>{' '} <Button xs outlined bsStyle='red'> Reject </Button> </div> </li> </ul> </TimelineBody> </TimelineItem> </TimelineView> <TimelineView className='border-black50 tl-green'> <TimelineItem> <TimelineHeader> <TimelineAvatar src='/imgs/app/avatars/avatar7.png' className='border-green' /> <TimelineTitle> Toby King </TimelineTitle> </TimelineHeader> <TimelineBody> <ul> <li> <div className='fg-lightgray'><small><strong>Aug 9, 2014</strong></small></div> <div> <small>Visiting <strong className='fg-darkgreen45'>The Museum of Modern Art</strong> at <strong><em>11 W 53rd St, New York, NY 10019</em></strong></small> </div> <br/> <img src='/imgs/app/staticmap.png' alt='Points of Interest in Lower Manhattan' /> </li> <li> <div className='fg-lightgray'><small><strong>Aug 8, 2014</strong></small></div> <div> <small>Driving through! :)</small> </div> <br/> <img width='155' src='/imgs/app/gallery/tumblr_n7yhe1sTa41st5lhmo1_1280-thumb.jpg' alt='the taxi' /> </li> </ul> </TimelineBody> </TimelineItem> </TimelineView> <TimelineView className='border-black50 tl-yellow'> <TimelineItem> <TimelineHeader> <TimelineAvatar src='/imgs/app/avatars/avatar10.png' className='border-yellow' /> <TimelineTitle> Angelina Mills </TimelineTitle> </TimelineHeader> <TimelineBody> <ul> <li> <div className='fg-lightgray'><small><strong>Aug 8, 2014</strong></small></div> <div> <small>Hey you free tomorrow? Lets go shopping!</small> </div> </li> </ul> </TimelineBody> </TimelineItem> </TimelineView> </Col> </Row> </Grid> </div> ); } }
packages/core/upload/admin/src/components/UploadAssetDialog/AddAssetStep/FromComputerForm.js
wistityhq/strapi
/* eslint-disable jsx-a11y/label-has-associated-control */ import React, { useRef, useState } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { Box } from '@strapi/design-system/Box'; import { Flex } from '@strapi/design-system/Flex'; import { Typography } from '@strapi/design-system/Typography'; import { useTracking } from '@strapi/helper-plugin'; import { ModalFooter } from '@strapi/design-system/ModalLayout'; import { Button } from '@strapi/design-system/Button'; import PicturePlus from '@strapi/icons/PicturePlus'; import { useIntl } from 'react-intl'; import getTrad from '../../../utils/getTrad'; import { rawFileToAsset } from '../../../utils/rawFileToAsset'; import { AssetSource } from '../../../constants'; const Wrapper = styled(Flex)` flex-direction: column; `; const IconWrapper = styled.div` font-size: ${60 / 16}rem; svg path { fill: ${({ theme }) => theme.colors.primary600}; } `; const MediaBox = styled(Box)` border-style: dashed; `; const OpaqueBox = styled(Box)` opacity: 0; cursor: pointer; `; export const FromComputerForm = ({ onClose, onAddAssets, trackedLocation }) => { const { formatMessage } = useIntl(); const [dragOver, setDragOver] = useState(false); const inputRef = useRef(null); const { trackUsage } = useTracking(); const handleDragEnter = () => setDragOver(true); const handleDragLeave = () => setDragOver(false); const handleClick = e => { e.preventDefault(); inputRef.current.click(); }; const handleChange = () => { const files = inputRef.current.files; const assets = []; for (let i = 0; i < files.length; i++) { const file = files.item(i); const asset = rawFileToAsset(file, AssetSource.Computer); assets.push(asset); } if (trackedLocation) { trackUsage('didSelectFile', { source: 'computer', location: trackedLocation }); } onAddAssets(assets); }; const handleDrop = e => { if (e?.dataTransfer?.files) { const files = e.dataTransfer.files; const assets = []; for (let i = 0; i < files.length; i++) { const file = files.item(i); const asset = rawFileToAsset(file, AssetSource.Computer); assets.push(asset); } onAddAssets(assets); } setDragOver(false); }; return ( <form> <Box paddingLeft={8} paddingRight={8} paddingTop={6} paddingBottom={6}> <label> <MediaBox paddingTop={11} paddingBottom={11} hasRadius justifyContent="center" borderColor={dragOver ? 'primary500' : 'neutral300'} background={dragOver ? 'primary100' : 'neutral100'} position="relative" onDragEnter={handleDragEnter} onDragLeave={handleDragLeave} onDrop={handleDrop} > <Flex justifyContent="center"> <Wrapper> <IconWrapper> <PicturePlus aria-hidden /> </IconWrapper> <Box paddingTop={3} paddingBottom={5}> <Typography variant="delta" textColor="neutral600" as="span"> {formatMessage({ id: getTrad('input.label'), defaultMessage: 'Drag & Drop here or', })} </Typography> </Box> <OpaqueBox as="input" position="absolute" left={0} right={0} bottom={0} top={0} width="100%" type="file" multiple name="files" tabIndex={-1} ref={inputRef} zIndex={1} onChange={handleChange} /> <Box position="relative"> <Button type="button" onClick={handleClick}> {formatMessage({ id: getTrad('input.button.label'), defaultMessage: 'Browse files', })} </Button> </Box> </Wrapper> </Flex> </MediaBox> </label> </Box> <ModalFooter startActions={ <Button onClick={onClose} variant="tertiary"> {formatMessage({ id: 'app.components.Button.cancel', defaultMessage: 'cancel', })} </Button> } /> </form> ); }; FromComputerForm.defaultProps = { trackedLocation: undefined, }; FromComputerForm.propTypes = { onClose: PropTypes.func.isRequired, onAddAssets: PropTypes.func.isRequired, trackedLocation: PropTypes.string, };
webApp/src/index.js
s-law/silent-disco
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route } from 'react-router'; import { createHistory } from 'history'; import injectTapEventPlugin from '../node_modules/react-tap-event-plugin'; import App from './App.jsx'; import StreamLive from './Components/StreamLive.js'; import Broadcast from './Components/Broadcast.js'; import BroadcastLive from './Components/BroadcastLive.js'; import BroadcastProfile from './Components/BroadcastProfile.js'; import Login from './Components/Login.js'; import Stream from './Components/Stream.js'; import Landing from './Components/Landing.js'; import auth from './utils/Auth'; // import routes from './config/routes' //Needed for onTouchTap //Can go away when react 1.0 release //Check this repo: //https://github.com/zilverline/react-tap-event-plugin injectTapEventPlugin(); function redirectToLogin(nextState, replace) { if (!auth.isAuth()) { replace({ nextPathname: nextState.location.pathname }, '/login') } } var routes = ( <Router history={createHistory()}> <Route path="/" component={Landing}/> <Route path="/listen" component={Stream}/> <Route path="/listen/:streamId" component={StreamLive}/> <Route path='/broadcast/setup' onEnter={redirectToLogin} component={Broadcast}/> <Route path='/broadcast/:streamId' onEnter={redirectToLogin} component={BroadcastLive}/> <Route path='/user/:userId' onEnter={redirectToLogin} component={BroadcastProfile}/> <Route path='/login' component={Login}/> </Router> ) ReactDOM.render(routes, document.getElementById('root')); // ReactDOM.render(<Router history={createHistory()} routes={routes}/>, document.getElementById('root'));
src/svg-icons/av/skip-next.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSkipNext = (props) => ( <SvgIcon {...props}> <path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/> </SvgIcon> ); AvSkipNext = pure(AvSkipNext); AvSkipNext.displayName = 'AvSkipNext'; AvSkipNext.muiName = 'SvgIcon'; export default AvSkipNext;
ajax/libs/golden-layout/1.5.6/goldenlayout.js
seogi1004/cdnjs
(function($){var lm={"config":{},"container":{},"controls":{},"errors":{},"items":{},"utils":{}}; lm.utils.F = function () {}; lm.utils.extend = function( subClass, superClass ) { subClass.prototype = lm.utils.createObject( superClass.prototype ); subClass.prototype.contructor = subClass; }; lm.utils.createObject = function( prototype ) { if( typeof Object.create === 'function' ) { return Object.create( prototype ); } else { lm.utils.F.prototype = prototype; return new lm.utils.F(); } }; lm.utils.objectKeys = function( object ) { var keys, key; if( typeof Object.keys === 'function' ) { return Object.keys( object ); } else { keys = []; for( key in object ) { keys.push( key ); } return keys; } }; lm.utils.getQueryStringParam = function( param ) { if( !window.location.search ) { return null; } var keyValuePairs = window.location.search.substr( 1 ).split( '&' ), params = {}, pair, i; for( i = 0; i < keyValuePairs.length; i++ ) { pair = keyValuePairs[ i ].split( '=' ); params[ pair[ 0 ] ] = pair[ 1 ]; } return params[ param ] || null; }; lm.utils.copy = function( target, source ) { for( var key in source ) { target[ key ] = source[ key ]; } return target; }; /** * This is based on Paul Irish's shim, but looks quite odd in comparison. Why? * Because * a) it shouldn't affect the global requestAnimationFrame function * b) it shouldn't pass on the time that has passed * * @param {Function} fn * * @returns {void} */ lm.utils.animFrame = function( fn ){ return ( window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); })(function(){ fn(); }); }; lm.utils.indexOf = function( needle, haystack ) { if( !( haystack instanceof Array ) ) { throw new Error( 'Haystack is not an Array' ); } if( haystack.indexOf ) { return haystack.indexOf( needle ); } else { for( var i = 0; i < haystack.length; i++ ) { if( haystack[ i ] === needle ) { return i; } } return -1; } }; if ( typeof /./ != 'function' && typeof Int8Array != 'object' ) { lm.utils.isFunction = function ( obj ) { return typeof obj == 'function' || false; }; } else { lm.utils.isFunction = function ( obj ) { return toString.call(obj) === '[object Function]'; }; } lm.utils.fnBind = function( fn, context, boundArgs ) { if( Function.prototype.bind !== undefined ) { return Function.prototype.bind.apply( fn, [ context ].concat( boundArgs || [] ) ); } var bound = function () { // Join the already applied arguments to the now called ones (after converting to an array again). var args = ( boundArgs || [] ).concat(Array.prototype.slice.call(arguments, 0)); // If not being called as a constructor if (!(this instanceof bound)){ // return the result of the function called bound to target and partially applied. return fn.apply(context, args); } // If being called as a constructor, apply the function bound to self. fn.apply(this, args); }; // Attach the prototype of the function to our newly created function. bound.prototype = fn.prototype; return bound; }; lm.utils.removeFromArray = function( item, array ) { var index = lm.utils.indexOf( item, array ); if( index === -1 ) { throw new Error( 'Can\'t remove item from array. Item is not in the array' ); } array.splice( index, 1 ); }; lm.utils.now = function() { if( typeof Date.now === 'function' ) { return Date.now(); } else { return ( new Date() ).getTime(); } }; lm.utils.getUniqueId = function() { return ( Math.random() * 1000000000000000 ) .toString(36) .replace( '.', '' ); }; /** * A basic XSS filter. It is ultimately up to the * implementing developer to make sure their particular * applications and usecases are save from cross site scripting attacks * * @param {String} input * @param {Boolean} keepTags * * @returns {String} filtered input */ lm.utils.filterXss = function( input, keepTags ) { var output = input .replace( /javascript/gi, 'j&#97;vascript' ) .replace( /expression/gi, 'expr&#101;ssion' ) .replace( /onload/gi, 'onlo&#97;d' ) .replace( /script/gi, '&#115;cript' ) .replace( /onerror/gi, 'on&#101;rror' ); if( keepTags === true ) { return output; } else { return output .replace( />/g, '&gt;' ) .replace( /</g, '&lt;' ); } }; /** * Removes html tags from a string * * @param {String} input * * @returns {String} input without tags */ lm.utils.stripTags = function( input ) { return $.trim( input.replace( /(<([^>]+)>)/ig, '' ) ); }; /** * A generic and very fast EventEmitter * implementation. On top of emitting the * actual event it emits an * * lm.utils.EventEmitter.ALL_EVENT * * event for every event triggered. This allows * to hook into it and proxy events forwards * * @constructor */ lm.utils.EventEmitter = function() { this._mSubscriptions = { }; this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ] = []; /** * Listen for events * * @param {String} sEvent The name of the event to listen to * @param {Function} fCallback The callback to execute when the event occurs * @param {[Object]} oContext The value of the this pointer within the callback function * * @returns {void} */ this.on = function( sEvent, fCallback, oContext ) { if ( !lm.utils.isFunction(fCallback) ) { throw new Error( 'Tried to listen to event ' + sEvent + ' with non-function callback ' + fCallback ); } if( !this._mSubscriptions[ sEvent ] ) { this._mSubscriptions[ sEvent ] = []; } this._mSubscriptions[ sEvent ].push({ fn: fCallback, ctx: oContext }); }; /** * Emit an event and notify listeners * * @param {String} sEvent The name of the event * @param {Mixed} various additional arguments that will be passed to the listener * * @returns {void} */ this.emit = function( sEvent ) { var i, ctx, args; args = Array.prototype.slice.call( arguments, 1 ); if( this._mSubscriptions[ sEvent ] ) { for( i = 0; i < this._mSubscriptions[ sEvent ].length; i++ ) { ctx = this._mSubscriptions[ sEvent ][ i ].ctx || {}; this._mSubscriptions[ sEvent ][ i ].fn.apply( ctx, args ); } } args.unshift( sEvent ); for( i = 0; i < this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ].length; i++ ) { ctx = this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ][ i ].ctx || {}; this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ][ i ].fn.apply( ctx, args ); } }; /** * Removes a listener for an event, or all listeners if no callback and context is provided. * * @param {String} sEvent The name of the event * @param {Function} fCallback The previously registered callback method (optional) * @param {Object} oContext The previously registered context (optional) * * @returns {void} */ this.unbind = function( sEvent, fCallback, oContext ) { if( !this._mSubscriptions[ sEvent ] ) { throw new Error( 'No subscribtions to unsubscribe for event ' + sEvent ); } var i, bUnbound = false; for( i = 0; i < this._mSubscriptions[ sEvent ].length; i++ ) { if ( ( !fCallback || this._mSubscriptions[ sEvent ][ i ].fn === fCallback ) && ( !oContext || oContext === this._mSubscriptions[ sEvent ][ i ].ctx ) ) { this._mSubscriptions[ sEvent ].splice( i, 1 ); bUnbound = true; } } if( bUnbound === false ) { throw new Error( 'Nothing to unbind for ' + sEvent ); } }; /** * Alias for unbind */ this.off = this.unbind; /** * Alias for emit */ this.trigger = this.emit; }; /** * The name of the event that's triggered for every other event * * usage * * myEmitter.on( lm.utils.EventEmitter.ALL_EVENT, function( eventName, argsArray ){ * //do stuff * }); * * @type {String} */ lm.utils.EventEmitter.ALL_EVENT = '__all'; lm.utils.DragListener = function(eElement, nButtonCode) { lm.utils.EventEmitter.call(this); this._eElement = $(eElement); this._oDocument = $(document); this._eBody = $(document.body); this._nButtonCode = nButtonCode || 0; /** * The delay after which to start the drag in milliseconds */ this._nDelay = 200; /** * The distance the mouse needs to be moved to qualify as a drag */ this._nDistance = 10;//TODO - works better with delay only this._nX = 0; this._nY = 0; this._nOriginalX = 0; this._nOriginalY = 0; this._bDragging = false; this._fMove = lm.utils.fnBind( this.onMouseMove, this ); this._fUp = lm.utils.fnBind( this.onMouseUp, this ); this._fDown = lm.utils.fnBind( this.onMouseDown, this ); this._eElement.on( 'mousedown touchstart', this._fDown ); }; lm.utils.DragListener.timeout = null; lm.utils.copy( lm.utils.DragListener.prototype, { destroy: function() { this._eElement.unbind( 'mousedown touchstart', this._fDown ); }, onMouseDown: function(oEvent) { oEvent.preventDefault(); if (oEvent.button == 0) { var coordinates = this._getCoordinates( oEvent ); this._nOriginalX = coordinates.x; this._nOriginalY = coordinates.y; this._oDocument.on( 'mousemove touchmove', this._fMove ); this._oDocument.one( 'mouseup touchend', this._fUp ); this._timeout = setTimeout( lm.utils.fnBind( this._startDrag, this ), this._nDelay ); } }, onMouseMove: function(oEvent) { if (this._timeout != null) { oEvent.preventDefault(); var coordinates = this._getCoordinates(oEvent); this._nX = coordinates.x - this._nOriginalX; this._nY = coordinates.y - this._nOriginalY; if (this._bDragging === false) { if ( Math.abs(this._nX) > this._nDistance || Math.abs(this._nY) > this._nDistance ) { clearTimeout(this._timeout); this._startDrag(); } } if (this._bDragging) { this.emit('drag', this._nX, this._nY, oEvent); } } }, onMouseUp: function(oEvent) { if(this._timeout != null) { clearTimeout( this._timeout ); this._eBody.removeClass( 'lm_dragging' ); this._eElement.removeClass( 'lm_dragging' ); this._oDocument.find( 'iframe' ).css( 'pointer-events', '' ); this._oDocument.unbind( 'mousemove touchmove', this._fMove ); if( this._bDragging === true ) { this._bDragging = false; this.emit( 'dragStop', oEvent, this._nOriginalX + this._nX ); } } }, _startDrag: function() { this._bDragging = true; this._eBody.addClass( 'lm_dragging' ); this._eElement.addClass( 'lm_dragging' ); this._oDocument.find( 'iframe' ).css( 'pointer-events', 'none' ); this.emit('dragStart', this._nOriginalX, this._nOriginalY); }, _getCoordinates: function( event ) { var coordinates = {}; if( event.type.substr( 0, 5 ) === 'touch' ) { coordinates.x = event.originalEvent.targetTouches[ 0 ].pageX; coordinates.y = event.originalEvent.targetTouches[ 0 ].pageY; } else { coordinates.x = event.pageX; coordinates.y = event.pageY; } return coordinates; } }); /** * The main class that will be exposed as GoldenLayout. * * @public * @constructor * @param {GoldenLayout config} config * @param {[DOM element container]} container Can be a jQuery selector string or a Dom element. Defaults to body * * @returns {VOID} */ lm.LayoutManager = function( config, container ) { if( !$ || typeof $.noConflict !== 'function' ) { var errorMsg = 'jQuery is missing as dependency for GoldenLayout. '; errorMsg += 'Please either expose $ on GoldenLayout\'s scope (e.g. window) or add "jquery" to '; errorMsg += 'your paths when using RequireJS/AMD'; throw new Error( errorMsg ); } lm.utils.EventEmitter.call( this ); this.isInitialised = false; this._isFullPage = false; this._resizeTimeoutId = null; this._components = { 'lm-react-component': lm.utils.ReactComponentHandler }; this._itemAreas = []; this._resizeFunction = lm.utils.fnBind( this._onResize, this ); this._unloadFunction = lm.utils.fnBind( this._onUnload, this ); this._maximisedItem = null; this._maximisePlaceholder = $( '<div class="lm_maximise_place"></div>' ); this._creationTimeoutPassed = false; this._subWindowsCreated = false; this.width = null; this.height = null; this.root = null; this.openPopouts = []; this.selectedItem = null; this.isSubWindow = false; this.eventHub = new lm.utils.EventHub( this ); this.config = this._createConfig( config ); this.container = container; this.dropTargetIndicator = null; this.transitionIndicator = null; this.tabDropPlaceholder = $( '<div class="lm_drop_tab_placeholder"></div>' ); if( this.isSubWindow === true ) { $( 'body' ).css( 'visibility', 'hidden' ); } this._typeToItem = { 'column': lm.utils.fnBind( lm.items.RowOrColumn, this, [ true ] ), 'row': lm.utils.fnBind( lm.items.RowOrColumn, this, [ false ] ), 'stack': lm.items.Stack, 'component': lm.items.Component }; }; /** * Hook that allows to access private classes */ lm.LayoutManager.__lm = lm; /** * Takes a GoldenLayout configuration object and * replaces its keys and values recursively with * one letter codes * * @static * @public * @param {Object} config A GoldenLayout config object * * @returns {Object} minified config */ lm.LayoutManager.minifyConfig = function( config ) { return ( new lm.utils.ConfigMinifier() ).minifyConfig( config ); }; /** * Takes a configuration Object that was previously minified * using minifyConfig and returns its original version * * @static * @public * @param {Object} minifiedConfig * * @returns {Object} the original configuration */ lm.LayoutManager.unminifyConfig = function( config ) { return ( new lm.utils.ConfigMinifier() ).unminifyConfig( config ); }; lm.utils.copy( lm.LayoutManager.prototype, { /** * Register a component with the layout manager. If a configuration node * of type component is reached it will look up componentName and create the * associated component * * { * type: "component", * componentName: "EquityNewsFeed", * componentState: { "feedTopic": "us-bluechips" } * } * * @public * @param {String} name * @param {Function} constructor * * @returns {void} */ registerComponent: function( name, constructor ) { if( typeof constructor !== 'function' ) { throw new Error( 'Please register a constructor function' ); } if( this._components[ name ] !== undefined ) { throw new Error( 'Component ' + name + ' is already registered' ); } this._components[ name ] = constructor; }, /** * Creates a layout configuration object based on the the current state * * @public * @returns {Object} GoldenLayout configuration */ toConfig: function( root ) { var config, next, i; if( this.isInitialised === false ) { throw new Error( 'Can\'t create config, layout not yet initialised' ); } if( root && !( root instanceof lm.items.AbstractContentItem ) ){ throw new Error( 'Root must be a ContentItem' ); } /* * settings & labels */ config = { settings: lm.utils.copy( {}, this.config.settings ), dimensions: lm.utils.copy( {}, this.config.dimensions ), labels: lm.utils.copy( {}, this.config.labels ) }; /* * Content */ config.content = []; next = function( configNode, item ) { var key, i; for( key in item.config ) { if( key !== 'content' ) { configNode[ key ] = item.config[ key ]; } } if( item.contentItems.length ) { configNode.content = []; for( i = 0; i < item.contentItems.length; i++ ) { configNode.content[ i ] = {}; next( configNode.content[ i ], item.contentItems[ i ] ); } } }; if( root ) { next( config, { contentItems: [ root ] } ); } else { next( config, this.root ); } /* * Retrieve config for subwindows */ this._$reconcilePopoutWindows(); config.openPopouts = []; for( i = 0; i < this.openPopouts.length; i++ ) { config.openPopouts.push( this.openPopouts[ i ].toConfig() ); } /* * Add maximised item */ config.maximisedItemId = this._maximisedItem ? '__glMaximised' : null; return config; }, /** * Returns a previously registered component * * @public * @param {String} name The name used * * @returns {Function} */ getComponent: function( name ) { if( this._components[ name ] === undefined ) { throw new lm.errors.ConfigurationError( 'Unknown component "' + name + '"' ); } return this._components[ name ]; }, /** * Creates the actual layout. Must be called after all initial components * are registered. Recurses through the configuration and sets up * the item tree. * * If called before the document is ready it adds itself as a listener * to the document.ready event * * @public * * @returns {void} */ init: function() { /** * Create the popout windows straight away. If popouts are blocked * an error is thrown on the same 'thread' rather than a timeout and can * be caught. This also prevents any further initilisation from taking place. */ if( this._subWindowsCreated === false ) { this._createSubWindows(); this._subWindowsCreated = true; } /** * If the document isn't ready yet, wait for it. */ if( document.readyState === 'loading' || document.body === null ) { $(document).ready( lm.utils.fnBind( this.init, this )); return; } /** * If this is a subwindow, wait a few milliseconds for the original * page's js calls to be executed, then replace the bodies content * with GoldenLayout */ if( this.isSubWindow === true && this._creationTimeoutPassed === false ) { setTimeout( lm.utils.fnBind( this.init, this ), 7 ); this._creationTimeoutPassed = true; return; } if( this.isSubWindow === true ) { this._adjustToWindowMode(); } this._setContainer(); this.dropTargetIndicator = new lm.controls.DropTargetIndicator( this.container ); this.transitionIndicator = new lm.controls.TransitionIndicator(); this.updateSize(); this._create( this.config ); this._bindEvents(); this.isInitialised = true; this.emit( 'initialised' ); }, /** * Updates the layout managers size * * @public * @param {[int]} width height in pixels * @param {[int]} height width in pixels * * @returns {void} */ updateSize: function( width, height ) { if( arguments.length === 2 ) { this.width = width; this.height = height; } else { this.width = this.container.width(); this.height = this.container.height(); } if( this.isInitialised === true ) { this.root.callDownwards( 'setSize' ); if( this._maximisedItem ) { this._maximisedItem.element.width( this.container.width() ); this._maximisedItem.element.height( this.container.height() ); this._maximisedItem.callDownwards( 'setSize' ); } } }, /** * Destroys the LayoutManager instance itself as well as every ContentItem * within it. After this is called nothing should be left of the LayoutManager. * * @public * @returns {void} */ destroy: function() { if( this.isInitialised === false ) { return; } this._onUnload(); $( window ).off( 'resize', this._resizeFunction ); $( window ).off( 'unload beforeunload', this._unloadFunction ); this.root.callDownwards( '_$destroy', [], true ); this.root.contentItems = []; this.tabDropPlaceholder.remove(); this.dropTargetIndicator.destroy(); this.transitionIndicator.destroy(); this.eventHub.destroy(); }, /** * Recursively creates new item tree structures based on a provided * ItemConfiguration object * * @public * @param {Object} config ItemConfig * @param {[ContentItem]} parent The item the newly created item should be a child of * * @returns {lm.items.ContentItem} */ createContentItem: function( config, parent ) { var typeErrorMsg, contentItem; if( typeof config.type !== 'string' ) { throw new lm.errors.ConfigurationError( 'Missing parameter \'type\'', config ); } if (config.type === 'react-component') { config.type = 'component'; config.componentName = 'lm-react-component'; } if( !this._typeToItem[ config.type ] ) { typeErrorMsg = 'Unknown type \'' + config.type + '\'. ' + 'Valid types are ' + lm.utils.objectKeys( this._typeToItem ).join( ',' ); throw new lm.errors.ConfigurationError( typeErrorMsg ); } /** * We add an additional stack around every component that's not within a stack anyways. */ if( // If this is a component config.type === 'component' && // and it's not already within a stack !( parent instanceof lm.items.Stack ) && // and we have a parent !!parent && // and it's not the topmost item in a new window !( this.isSubWindow === true && parent instanceof lm.items.Root ) ) { config = { type: 'stack', width: config.width, height: config.height, content: [ config ] }; } contentItem = new this._typeToItem[ config.type ]( this, config, parent ); return contentItem; }, /** * Creates a popout window with the specified content and dimensions * * @param {Object|lm.itemsAbstractContentItem} configOrContentItem * @param {[Object]} dimensions A map with width, height, left and top * @param {[String]} parentId the id of the element this item will be appended to * when popIn is called * @param {[Number]} indexInParent The position of this item within its parent element * @returns {lm.controls.BrowserPopout} */ createPopout: function( configOrContentItem, dimensions, parentId, indexInParent ) { var config = configOrContentItem, isItem = configOrContentItem instanceof lm.items.AbstractContentItem, self = this, windowLeft, windowTop, offset, parent, child, browserPopout; parentId = parentId || null; if( isItem ) { config = this.toConfig( configOrContentItem ).content; parentId = lm.utils.getUniqueId(); /** * If the item is the only component within a stack or for some * other reason the only child of its parent the parent will be destroyed * when the child is removed. * * In order to support this we move up the tree until we find something * that will remain after the item is being popped out */ parent = configOrContentItem.parent; child = configOrContentItem; while( parent.contentItems.length === 1 && !parent.isRoot ) { parent = parent.parent; child = child.parent; } parent.addId( parentId ); if( isNaN( indexInParent ) ) { indexInParent = lm.utils.indexOf( child, parent.contentItems ); } } else { if( !( config instanceof Array ) ) { config = [ config ]; } } if( !dimensions && isItem ) { windowLeft = window.screenX || window.screenLeft; windowTop = window.screenY || window.screenTop; offset = configOrContentItem.element.offset(); dimensions = { left: windowLeft + offset.left, top: windowTop + offset.top, width: configOrContentItem.element.width(), height: configOrContentItem.element.height() }; } if( !dimensions && !isItem ) { dimensions = { left: window.screenX || window.screenLeft + 20, top: window.screenY || window.screenTop + 20, width: 500, height: 309 }; } if( isItem ) { configOrContentItem.remove(); } browserPopout = new lm.controls.BrowserPopout( config, dimensions, parentId, indexInParent, this ); browserPopout.on( 'initialised', function(){ self.emit( 'windowOpened', browserPopout ); }); browserPopout.on( 'closed', function(){ self._$reconcilePopoutWindows(); }); this.openPopouts.push( browserPopout ); return browserPopout; }, /** * Attaches DragListener to any given DOM element * and turns it into a way of creating new ContentItems * by 'dragging' the DOM element into the layout * * @param {jQuery DOM element} element * @param {Object|Function} itemConfig for the new item to be created, or a function which will provide it * * @returns {void} */ createDragSource: function( element, itemConfig ) { this.config.settings.constrainDragToContainer = false; new lm.controls.DragSource( $( element ), itemConfig, this ); }, /** * Programmatically selects an item. This deselects * the currently selected item, selects the specified item * and emits a selectionChanged event * * @param {lm.item.AbstractContentItem} item# * @param {[Boolean]} _$silent Wheather to notify the item of its selection * @event selectionChanged * * @returns {VOID} */ selectItem: function( item, _$silent ) { if( this.config.settings.selectionEnabled !== true ) { throw new Error( 'Please set selectionEnabled to true to use this feature' ); } if( item === this.selectedItem ) { return; } if( this.selectedItem !== null ) { this.selectedItem.deselect(); } if( item && _$silent !== true ) { item.select(); } this.selectedItem = item; this.emit( 'selectionChanged', item ); }, /************************* * PACKAGE PRIVATE *************************/ _$maximiseItem: function( contentItem ) { if( this._maximisedItem !== null ) { this._$minimiseItem( this._maximisedItem ); } this._maximisedItem = contentItem; this._maximisedItem.addId( '__glMaximised' ); contentItem.element.addClass( 'lm_maximised' ); contentItem.element.after( this._maximisePlaceholder ); this.root.element.prepend( contentItem.element ); contentItem.element.width( this.container.width() ); contentItem.element.height( this.container.height() ); contentItem.callDownwards( 'setSize' ); this._maximisedItem.emit( 'maximised' ); this.emit( 'stateChanged' ); }, _$minimiseItem: function( contentItem ) { contentItem.element.removeClass( 'lm_maximised' ); contentItem.removeId( '__glMaximised' ); this._maximisePlaceholder.after( contentItem.element ); this._maximisePlaceholder.remove(); contentItem.parent.callDownwards( 'setSize' ); this._maximisedItem = null; contentItem.emit( 'minimised' ); this.emit( 'stateChanged' ); }, /** * This method is used to get around sandboxed iframe restrictions. * If 'allow-top-navigation' is not specified in the iframe's 'sandbox' attribute * (as is the case with codepens) the parent window is forbidden from calling certain * methods on the child, such as window.close() or setting document.location.href. * * This prevented GoldenLayout popouts from popping in in codepens. The fix is to call * _$closeWindow on the child window's gl instance which (after a timeout to disconnect * the invoking method from the close call) closes itself. * * @packagePrivate * * @returns {void} */ _$closeWindow: function() { window.setTimeout(function(){ window.close(); }, 1); }, _$getArea: function( x, y ) { var i, area, smallestSurface = Infinity, mathingArea = null; for( i = 0; i < this._itemAreas.length; i++ ) { area = this._itemAreas[ i ]; if( x > area.x1 && x < area.x2 && y > area.y1 && y < area.y2 && smallestSurface > area.surface ){ smallestSurface = area.surface; mathingArea = area; } } return mathingArea; }, _$calculateItemAreas: function() { var i, area, allContentItems = this._getAllContentItems(); this._itemAreas = []; /** * If the last item is dragged out, highlight the entire container size to * allow to re-drop it. allContentItems[ 0 ] === this.root at this point * * Don't include root into the possible drop areas though otherwise since it * will used for every gap in the layout, e.g. splitters */ if( allContentItems.length === 1 ) { this._itemAreas.push( this.root._$getArea() ); return; } for( i = 0; i < allContentItems.length; i++ ) { if( !( allContentItems[ i ].isStack ) ) { continue; } area = allContentItems[ i ]._$getArea(); if( area === null ) { continue; } else if( area instanceof Array ) { this._itemAreas = this._itemAreas.concat( area ); } else { this._itemAreas.push( area ); } } }, /** * Takes a contentItem or a configuration and optionally a parent * item and returns an initialised instance of the contentItem. * If the contentItem is a function, it is first called * * @packagePrivate * * @param {lm.items.AbtractContentItem|Object|Function} contentItemOrConfig * @param {lm.items.AbtractContentItem} parent Only necessary when passing in config * * @returns {lm.items.AbtractContentItem} */ _$normalizeContentItem: function( contentItemOrConfig, parent ) { if( !contentItemOrConfig ) { throw new Error( 'No content item defined' ); } if( lm.utils.isFunction( contentItemOrConfig ) ) { contentItemOrConfig = contentItemOrConfig(); } if( contentItemOrConfig instanceof lm.items.AbstractContentItem ) { return contentItemOrConfig; } if( $.isPlainObject( contentItemOrConfig ) && contentItemOrConfig.type ) { var newContentItem = this.createContentItem( contentItemOrConfig, parent ); newContentItem.callDownwards( '_$init' ); return newContentItem; } else { throw new Error( 'Invalid contentItem' ); } }, /** * Iterates through the array of open popout windows and removes the ones * that are effectively closed. This is necessary due to the lack of reliably * listening for window.close / unload events in a cross browser compatible fashion. * * @packagePrivate * * @returns {void} */ _$reconcilePopoutWindows: function() { var openPopouts = [], i; for( i = 0; i < this.openPopouts.length; i++ ) { if( this.openPopouts[ i ].getWindow().closed === false ) { openPopouts.push( this.openPopouts[ i ] ); } else { this.emit( 'windowClosed', this.openPopouts[ i ] ); } } if( this.openPopouts.length !== openPopouts.length ) { this.emit( 'stateChanged' ); this.openPopouts = openPopouts; } }, /*************************** * PRIVATE ***************************/ /** * Returns a flattened array of all content items, * regardles of level or type * * @private * * @returns {void} */ _getAllContentItems: function() { var allContentItems = []; var addChildren = function( contentItem ) { allContentItems.push( contentItem ); if( contentItem.contentItems instanceof Array ) { for( var i = 0; i < contentItem.contentItems.length; i++ ) { addChildren( contentItem.contentItems[ i ] ); } } }; addChildren( this.root ); return allContentItems; }, /** * Binds to DOM/BOM events on init * * @private * * @returns {void} */ _bindEvents: function() { if( this._isFullPage ) { $(window).resize( this._resizeFunction ); } $(window).on( 'unload beforeunload', this._unloadFunction ); }, /** * Debounces resize events * * @private * * @returns {void} */ _onResize: function() { clearTimeout( this._resizeTimeoutId ); this._resizeTimeoutId = setTimeout(lm.utils.fnBind( this.updateSize, this ), 100 ); }, /** * Extends the default config with the user specific settings and applies * derivations. Please note that there's a seperate method (AbstractContentItem._extendItemNode) * that deals with the extension of item configs * * @param {Object} config * @static * @returns {Object} config */ _createConfig: function( config ) { var windowConfigKey = lm.utils.getQueryStringParam( 'gl-window' ); if( windowConfigKey ) { this.isSubWindow = true; config = localStorage.getItem( windowConfigKey ); config = JSON.parse( config ); config = ( new lm.utils.ConfigMinifier() ).unminifyConfig( config ); localStorage.removeItem( windowConfigKey ); } config = $.extend( true, {}, lm.config.defaultConfig, config ); var nextNode = function( node ) { for( var key in node ) { if( key !== 'props' && typeof node[ key ] === 'object' ) { nextNode( node[ key ] ); } else if( key === 'type' && node[ key ] === 'react-component' ) { node.type = 'component'; node.componentName = 'lm-react-component'; } } } nextNode( config ); if( config.settings.hasHeaders === false ) { config.dimensions.headerHeight = 0; } return config; }, /** * This is executed when GoldenLayout detects that it is run * within a previously opened popout window. * * @private * * @returns {void} */ _adjustToWindowMode: function() { var popInButton = $( '<div class="lm_popin" title="' + this.config.labels.popin + '">' + '<div class="lm_icon"></div>' + '<div class="lm_bg"></div>' + '</div>'); popInButton.click(lm.utils.fnBind(function(){ this.emit( 'popIn' ); }, this)); document.title = lm.utils.stripTags( this.config.content[ 0 ].title ); $( 'head' ).append( $( 'body link, body style, template, .gl_keep' ) ); this.container = $( 'body' ) .html( '' ) .css( 'visibility', 'visible' ) .append( popInButton ); /* * This seems a bit pointless, but actually causes a reflow/re-evaluation getting around * slickgrid's "Cannot find stylesheet." bug in chrome */ var x = document.body.offsetHeight; // jshint ignore:line /* * Expose this instance on the window object * to allow the opening window to interact with * it */ window.__glInstance = this; }, /** * Creates Subwindows (if there are any). Throws an error * if popouts are blocked. * * @returns {void} */ _createSubWindows: function() { var i, popout; for( i = 0; i < this.config.openPopouts.length; i++ ) { popout = this.config.openPopouts[ i ]; this.createPopout( popout.content, popout.dimensions, popout.parentId, popout.indexInParent ); } }, /** * Determines what element the layout will be created in * * @private * * @returns {void} */ _setContainer: function() { var container = $( this.container || 'body' ); if( container.length === 0 ) { throw new Error( 'GoldenLayout container not found' ); } if( container.length > 1 ) { throw new Error( 'GoldenLayout more than one container element specified' ); } if( container[ 0 ] === document.body ) { this._isFullPage = true; $( 'html, body' ).css({ height: '100%', margin:0, padding: 0, overflow: 'hidden' }); } this.container = container; }, /** * Kicks of the initial, recursive creation chain * * @param {Object} config GoldenLayout Config * * @returns {void} */ _create: function( config ) { var errorMsg; if( !( config.content instanceof Array ) ) { if( config.content === undefined ) { errorMsg = 'Missing setting \'content\' on top level of configuration'; } else { errorMsg = 'Configuration parameter \'content\' must be an array'; } throw new lm.errors.ConfigurationError( errorMsg, config ); } if( config.content.length > 1 ) { errorMsg = 'Top level content can\'t contain more then one element.'; throw new lm.errors.ConfigurationError( errorMsg, config ); } this.root = new lm.items.Root( this, { content: config.content }, this.container ); this.root.callDownwards( '_$init' ); if( config.maximisedItemId === '__glMaximised' ) { this.root.getItemsById( config.maximisedItemId )[ 0 ].toggleMaximise(); } }, /** * Called when the window is closed or the user navigates away * from the page * * @returns {void} */ _onUnload: function() { if( this.config.settings.closePopoutsOnUnload === true ) { for( var i = 0; i < this.openPopouts.length; i++ ) { this.openPopouts[ i ].close(); } } } }); /** * Expose the Layoutmanager as the single entrypoint using UMD */ (function () { /* global define */ if ( typeof define === 'function' && define.amd) { define([ 'jquery' ], function( jquery ){ $ = jquery; return lm.LayoutManager; }); // jshint ignore:line } else if (typeof exports === 'object') { module.exports = lm.LayoutManager; } else { window.GoldenLayout = lm.LayoutManager; } })(); lm.config.itemDefaultConfig = { isClosable: true, reorderEnabled: true, title: '' }; lm.config.defaultConfig = { openPopouts:[], settings:{ hasHeaders: true, constrainDragToContainer: true, reorderEnabled: true, selectionEnabled: false, popoutWholeStack: false, blockedPopoutsThrowError: true, closePopoutsOnUnload: true, showPopoutIcon: true, showMaximiseIcon: true, showCloseIcon: true }, dimensions: { borderWidth: 5, minItemHeight: 10, minItemWidth: 10, headerHeight: 20, dragProxyWidth: 300, dragProxyHeight: 200 }, labels: { close: 'close', maximise: 'maximise', minimise: 'minimise', popout: 'open in new window', popin: 'pop in' } }; lm.container.ItemContainer = function( config, parent, layoutManager ) { lm.utils.EventEmitter.call( this ); this.width = null; this.height = null; this.title = config.componentName; this.parent = parent; this.layoutManager = layoutManager; this.isHidden = false; this._config = config; this._element = $([ '<div class="lm_item_container">', '<div class="lm_content"></div>', '</div>' ].join( '' )); this._contentElement = this._element.find( '.lm_content' ); }; lm.utils.copy( lm.container.ItemContainer.prototype, { /** * Get the inner DOM element the container's content * is intended to live in * * @returns {DOM element} */ getElement: function() { return this._contentElement; }, /** * Hide the container. Notifies the containers content first * and then hides the DOM node. If the container is already hidden * this should have no effect * * @returns {void} */ hide: function() { this.emit( 'hide' ); this.isHidden = true; this._element.hide(); }, /** * Shows a previously hidden container. Notifies the * containers content first and then shows the DOM element. * If the container is already visible this has no effect. * * @returns {void} */ show: function() { this.emit( 'show' ); this.isHidden = false; this._element.show(); // call shown only if the container has a valid size if(this.height != 0 || this.width != 0) { this.emit( 'shown' ); } }, /** * Set the size from within the container. Traverses up * the item tree until it finds a row or column element * and resizes its items accordingly. * * If this container isn't a descendant of a row or column * it returns false * @todo Rework!!! * @param {Number} width The new width in pixel * @param {Number} height The new height in pixel * * @returns {Boolean} resizeSuccesful */ setSize: function( width, height ) { var rowOrColumn = this.parent, rowOrColumnChild = this, totalPixel, percentage, direction, newSize, delta, i; while( !rowOrColumn.isColumn && !rowOrColumn.isRow ) { rowOrColumnChild = rowOrColumn; rowOrColumn = rowOrColumn.parent; /** * No row or column has been found */ if( rowOrColumn.isRoot ) { return false; } } direction = rowOrColumn.isColumn ? "height" : "width"; newSize = direction === "height" ? height : width; totalPixel = this[direction] * ( 1 / ( rowOrColumnChild.config[direction] / 100 ) ); percentage = ( newSize / totalPixel ) * 100; delta = ( rowOrColumnChild.config[direction] - percentage ) / rowOrColumn.contentItems.length; for( i = 0; i < rowOrColumn.contentItems.length; i++ ) { if( rowOrColumn.contentItems[ i ] === rowOrColumnChild ) { rowOrColumn.contentItems[ i ].config[direction] = percentage; } else { rowOrColumn.contentItems[ i ].config[direction] += delta; } } rowOrColumn.callDownwards( 'setSize' ); return true; }, /** * Closes the container if it is closable. Can be called by * both the component within at as well as the contentItem containing * it. Emits a close event before the container itself is closed. * * @returns {void} */ close: function() { if( this._config.isClosable ) { this.emit( 'close' ); this.parent.close(); } }, /** * Returns the current state object * * @returns {Object} state */ getState: function() { return this._config.componentState; }, /** * Merges the provided state into the current one * * @param {Object} state * * @returns {void} */ extendState: function( state ) { this.setState( $.extend( true, this.getState(), state ) ); }, /** * Notifies the layout manager of a stateupdate * * @param {serialisable} state */ setState: function( state ) { this._config.componentState = state; this.parent.emitBubblingEvent( 'stateChanged' ); }, /** * Set's the components title * * @param {String} title */ setTitle: function( title ) { this.parent.setTitle( title ); }, /** * Set's the containers size. Called by the container's component. * To set the size programmatically from within the container please * use the public setSize method * * @param {[Int]} width in px * @param {[Int]} height in px * * @returns {void} */ _$setSize: function( width, height ) { if( width !== this.width || height !== this.height ) { this.width = width; this.height = height; this._contentElement.width( this.width ).height( this.height ); this.emit( 'resize' ); } } }); /** * Pops a content item out into a new browser window. * This is achieved by * * - Creating a new configuration with the content item as root element * - Serializing and minifying the configuration * - Opening the current window's URL with the configuration as a GET parameter * - GoldenLayout when opened in the new window will look for the GET parameter * and use it instead of the provided configuration * * @param {Object} config GoldenLayout item config * @param {Object} dimensions A map with width, height, top and left * @param {String} parentId The id of the element the item will be appended to on popIn * @param {Number} indexInParent The position of this element within its parent * @param {lm.LayoutManager} layoutManager */ lm.controls.BrowserPopout = function( config, dimensions, parentId, indexInParent, layoutManager ) { lm.utils.EventEmitter.call( this ); this.isInitialised = false; this._config = config; this._dimensions = dimensions; this._parentId = parentId; this._indexInParent = indexInParent; this._layoutManager = layoutManager; this._popoutWindow = null; this._id = null; this._createWindow(); }; lm.utils.copy( lm.controls.BrowserPopout.prototype, { toConfig: function() { return { dimensions:{ width: this.getGlInstance().width, height: this.getGlInstance().height, left: this._popoutWindow.screenX || this._popoutWindow.screenLeft, top: this._popoutWindow.screenY || this._popoutWindow.screenTop }, content: this.getGlInstance().toConfig().content, parentId: this._parentId, indexInParent: this._indexInParent }; }, getGlInstance: function() { return this._popoutWindow.__glInstance; }, getWindow: function() { return this._popoutWindow; }, close: function() { if( this.getGlInstance() ) { this.getGlInstance()._$closeWindow(); } else { try{ this.getWindow().close(); } catch( e ){} } }, /** * Returns the popped out item to its original position. If the original * parent isn't available anymore it falls back to the layout's topmost element */ popIn: function() { var childConfig, parentItem, index = this._indexInParent; if( this._parentId ) { /* * The $.extend call seems a bit pointless, but it's crucial to * copy the config returned by this.getGlInstance().toConfig() * onto a new object. Internet Explorer keeps the references * to objects on the child window, resulting in the following error * once the child window is closed: * * The callee (server [not server application]) is not available and disappeared */ childConfig = $.extend( true, {}, this.getGlInstance().toConfig() ).content[ 0 ]; parentItem = this._layoutManager.root.getItemsById( this._parentId )[ 0 ]; /* * Fallback if parentItem is not available. Either add it to the topmost * item or make it the topmost item if the layout is empty */ if( !parentItem ) { if( this._layoutManager.root.contentItems.length > 0 ) { parentItem = this._layoutManager.root.contentItems[ 0 ]; } else { parentItem = this._layoutManager.root; } index = 0; } } parentItem.addChild( childConfig, this._indexInParent ); this.close(); }, /** * Creates the URL and window parameter * and opens a new window * * @private * * @returns {void} */ _createWindow: function() { var checkReadyInterval, url = this._createUrl(), /** * Bogus title to prevent re-usage of existing window with the * same title. The actual title will be set by the new window's * GoldenLayout instance if it detects that it is in subWindowMode */ title = Math.floor( Math.random() * 1000000 ).toString( 36 ), /** * The options as used in the window.open string */ options = this._serializeWindowOptions({ width: this._dimensions.width, height: this._dimensions.height, innerWidth: this._dimensions.width, innerHeight: this._dimensions.height, menubar: 'no', toolbar: 'no', location: 'no', personalbar: 'no', resizable: 'yes', scrollbars: 'no', status: 'no' }); this._popoutWindow = window.open( url, title, options ); if( !this._popoutWindow ) { if( this._layoutManager.config.settings.blockedPopoutsThrowError === true ) { var error = new Error( 'Popout blocked' ); error.type = 'popoutBlocked'; throw error; } else { return; } } $( this._popoutWindow ) .on( 'load', lm.utils.fnBind( this._positionWindow, this ) ) .on( 'unload beforeunload', lm.utils.fnBind( this._onClose, this ) ); /** * Polling the childwindow to find out if GoldenLayout has been initialised * doesn't seem optimal, but the alternatives - adding a callback to the parent * window or raising an event on the window object - both would introduce knowledge * about the parent to the child window which we'd rather avoid */ checkReadyInterval = setInterval(lm.utils.fnBind(function(){ if( this._popoutWindow.__glInstance && this._popoutWindow.__glInstance.isInitialised ) { this._onInitialised(); clearInterval( checkReadyInterval ); } }, this ), 10 ); }, /** * Serialises a map of key:values to a window options string * * @param {Object} windowOptions * * @returns {String} serialised window options */ _serializeWindowOptions: function( windowOptions ) { var windowOptionsString = [], key; for( key in windowOptions ) { windowOptionsString.push( key + '=' + windowOptions[ key ] ); } return windowOptionsString.join( ',' ); }, /** * Creates the URL for the new window, including the * config GET parameter * * @returns {String} URL */ _createUrl: function() { var config = { content: this._config }, storageKey = 'gl-window-config-' + lm.utils.getUniqueId(), urlParts; config = ( new lm.utils.ConfigMinifier() ).minifyConfig( config ); try{ localStorage.setItem( storageKey, JSON.stringify( config ) ); } catch( e ) { throw new Error( 'Error while writing to localStorage ' + e.toString() ); } urlParts = document.location.href.split( '?' ); // URL doesn't contain GET-parameters if( urlParts.length === 1 ) { return urlParts[ 0 ] + '?gl-window=' + storageKey; // URL contains GET-parameters } else { return document.location.href + '&gl-window=' + storageKey; } }, /** * Move the newly created window roughly to * where the component used to be. * * @private * * @returns {void} */ _positionWindow: function() { this._popoutWindow.moveTo( this._dimensions.left, this._dimensions.top ); this._popoutWindow.focus(); }, /** * Callback when the new window is opened and the GoldenLayout instance * within it is initialised * * @returns {void} */ _onInitialised: function() { this.isInitialised = true; this.getGlInstance().on( 'popIn', this.popIn, this ); this.emit( 'initialised' ); }, /** * Invoked 50ms after the window unload event * * @private * * @returns {void} */ _onClose: function() { setTimeout( lm.utils.fnBind( this.emit, this, [ 'closed' ] ), 50 ); } }); /** * This class creates a temporary container * for the component whilst it is being dragged * and handles drag events * * @constructor * @private * * @param {Number} x The initial x position * @param {Number} y The initial y position * @param {lm.utils.DragListener} dragListener * @param {lm.LayoutManager} layoutManager * @param {lm.item.AbstractContentItem} contentItem * @param {lm.item.AbstractContentItem} originalParent */ lm.controls.DragProxy = function( x, y, dragListener, layoutManager, contentItem, originalParent ) { lm.utils.EventEmitter.call( this ); this._dragListener = dragListener; this._layoutManager = layoutManager; this._contentItem = contentItem; this._originalParent = originalParent; this._area = null; this._lastValidArea = null; this._dragListener.on( 'drag', this._onDrag, this ); this._dragListener.on( 'dragStop', this._onDrop, this ); this.element = $( lm.controls.DragProxy._template ); this.element.css({ left: x, top: y }); this.element.find( '.lm_tab' ).attr( 'title', lm.utils.stripTags( this._contentItem.config.title ) ); this.element.find( '.lm_title' ).html( this._contentItem.config.title ); this.childElementContainer = this.element.find( '.lm_content' ); this.childElementContainer.append( contentItem.element ); this._updateTree(); this._layoutManager._$calculateItemAreas(); this._setDimensions(); $( document.body ).append( this.element ); var offset = this._layoutManager.container.offset(); this._minX = offset.left; this._minY = offset.top; this._maxX = this._layoutManager.container.width() + this._minX; this._maxY = this._layoutManager.container.height() + this._minY; this._width = this.element.width(); this._height = this.element.height(); this._setDropPosition( x, y ); }; lm.controls.DragProxy._template = '<div class="lm_dragProxy">' + '<div class="lm_header">' + '<ul class="lm_tabs">' + '<li class="lm_tab lm_active"><i class="lm_left"></i>' + '<span class="lm_title"></span>' + '<i class="lm_right"></i></li>' + '</ul>' + '</div>' + '<div class="lm_content"></div>' + '</div>'; lm.utils.copy( lm.controls.DragProxy.prototype, { /** * Callback on every mouseMove event during a drag. Determines if the drag is * still within the valid drag area and calls the layoutManager to highlight the * current drop area * * @param {Number} offsetX The difference from the original x position in px * @param {Number} offsetY The difference from the original y position in px * @param {jQuery DOM event} event * * @private * * @returns {void} */ _onDrag: function( offsetX, offsetY, event ) { var x = event.pageX, y = event.pageY, isWithinContainer = x > this._minX && x < this._maxX && y > this._minY && y < this._maxY; if( !isWithinContainer && this._layoutManager.config.settings.constrainDragToContainer === true ) { return; } this._setDropPosition( x, y ); }, /** * Sets the target position, highlighting the appropriate area * * @param {Number} x The x position in px * @param {Number} y The y position in px * * @private * * @returns {void} */ _setDropPosition: function( x, y ) { this.element.css({ left: x, top: y }); this._area = this._layoutManager._$getArea( x, y ); if( this._area !== null ) { this._lastValidArea = this._area; this._area.contentItem._$highlightDropZone( x, y, this._area ); } }, /** * Callback when the drag has finished. Determines the drop area * and adds the child to it * * @private * * @returns {void} */ _onDrop: function() { this._layoutManager.dropTargetIndicator.hide(); /* * Valid drop area found */ if( this._area !== null ) { this._area.contentItem._$onDrop( this._contentItem ); /** * No valid drop area available at present, but one has been found before. * Use it */ } else if( this._lastValidArea !== null ) { this._lastValidArea.contentItem._$onDrop( this._contentItem ); /** * No valid drop area found during the duration of the drag. Return * content item to its original position if a original parent is provided. * (Which is not the case if the drag had been initiated by createDragSource) */ } else if ( this._originalParent ){ this._originalParent.addChild( this._contentItem ); /** * The drag didn't ultimately end up with adding the content item to * any container. In order to ensure clean up happens, destroy the * content item. */ } else { this._contentItem._$destroy(); } this.element.remove(); this._layoutManager.emit( 'itemDropped', this._contentItem ); }, /** * Removes the item from its original position within the tree * * @private * * @returns {void} */ _updateTree: function() { /** * parent is null if the drag had been initiated by a external drag source */ if( this._contentItem.parent ) { this._contentItem.parent.removeChild( this._contentItem, true ); } this._contentItem._$setParent( this ); }, /** * Updates the Drag Proxie's dimensions * * @private * * @returns {void} */ _setDimensions: function() { var dimensions = this._layoutManager.config.dimensions, width = dimensions.dragProxyWidth, height = dimensions.dragProxyHeight - dimensions.headerHeight; this.childElementContainer.width( width ); this.childElementContainer.height( height ); this._contentItem.element.width( width ); this._contentItem.element.height( height ); this._contentItem.callDownwards( '_$show' ); this._contentItem.callDownwards( 'setSize' ); } }); /** * Allows for any DOM item to create a component on drag * start tobe dragged into the Layout * * @param {jQuery element} element * @param {Object} itemConfig the configuration for the contentItem that will be created * @param {LayoutManager} layoutManager * * @constructor */ lm.controls.DragSource = function( element, itemConfig, layoutManager ) { this._element = element; this._itemConfig = itemConfig; this._layoutManager = layoutManager; this._dragListener = null; this._createDragListener(); }; lm.utils.copy( lm.controls.DragSource.prototype, { /** * Called initially and after every drag * * @returns {void} */ _createDragListener: function() { if( this._dragListener !== null ) { this._dragListener.destroy(); } this._dragListener = new lm.utils.DragListener( this._element ); this._dragListener.on( 'dragStart', this._onDragStart, this ); this._dragListener.on( 'dragStop', this._createDragListener, this ); }, /** * Callback for the DragListener's dragStart event * * @param {int} x the x position of the mouse on dragStart * @param {int} y the x position of the mouse on dragStart * * @returns {void} */ _onDragStart: function( x, y ) { var contentItem = this._layoutManager._$normalizeContentItem( this._itemConfig ), dragProxy = new lm.controls.DragProxy( x, y, this._dragListener, this._layoutManager, contentItem, null ); this._layoutManager.transitionIndicator.transitionElements( this._element, dragProxy.element ); } }); lm.controls.DropTargetIndicator = function() { this.element = $( lm.controls.DropTargetIndicator._template ); $(document.body).append( this.element ); }; lm.controls.DropTargetIndicator._template = '<div class="lm_dropTargetIndicator"><div class="lm_inner"></div></div>'; lm.utils.copy( lm.controls.DropTargetIndicator.prototype, { destroy: function() { this.element.remove(); }, highlight: function( x1, y1, x2, y2 ) { this.highlightArea({ x1:x1, y1:y1, x2:x2, y2:y2 }); }, highlightArea: function( area ) { this.element.css({ left: area.x1, top: area.y1, width: area.x2 - area.x1, height: area.y2 - area.y1 }).show(); }, hide: function() { this.element.hide(); } }); /** * This class represents a header above a Stack ContentItem. * * @param {lm.LayoutManager} layoutManager * @param {lm.item.AbstractContentItem} parent */ lm.controls.Header = function( layoutManager, parent ) { lm.utils.EventEmitter.call( this ); this.layoutManager = layoutManager; this.element = $( lm.controls.Header._template ); if( this.layoutManager.config.settings.selectionEnabled === true ) { this.element.addClass( 'lm_selectable' ); this.element.click( lm.utils.fnBind( this._onHeaderClick, this ) ); } this.element.height( layoutManager.config.dimensions.headerHeight ); this.tabsContainer = this.element.find( '.lm_tabs' ); this.controlsContainer = this.element.find( '.lm_controls' ); this.parent = parent; this.parent.on( 'resize', this._updateTabSizes, this ); this.tabs = []; this.activeContentItem = null; this.closeButton = null; this._createControls(); }; lm.controls.Header._template = [ '<div class="lm_header">', '<ul class="lm_tabs"></ul>', '<ul class="lm_controls"></ul>', '</div>' ].join( '' ); lm.utils.copy( lm.controls.Header.prototype, { /** * Creates a new tab and associates it with a contentItem * * @param {lm.item.AbstractContentItem} contentItem * @param {Integer} index The position of the tab * * @returns {void} */ createTab: function( contentItem, index ) { var tab, i; //If there's already a tab relating to the //content item, don't do anything for( i = 0; i < this.tabs.length; i++ ) { if( this.tabs[ i ].contentItem === contentItem ) { return; } } tab = new lm.controls.Tab( this, contentItem ); if( this.tabs.length === 0 ) { this.tabs.push( tab ); this.tabsContainer.append( tab.element ); return; } if( index === undefined ) { index = this.tabs.length; } if( index > 0 ) { this.tabs[ index - 1 ].element.after( tab.element ); } else { this.tabs[ 0 ].element.before( tab.element ); } this.tabs.splice( index, 0, tab ); this._updateTabSizes(); }, /** * Finds a tab based on the contentItem its associated with and removes it. * * @param {lm.item.AbstractContentItem} contentItem * * @returns {void} */ removeTab: function( contentItem ) { for( var i = 0; i < this.tabs.length; i++ ) { if( this.tabs[ i ].contentItem === contentItem ) { this.tabs[ i ]._$destroy(); this.tabs.splice( i, 1 ); return; } } throw new Error( 'contentItem is not controlled by this header' ); }, /** * The programmatical equivalent of clicking a Tab. * * @param {lm.item.AbstractContentItem} contentItem */ setActiveContentItem: function( contentItem ) { var i, isActive; for( i = 0; i < this.tabs.length; i++ ) { isActive = this.tabs[ i ].contentItem === contentItem; this.tabs[ i ].setActive( isActive ); if( isActive === true ) { this.activeContentItem = contentItem; this.parent.config.activeItemIndex = i; } } this._updateTabSizes(); this.parent.emitBubblingEvent( 'stateChanged' ); }, /** * Programmatically set closability. * * @package private * @param {Boolean} isClosable Whether to enable/disable closability. * * @returns {Boolean} Whether the action was successful */ _$setClosable: function( isClosable ) { if ( this.closeButton && this._isClosable() ) { this.closeButton.element[ isClosable ? "show" : "hide" ](); return true; } return false; }, /** * Destroys the entire header * * @package private * * @returns {void} */ _$destroy: function() { this.emit( 'destroy' ); for( var i = 0; i < this.tabs.length; i++ ) { this.tabs[ i ]._$destroy(); } this.element.remove(); }, /** * Creates the popout, maximise and close buttons in the header's top right corner * * @returns {void} */ _createControls: function() { var closeStack, popout, label, maximiseLabel, minimiseLabel, maximise, maximiseButton; /** * Popout control to launch component in new window. */ if( this.layoutManager.config.settings.showPopoutIcon ) { popout = lm.utils.fnBind( this._onPopoutClick, this ); label = this.layoutManager.config.labels.popout; new lm.controls.HeaderButton( this, label, 'lm_popout', popout ); } /** * Maximise control - set the component to the full size of the layout */ if( this.layoutManager.config.settings.showMaximiseIcon ) { maximise = lm.utils.fnBind( this.parent.toggleMaximise, this.parent ); maximiseLabel = this.layoutManager.config.labels.maximise; minimiseLabel = this.layoutManager.config.labels.minimise; maximiseButton = new lm.controls.HeaderButton( this, maximiseLabel, 'lm_maximise', maximise ); this.parent.on( 'maximised', function(){ maximiseButton.element.attr( 'title', minimiseLabel ); }); this.parent.on( 'minimised', function(){ maximiseButton.element.attr( 'title', maximiseLabel ); }); } /** * Close button */ if( this._isClosable() ) { closeStack = lm.utils.fnBind( this.parent.remove, this.parent ); label = this.layoutManager.config.labels.close; this.closeButton = new lm.controls.HeaderButton( this, label, 'lm_close', closeStack ); } }, /** * Checks whether the header is closable based on the parent config and * the global config. * * @returns {Boolean} Whether the header is closable. */ _isClosable: function() { return this.parent.config.isClosable && this.layoutManager.config.settings.showCloseIcon; }, _onPopoutClick: function() { if( this.layoutManager.config.settings.popoutWholeStack === true ) { this.parent.popout(); } else { this.activeContentItem.popout(); } }, /** * Invoked when the header's background is clicked (not it's tabs or controls) * * @param {jQuery DOM event} event * * @returns {void} */ _onHeaderClick: function( event ) { if( event.target === this.element[ 0 ] ) { this.parent.select(); } }, /** * Shrinks the tabs if the available space is not sufficient * * @returns {void} */ _updateTabSizes: function() { if( this.tabs.length === 0 ) { return; } var availableWidth = this.element.outerWidth() - this.controlsContainer.outerWidth(), totalTabWidth = 0, tabElement, i, marginLeft, gap; for( i = 0; i < this.tabs.length; i++ ) { tabElement = this.tabs[ i ].element; /* * In order to show every tab's close icon, decrement the z-index from left to right */ tabElement.css( 'z-index', this.tabs.length - i ); totalTabWidth += tabElement.outerWidth() + parseInt( tabElement.css( 'margin-right' ), 10 ); } gap = ( totalTabWidth - availableWidth ) / ( this.tabs.length - 1 ); for( i = 0; i < this.tabs.length; i++ ) { /* * The active tab keeps it's original width */ if( !this.tabs[ i ].isActive && gap > 0 ) { marginLeft = '-' + Math.floor( gap )+ 'px'; } else { marginLeft = ''; } this.tabs[ i ].element.css( 'margin-left', marginLeft ); } if( availableWidth < totalTabWidth ) { this.element.css( 'overflow', 'hidden' ); } else { this.element.css( 'overflow', 'visible' ); } } }); lm.controls.HeaderButton = function( header, label, cssClass, action ) { this._header = header; this.element = $( '<li class="' + cssClass + '" title="' + label + '"></li>' ); this._header.on( 'destroy', this._$destroy, this ); this._action = action; this.element.click( this._action ); this._header.controlsContainer.append( this.element ); }; lm.utils.copy( lm.controls.HeaderButton.prototype, { _$destroy: function() { this.element.off(); this.element.remove(); } }); lm.controls.Splitter = function( isVertical, size ) { this._isVertical = isVertical; this._size = size; this.element = this._createElement(); this._dragListener = new lm.utils.DragListener( this.element ); }; lm.utils.copy( lm.controls.Splitter.prototype, { on: function( event, callback, context ) { this._dragListener.on( event, callback, context ); }, _$destroy: function() { this.element.remove(); }, _createElement: function() { var element = $( '<div class="lm_splitter"><div class="lm_drag_handle"></div></div>' ); element.addClass( 'lm_' + ( this._isVertical ? 'vertical' : 'horizontal' ) ); element[ this._isVertical ? 'height' : 'width' ]( this._size ); return element; } }); /** * Represents an individual tab within a Stack's header * * @param {lm.controls.Header} header * @param {lm.items.AbstractContentItem} contentItem * * @constructor */ lm.controls.Tab = function( header, contentItem ) { this.header = header; this.contentItem = contentItem; this.element = $( lm.controls.Tab._template ); this.titleElement = this.element.find( '.lm_title' ); this.closeElement = this.element.find( '.lm_close_tab' ); this.closeElement[ contentItem.config.isClosable ? 'show' : 'hide' ](); this.isActive = false; this.setTitle( contentItem.config.title ); this.contentItem.on( 'titleChanged', this.setTitle, this ); this._layoutManager = this.contentItem.layoutManager; if( this._layoutManager.config.settings.reorderEnabled === true && contentItem.config.reorderEnabled === true ) { this._dragListener = new lm.utils.DragListener( this.element ); this._dragListener.on( 'dragStart', this._onDragStart, this ); } this._onTabClickFn = lm.utils.fnBind( this._onTabClick, this ); this._onCloseClickFn = lm.utils.fnBind( this._onCloseClick, this ); this.element.click( this._onTabClickFn ); if( this.contentItem.config.isClosable ) { this.closeElement.click( this._onCloseClickFn ); } else { this.closeElement.remove(); } this.contentItem.tab = this; this.contentItem.emit( 'tab', this ); this.contentItem.layoutManager.emit( 'tabCreated', this ); if( this.contentItem.isComponent ) { this.contentItem.container.tab = this; this.contentItem.container.emit( 'tab', this ); } }; /** * The tab's html template * * @type {String} */ lm.controls.Tab._template = '<li class="lm_tab"><i class="lm_left"></i>' + '<span class="lm_title"></span><div class="lm_close_tab"></div>' + '<i class="lm_right"></i></li>'; lm.utils.copy( lm.controls.Tab.prototype,{ /** * Sets the tab's title to the provided string and sets * its title attribute to a pure text representation (without * html tags) of the same string. * * @public * @param {String} title can contain html */ setTitle: function( title ) { this.element.attr( 'title', lm.utils.stripTags( title ) ); this.titleElement.html( title ); }, /** * Sets this tab's active state. To programmatically * switch tabs, use header.setActiveContentItem( item ) instead. * * @public * @param {Boolean} isActive */ setActive: function( isActive ) { if( isActive === this.isActive ) { return; } this.isActive = isActive; if( isActive ) { this.element.addClass( 'lm_active' ); } else { this.element.removeClass( 'lm_active'); } }, /** * Destroys the tab * * @private * @returns {void} */ _$destroy: function() { this.element.off( 'click', this._onTabClickFn ); this.closeElement.off( 'click', this._onCloseClickFn ); if( this._dragListener ) { this._dragListener.off( 'dragStart', this._onDragStart ); this._dragListener = null; } this.element.remove(); }, /** * Callback for the DragListener * * @param {Number} x The tabs absolute x position * @param {Number} y The tabs absolute y position * * @private * @returns {void} */ _onDragStart: function( x, y ) { if( this.contentItem.parent.isMaximised === true ) { this.contentItem.parent.toggleMaximise(); } new lm.controls.DragProxy( x, y, this._dragListener, this._layoutManager, this.contentItem, this.header.parent ); }, /** * Callback when the tab is clicked * * @param {jQuery DOM event} event * * @private * @returns {void} */ _onTabClick: function( event ) { // left mouse button if( event.button === 0 ) { var activeContentItem = this.header.parent.getActiveContentItem(); if (this.contentItem !== activeContentItem) { this.header.parent.setActiveContentItem( this.contentItem ); } // middle mouse button } else if( event.button === 1 && this.contentItem.config.isClosable ) { this._onCloseClick( event ); } }, /** * Callback when the tab's close button is * clicked * * @param {jQuery DOM event} event * * @private * @returns {void} */ _onCloseClick: function( event ) { event.stopPropagation(); this.header.parent.removeChild( this.contentItem ); } }); lm.controls.TransitionIndicator = function() { this._element = $( '<div class="lm_transition_indicator"></div>' ); $( document.body ).append( this._element ); this._toElement = null; this._fromDimensions = null; this._totalAnimationDuration = 200; this._animationStartTime = null; }; lm.utils.copy( lm.controls.TransitionIndicator.prototype, { destroy: function() { this._element.remove(); }, transitionElements: function( fromElement, toElement ) { /** * TODO - This is not quite as cool as expected. Review. */ return; this._toElement = toElement; this._animationStartTime = lm.utils.now(); this._fromDimensions = this._measure( fromElement ); this._fromDimensions.opacity = 0.8; this._element.show().css( this._fromDimensions ); lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) ); }, _nextAnimationFrame: function() { var toDimensions = this._measure( this._toElement ), animationProgress = ( lm.utils.now() - this._animationStartTime ) / this._totalAnimationDuration, currentFrameStyles = {}, cssProperty; if( animationProgress >= 1 ) { this._element.hide(); return; } toDimensions.opacity = 0; for( cssProperty in this._fromDimensions ) { currentFrameStyles[ cssProperty ] = this._fromDimensions[ cssProperty ] + ( toDimensions[ cssProperty] - this._fromDimensions[ cssProperty ] ) * animationProgress; } this._element.css( currentFrameStyles ); lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) ); }, _measure: function( element ) { var offset = element.offset(); return { left: offset.left, top: offset.top, width: element.outerWidth(), height: element.outerHeight() }; } }); lm.errors.ConfigurationError = function( message, node ) { Error.call( this ); this.name = 'Configuration Error'; this.message = message; this.node = node; }; lm.errors.ConfigurationError.prototype = new Error(); /** * This is the baseclass that all content items inherit from. * Most methods provide a subset of what the sub-classes do. * * It also provides a number of functions for tree traversal * * @param {lm.LayoutManager} layoutManager * @param {item node configuration} config * @param {lm.item} parent * * @event stateChanged * @event beforeItemDestroyed * @event itemDestroyed * @event itemCreated * @event componentCreated * @event rowCreated * @event columnCreated * @event stackCreated * * @constructor */ lm.items.AbstractContentItem = function( layoutManager, config, parent ) { lm.utils.EventEmitter.call( this ); this.config = this._extendItemNode( config ); this.type = config.type; this.contentItems = []; this.parent = parent; this.isInitialised = false; this.isMaximised = false; this.isRoot = false; this.isRow = false; this.isColumn = false; this.isStack = false; this.isComponent = false; this.layoutManager = layoutManager; this._pendingEventPropagations = {}; this._throttledEvents = [ 'stateChanged' ]; this.on( lm.utils.EventEmitter.ALL_EVENT, this._propagateEvent, this ); if( config.content ) { this._createContentItems( config ); } }; lm.utils.copy( lm.items.AbstractContentItem.prototype, { /** * Set the size of the component and its children, called recursively * * @abstract * @returns void */ setSize: function() { throw new Error( 'Abstract Method' ); }, /** * Calls a method recursively downwards on the tree * * @param {String} functionName the name of the function to be called * @param {[Array]}functionArguments optional arguments that are passed to every function * @param {[bool]} bottomUp Call methods from bottom to top, defaults to false * @param {[bool]} skipSelf Don't invoke the method on the class that calls it, defaults to false * * @returns {void} */ callDownwards: function( functionName, functionArguments, bottomUp, skipSelf ) { var i; if( bottomUp !== true && skipSelf !== true ) { this[ functionName ].apply( this, functionArguments || [] ); } for( i = 0; i < this.contentItems.length; i++ ) { this.contentItems[ i ].callDownwards( functionName, functionArguments, bottomUp ); } if( bottomUp === true && skipSelf !== true ) { this[ functionName ].apply( this, functionArguments || [] ); } }, /** * Removes a child node (and its children) from the tree * * @param {lm.items.ContentItem} contentItem * * @returns {void} */ removeChild: function( contentItem, keepChild ) { /* * Get the position of the item that's to be removed within all content items this node contains */ var index = lm.utils.indexOf( contentItem, this.contentItems ); /* * Make sure the content item to be removed is actually a child of this item */ if( index === -1 ) { throw new Error( 'Can\'t remove child item. Unknown content item' ); } /** * Call ._$destroy on the content item. This also calls ._$destroy on all its children */ if( keepChild !== true ) { this.contentItems[ index ]._$destroy(); } /** * Remove the content item from this nodes array of children */ this.contentItems.splice( index, 1 ); /** * Remove the item from the configuration */ this.config.content.splice( index, 1 ); /** * If this node still contains other content items, adjust their size */ if( this.contentItems.length > 0 ) { this.callDownwards( 'setSize' ); /** * If this was the last content item, remove this node as well */ } else if( !(this instanceof lm.items.Root) && this.config.isClosable === true ) { this.parent.removeChild( this ); } }, /** * Sets up the tree structure for the newly added child * The responsibility for the actual DOM manipulations lies * with the concrete item * * @param {lm.items.AbstractContentItem} contentItem * @param {[Int]} index If omitted item will be appended */ addChild: function( contentItem, index ) { if ( index === undefined ) { index = this.contentItems.length; } this.contentItems.splice( index, 0, contentItem ); if( this.config.content === undefined ) { this.config.content = []; } this.config.content.splice( index, 0, contentItem.config ); contentItem.parent = this; if( contentItem.parent.isInitialised === true && contentItem.isInitialised === false ) { contentItem._$init(); } }, /** * Replaces oldChild with newChild. This used to use jQuery.replaceWith... which for * some reason removes all event listeners, so isn't really an option. * * @param {lm.item.AbstractContentItem} oldChild * @param {lm.item.AbstractContentItem} newChild * * @returns {void} */ replaceChild: function( oldChild, newChild, _$destroyOldChild ) { newChild = this.layoutManager._$normalizeContentItem( newChild ); var index = lm.utils.indexOf( oldChild, this.contentItems ), parentNode = oldChild.element[ 0 ].parentNode; if( index === -1 ) { throw new Error( 'Can\'t replace child. oldChild is not child of this' ); } parentNode.replaceChild( newChild.element[ 0 ], oldChild.element[ 0 ] ); /* * Optionally destroy the old content item */ if( _$destroyOldChild === true ) { oldChild.parent = null; oldChild._$destroy(); } /* * Wire the new contentItem into the tree */ this.contentItems[ index ] = newChild; newChild.parent = this; /* * Update tab reference */ if ( this.isStack ) { this.header.tabs[ index ].contentItem = newChild; } //TODO This doesn't update the config... refactor to leave item nodes untouched after creation if( newChild.parent.isInitialised === true && newChild.isInitialised === false ) { newChild._$init(); } this.callDownwards( 'setSize' ); }, /** * Convenience method. * Shorthand for this.parent.removeChild( this ) * * @returns {void} */ remove: function() { this.parent.removeChild( this ); }, /** * Removes the component from the layout and creates a new * browser window with the component and its children inside * * @returns {lm.controls.BrowserPopout} */ popout: function() { var browserPopout = this.layoutManager.createPopout( this ); this.emitBubblingEvent( 'stateChanged' ); return browserPopout; }, /** * Maximises the Item or minimises it if it is already maximised * * @returns {void} */ toggleMaximise: function() { if( this.isMaximised === true ) { this.layoutManager._$minimiseItem( this ); } else { this.layoutManager._$maximiseItem( this ); } this.isMaximised = !this.isMaximised; this.emitBubblingEvent( 'stateChanged' ); }, /** * Selects the item if it is not already selected * * @returns {void} */ select: function() { if( this.layoutManager.selectedItem !== this ) { this.layoutManager.selectItem( this, true ); this.element.addClass( 'lm_selected' ); } }, /** * De-selects the item if it is selected * * @returns {void} */ deselect: function() { if( this.layoutManager.selectedItem === this ) { this.layoutManager.selectedItem = null; this.element.removeClass( 'lm_selected' ); } }, /** * Set this component's title * * @public * @param {String} title * * @returns {void} */ setTitle: function( title ) { this.config.title = title; this.emit( 'titleChanged', title ); this.emit( 'stateChanged' ); }, /** * Checks whether a provided id is present * * @public * @param {String} id * * @returns {Boolean} isPresent */ hasId: function( id ) { if( !this.config.id ) { return false; } else if( typeof this.config.id === 'string' ) { return this.config.id === id; } else if( this.config.id instanceof Array ) { return lm.utils.indexOf( id, this.config.id ) !== -1; } }, /** * Adds an id. Adds it as a string if the component doesn't * have an id yet or creates/uses an array * * @public * @param {String} id * * @returns {void} */ addId: function( id ) { if( this.hasId( id ) ) { return; } if( !this.config.id ) { this.config.id = id; } else if( typeof this.config.id === 'string' ) { this.config.id = [ this.config.id, id ]; } else if( this.config.id instanceof Array ) { this.config.id.push( id ); } }, /** * Removes an existing id. Throws an error * if the id is not present * * @public * @param {String} id * * @returns {void} */ removeId: function( id ) { if( !this.hasId( id ) ) { throw new Error( 'Id not found' ); } if( typeof this.config.id === 'string' ) { delete this.config.id; } else if( this.config.id instanceof Array ) { var index = lm.utils.indexOf( id, this.config.id ); this.config.id.splice( index, 1 ); } }, /**************************************** * SELECTOR ****************************************/ getItemsByFilter: function( filter ) { var result = [], next = function( contentItem ) { for( var i = 0; i < contentItem.contentItems.length; i++ ) { if( filter( contentItem.contentItems[ i ] ) === true ) { result.push( contentItem.contentItems[ i ] ); } next( contentItem.contentItems[ i ] ); } }; next( this ); return result; }, getItemsById: function( id ) { return this.getItemsByFilter( function( item ){ if( item.config.id instanceof Array ) { return lm.utils.indexOf( id, item.config.id ) !== -1; } else { return item.config.id === id; } }); }, getItemsByType: function( type ) { return this._$getItemsByProperty( 'type', type ); }, getComponentsByName: function( componentName ) { var components = this._$getItemsByProperty( 'componentName', componentName ), instances = [], i; for( i = 0; i < components.length; i++ ) { instances.push( components[ i ].instance ); } return instances; }, /**************************************** * PACKAGE PRIVATE ****************************************/ _$getItemsByProperty: function( key, value ) { return this.getItemsByFilter( function( item ){ return item[ key ] === value; }); }, _$setParent: function( parent ) { this.parent = parent; }, _$highlightDropZone: function( x, y, area ) { this.layoutManager.dropTargetIndicator.highlightArea( area ); }, _$onDrop: function( contentItem ) { this.addChild( contentItem ); }, _$hide: function() { this._callOnActiveComponents( 'hide' ); this.element.hide(); this.layoutManager.updateSize(); }, _$show: function() { this._callOnActiveComponents( 'show' ); this.element.show(); this.layoutManager.updateSize(); this._callOnActiveComponents( 'shown' ); }, _callOnActiveComponents: function( methodName ) { var stacks = this.getItemsByType( 'stack' ), activeContentItem, i; for( i = 0; i < stacks.length; i++ ) { activeContentItem = stacks[ i ].getActiveContentItem(); if( activeContentItem && activeContentItem.isComponent ) { activeContentItem.container[ methodName ](); } } }, /** * Destroys this item ands its children * * @returns {void} */ _$destroy: function() { this.emitBubblingEvent( 'beforeItemDestroyed' ); this.callDownwards( '_$destroy', [], true, true ); this.element.remove(); this.emitBubblingEvent( 'itemDestroyed' ); }, /** * Returns the area the component currently occupies in the format * * { * x1: int * xy: int * y1: int * y2: int * contentItem: contentItem * } */ _$getArea: function( element ) { element = element || this.element; var offset = element.offset(), width = element.width(), height = element.height(); return { x1: offset.left, y1: offset.top, x2: offset.left + width, y2: offset.top + height, surface: width * height, contentItem: this }; }, /** * The tree of content items is created in two steps: First all content items are instantiated, * then init is called recursively from top to bottem. This is the basic init function, * it can be used, extended or overwritten by the content items * * Its behaviour depends on the content item * * @package private * * @returns {void} */ _$init: function() { var i; this.setSize(); for( i = 0; i < this.contentItems.length; i++ ) { this.childElementContainer.append( this.contentItems[ i ].element ); } this.isInitialised = true; this.emitBubblingEvent( 'itemCreated' ); this.emitBubblingEvent( this.type + 'Created' ); }, /** * Emit an event that bubbles up the item tree. * * @param {String} name The name of the event * * @returns {void} */ emitBubblingEvent: function( name ) { var event = new lm.utils.BubblingEvent( name, this ); this.emit( name, event ); }, /** * Private method, creates all content items for this node at initialisation time * PLEASE NOTE, please see addChild for adding contentItems add runtime * @private * @param {configuration item node} config * * @returns {void} */ _createContentItems: function( config ) { var oContentItem, i; if( !( config.content instanceof Array ) ) { throw new lm.errors.ConfigurationError( 'content must be an Array', config ); } for( i = 0; i < config.content.length; i++ ) { oContentItem = this.layoutManager.createContentItem( config.content[ i ], this ); this.contentItems.push( oContentItem ); } }, /** * Extends an item configuration node with default settings * @private * @param {configuration item node} config * * @returns {configuration item node} extended config */ _extendItemNode: function( config ) { for( var key in lm.config.itemDefaultConfig ) { if( config[ key ] === undefined ) { config[ key ] = lm.config.itemDefaultConfig[ key ]; } } return config; }, /** * Called for every event on the item tree. Decides whether the event is a bubbling * event and propagates it to its parent * * @param {String} name the name of the event * @param {lm.utils.BubblingEvent} event * * @returns {void} */ _propagateEvent: function( name, event ) { if( event instanceof lm.utils.BubblingEvent && event.isPropagationStopped === false && this.isInitialised === true ) { /** * In some cases (e.g. if an element is created from a DragSource) it * doesn't have a parent and is not below root. If that's the case * propagate the bubbling event from the top level of the substree directly * to the layoutManager */ if( this.isRoot === false && this.parent ) { this.parent.emit.apply( this.parent, Array.prototype.slice.call( arguments, 0 ) ); } else { this._scheduleEventPropagationToLayoutManager( name, event ); } } }, /** * All raw events bubble up to the root element. Some events that * are propagated to - and emitted by - the layoutManager however are * only string-based, batched and sanitized to make them more usable * * @param {String} name the name of the event * * @private * @returns {void} */ _scheduleEventPropagationToLayoutManager: function( name, event ) { if( lm.utils.indexOf( name, this._throttledEvents ) === -1 ) { this.layoutManager.emit( name, event.origin ); } else { if( this._pendingEventPropagations[ name ] !== true ) { this._pendingEventPropagations[ name ] = true; lm.utils.animFrame( lm.utils.fnBind( this._propagateEventToLayoutManager, this, [ name, event ] ) ); } } }, /** * Callback for events scheduled by _scheduleEventPropagationToLayoutManager * * @param {String} name the name of the event * * @private * @returns {void} */ _propagateEventToLayoutManager: function( name, event ) { this._pendingEventPropagations[ name ] = false; this.layoutManager.emit( name, event ); } }); /** * @param {[type]} layoutManager [description] * @param {[type]} config [description] * @param {[type]} parent [description] */ lm.items.Component = function( layoutManager, config, parent ) { lm.items.AbstractContentItem.call( this, layoutManager, config, parent ); var ComponentConstructor = layoutManager.getComponent( this.config.componentName ), componentConfig = $.extend( true, {}, this.config.componentState || {} ); componentConfig.componentName = this.config.componentName; this.componentName = this.config.componentName; if( this.config.title === '' ) { this.config.title = this.config.componentName; } this.isComponent = true; this.container = new lm.container.ItemContainer( this.config, this, layoutManager ); this.instance = new ComponentConstructor( this.container, componentConfig ); this.element = this.container._element; }; lm.utils.extend( lm.items.Component, lm.items.AbstractContentItem ); lm.utils.copy( lm.items.Component.prototype, { close: function() { this.parent.removeChild( this ); }, setSize: function() { this.container._$setSize( this.element.width(), this.element.height() ); }, _$init: function() { lm.items.AbstractContentItem.prototype._$init.call( this ); this.container.emit( 'open' ); }, _$hide: function() { this.container.hide(); lm.items.AbstractContentItem.prototype._$hide.call( this ); }, _$show: function() { this.container.show(); lm.items.AbstractContentItem.prototype._$show.call( this ); }, _$shown: function() { this.container.shown(); lm.items.AbstractContentItem.prototype._$shown.call( this ); }, _$destroy: function() { this.container.emit( 'destroy' ); lm.items.AbstractContentItem.prototype._$destroy.call( this ); }, /** * Dragging onto a component directly is not an option * * @returns null */ _$getArea: function() { return null; } }); lm.items.Root = function( layoutManager, config, containerElement ) { lm.items.AbstractContentItem.call( this, layoutManager, config, null ); this.isRoot = true; this.type = 'root'; this.element = $( '<div class="lm_goldenlayout lm_item lm_root"></div>' ); this.childElementContainer = this.element; this._containerElement = containerElement; this._containerElement.append( this.element ); }; lm.utils.extend( lm.items.Root, lm.items.AbstractContentItem ); lm.utils.copy( lm.items.Root.prototype, { addChild: function( contentItem ) { if( this.contentItems.length > 0 ) { throw new Error( 'Root node can only have a single child' ); } contentItem = this.layoutManager._$normalizeContentItem( contentItem, this ); this.childElementContainer.append( contentItem.element ); lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem ); this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); }, setSize: function() { var width = this._containerElement.width(), height = this._containerElement.height(); this.element.width( width ); this.element.height( height ); /* * Root can be empty */ if( this.contentItems[ 0 ] ) { this.contentItems[ 0 ].element.width( width ); this.contentItems[ 0 ].element.height( height ); } }, _$onDrop: function( contentItem ) { var stack; if( contentItem.isComponent === true ) { stack = this.layoutManager.createContentItem( {type: 'stack' }, this ); stack.addChild( contentItem ); this.addChild( stack ); } else { this.addChild( contentItem ); } } }); lm.items.RowOrColumn = function( isColumn, layoutManager, config, parent ) { lm.items.AbstractContentItem.call( this, layoutManager, config, parent ); this.isRow = !isColumn; this.isColumn = isColumn; this.element = $( '<div class="lm_item lm_' + ( isColumn ? 'column' : 'row' ) + '"></div>' ); this.childElementContainer = this.element; this._splitterSize = layoutManager.config.dimensions.borderWidth; this._isColumn = isColumn; this._dimension = isColumn ? 'height' : 'width'; this._splitter = []; this._splitterPosition = null; this._splitterMinPosition = null; this._splitterMaxPosition = null; }; lm.utils.extend( lm.items.RowOrColumn, lm.items.AbstractContentItem ); lm.utils.copy( lm.items.RowOrColumn.prototype, { /** * Add a new contentItem to the Row or Column * * @param {lm.item.AbstractContentItem} contentItem * @param {[int]} index The position of the new item within the Row or Column. * If no index is provided the item will be added to the end * @param {[bool]} _$suspendResize If true the items won't be resized. This will leave the item in * an inconsistent state and is only intended to be used if multiple * children need to be added in one go and resize is called afterwards * * @returns {void} */ addChild: function( contentItem, index, _$suspendResize ) { var newItemSize, itemSize, i, splitterElement; contentItem = this.layoutManager._$normalizeContentItem( contentItem, this ); if( index === undefined ) { index = this.contentItems.length; } if( this.contentItems.length > 0 ) { splitterElement = this._createSplitter( Math.max( 0, index - 1 ) ).element; if( index > 0 ) { this.contentItems[ index - 1 ].element.after( splitterElement ); splitterElement.after( contentItem.element ); } else { this.contentItems[ 0 ].element.before( splitterElement ); splitterElement.before( contentItem.element ); } } else { this.childElementContainer.append( contentItem.element ); } lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index ); newItemSize = ( 1 / this.contentItems.length ) * 100; if( _$suspendResize === true ) { this.emitBubblingEvent( 'stateChanged' ); return; } for( i = 0; i < this.contentItems.length; i++ ) { if( this.contentItems[ i ] === contentItem ) { contentItem.config[ this._dimension ] = newItemSize; } else { itemSize = this.contentItems[ i ].config[ this._dimension ] *= ( 100 - newItemSize ) / 100; this.contentItems[ i ].config[ this._dimension ] = itemSize; } } this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); }, /** * Removes a child of this element * * @param {lm.items.AbstractContentItem} contentItem * @param {boolean} keepChild If true the child will be removed, but not destroyed * * @returns {void} */ removeChild: function( contentItem, keepChild ) { var removedItemSize = contentItem.config[ this._dimension ], index = lm.utils.indexOf( contentItem, this.contentItems ), splitterIndex = Math.max( index - 1, 0 ), i, childItem; if( index === -1 ) { throw new Error( 'Can\'t remove child. ContentItem is not child of this Row or Column' ); } /** * Remove the splitter before the item or after if the item happens * to be the first in the row/column */ if( this._splitter[ splitterIndex ] ) { this._splitter[ splitterIndex ]._$destroy(); this._splitter.splice( splitterIndex, 1 ); } /** * Allocate the space that the removed item occupied to the remaining items */ for( i = 0; i < this.contentItems.length; i++ ) { if( this.contentItems[ i ] !== contentItem ) { this.contentItems[ i ].config[ this._dimension ] += removedItemSize / ( this.contentItems.length - 1 ); } } lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild ); if( this.contentItems.length === 1 && this.config.isClosable === true ) { childItem = this.contentItems[ 0 ]; this.contentItems = []; this.parent.replaceChild( this, childItem, true ); } else { this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); } }, /** * Replaces a child of this Row or Column with another contentItem * * @param {lm.items.AbstractContentItem} oldChild * @param {lm.items.AbstractContentItem} newChild * * @returns {void} */ replaceChild: function( oldChild, newChild ) { var size = oldChild.config[ this._dimension ]; lm.items.AbstractContentItem.prototype.replaceChild.call( this, oldChild, newChild ); newChild.config[ this._dimension ] = size; this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); }, /** * Called whenever the dimensions of this item or one of its parents change * * @returns {void} */ setSize: function() { if( this.contentItems.length > 0 ) { this._calculateRelativeSizes(); this._setAbsoluteSizes(); } this.emitBubblingEvent( 'stateChanged' ); this.emit( 'resize' ); }, /** * Invoked recursively by the layout manager. AbstractContentItem.init appends * the contentItem's DOM elements to the container, RowOrColumn init adds splitters * in between them * * @package private * @override AbstractContentItem._$init * @returns {void} */ _$init: function() { if( this.isInitialised === true ) return; var i; lm.items.AbstractContentItem.prototype._$init.call( this ); for( i = 0; i < this.contentItems.length - 1; i++ ) { this.contentItems[ i ].element.after( this._createSplitter( i ).element ); } }, /** * Turns the relative sizes calculated by _calculateRelativeSizes into * absolute pixel values and applies them to the children's DOM elements * * Assigns additional pixels to counteract Math.floor * * @private * @returns {void} */ _setAbsoluteSizes: function() { var i, totalSplitterSize = ( this.contentItems.length - 1 ) * this._splitterSize, totalWidth = this.element.width(), totalHeight = this.element.height(), totalAssigned = 0, additionalPixel, itemSize, itemSizes = []; if( this._isColumn ) { totalHeight -= totalSplitterSize; } else { totalWidth -= totalSplitterSize; } for( i = 0; i < this.contentItems.length; i++ ) { if( this._isColumn ) { itemSize = Math.floor( totalHeight * ( this.contentItems[ i ].config.height / 100 ) ); } else { itemSize = Math.floor( totalWidth * ( this.contentItems[ i ].config.width / 100 ) ); } totalAssigned += itemSize; itemSizes.push( itemSize ); } additionalPixel = Math.floor( ( this._isColumn ? totalHeight : totalWidth ) - totalAssigned ); for( i = 0; i < this.contentItems.length; i++ ) { if( additionalPixel - i > 0 ) { itemSizes[ i ]++; } if( this._isColumn ) { this.contentItems[ i ].element.width( totalWidth ); this.contentItems[ i ].element.height( itemSizes[ i ] ); } else { this.contentItems[ i ].element.width( itemSizes[ i ] ); this.contentItems[ i ].element.height( totalHeight ); } } }, /** * Calculates the relative sizes of all children of this Item. The logic * is as follows: * * - Add up the total size of all items that have a configured size * * - If the total == 100 (check for floating point errors) * Excellent, job done * * - If the total is > 100, * set the size of items without set dimensions to 1/3 and add this to the total * set the size off all items so that the total is hundred relative to their original size * * - If the total is < 100 * If there are items without set dimensions, distribute the remainder to 100 evenly between them * If there are no items without set dimensions, increase all items sizes relative to * their original size so that they add up to 100 * * @private * @returns {void} */ _calculateRelativeSizes: function() { var i, total = 0, itemsWithoutSetDimension = [], dimension = this._isColumn ? 'height' : 'width'; for( i = 0; i < this.contentItems.length; i++ ) { if( this.contentItems[ i ].config[ dimension ] !== undefined ) { total += this.contentItems[ i ].config[ dimension ]; } else { itemsWithoutSetDimension.push( this.contentItems[ i ] ); } } /** * Everything adds up to hundred, all good :-) */ if( Math.round( total ) === 100 ) { return; } /** * Allocate the remaining size to the items without a set dimension */ if( Math.round( total ) < 100 && itemsWithoutSetDimension.length > 0 ) { for( i = 0; i < itemsWithoutSetDimension.length; i++ ) { itemsWithoutSetDimension[ i ].config[ dimension ] = ( 100 - total ) / itemsWithoutSetDimension.length; } return; } /** * If the total is > 100, but there are also items without a set dimension left, assing 50 * as their dimension and add it to the total * * This will be reset in the next step */ if( Math.round( total ) > 100 ) { for( i = 0; i < itemsWithoutSetDimension.length; i++ ) { itemsWithoutSetDimension[ i ].config[ dimension ] = 50; total += 50; } } /** * Set every items size relative to 100 relative to its size to total */ for( i = 0; i < this.contentItems.length; i++ ) { this.contentItems[ i ].config[ dimension ] = ( this.contentItems[ i ].config[ dimension ] / total ) * 100; } }, /** * Instantiates a new lm.controls.Splitter, binds events to it and adds * it to the array of splitters at the position specified as the index argument * * What it doesn't do though is append the splitter to the DOM * * @param {Int} index The position of the splitter * * @returns {lm.controls.Splitter} */ _createSplitter: function( index ) { var splitter; splitter = new lm.controls.Splitter( this._isColumn, this._splitterSize ); splitter.on( 'drag', lm.utils.fnBind( this._onSplitterDrag, this, [ splitter ] ), this ); splitter.on( 'dragStop', lm.utils.fnBind( this._onSplitterDragStop, this, [ splitter ] ), this ); splitter.on( 'dragStart', lm.utils.fnBind( this._onSplitterDragStart, this, [ splitter ] ), this ); this._splitter.splice( index, 0, splitter ); return splitter; }, /** * Locates the instance of lm.controls.Splitter in the array of * registered splitters and returns a map containing the contentItem * before and after the splitters, both of which are affected if the * splitter is moved * * @param {lm.controls.Splitter} splitter * * @returns {Object} A map of contentItems that the splitter affects */ _getItemsForSplitter: function( splitter ) { var index = lm.utils.indexOf( splitter, this._splitter ); return { before: this.contentItems[ index ], after: this.contentItems[ index + 1 ] }; }, /** * Gets the minimum dimensions for the given item configuration array * @param item * @private */ _getMinimumDimensions: function (arr) { var minWidth = 0, minHeight = 0; for (var i = 0; i < arr.length; ++i) { minWidth = Math.max(arr[i].minWidth || 0, minWidth); minHeight = Math.max(arr[i].minHeight || 0, minHeight); } return { horizontal: minWidth, vertical: minHeight }; }, /** * Invoked when a splitter's dragListener fires dragStart. Calculates the splitters * movement area once (so that it doesn't need calculating on every mousemove event) * * @param {lm.controls.Splitter} splitter * * @returns {void} */ _onSplitterDragStart: function( splitter ) { var items = this._getItemsForSplitter( splitter ), minSize = this.layoutManager.config.dimensions[ this._isColumn ? 'minItemHeight' : 'minItemWidth' ]; var beforeMinDim = this._getMinimumDimensions(items.before.config.content); var beforeMinSize = this._isColumn ? beforeMinDim.vertical : beforeMinDim.horizontal; var afterMinDim = this._getMinimumDimensions(items.after.config.content); var afterMinSize = this._isColumn ? afterMinDim.vertical : afterMinDim.horizontal; this._splitterPosition = 0; this._splitterMinPosition = -1 * ( items.before.element[ this._dimension ]() - (beforeMinSize || minSize) ); this._splitterMaxPosition = items.after.element[ this._dimension ]() - (afterMinSize || minSize); }, /** * Invoked when a splitter's DragListener fires drag. Updates the splitters DOM position, * but not the sizes of the elements the splitter controls in order to minimize resize events * * @param {lm.controls.Splitter} splitter * @param {Int} offsetX Relative pixel values to the splitters original position. Can be negative * @param {Int} offsetY Relative pixel values to the splitters original position. Can be negative * * @returns {void} */ _onSplitterDrag: function( splitter, offsetX, offsetY ) { var offset = this._isColumn ? offsetY : offsetX; if( offset > this._splitterMinPosition && offset < this._splitterMaxPosition ) { this._splitterPosition = offset; splitter.element.css( this._isColumn ? 'top' : 'left', offset ); } }, /** * Invoked when a splitter's DragListener fires dragStop. Resets the splitters DOM position, * and applies the new sizes to the elements before and after the splitter and their children * on the next animation frame * * @param {lm.controls.Splitter} splitter * * @returns {void} */ _onSplitterDragStop: function( splitter ) { var items = this._getItemsForSplitter( splitter ), sizeBefore = items.before.element[ this._dimension ](), sizeAfter = items.after.element[ this._dimension ](), splitterPositionInRange = ( this._splitterPosition + sizeBefore ) / ( sizeBefore + sizeAfter ), totalRelativeSize = items.before.config[ this._dimension ] + items.after.config[ this._dimension ]; items.before.config[ this._dimension ] = splitterPositionInRange * totalRelativeSize; items.after.config[ this._dimension ] = ( 1 - splitterPositionInRange ) * totalRelativeSize; splitter.element.css({ 'top': 0, 'left': 0 }); lm.utils.animFrame( lm.utils.fnBind( this.callDownwards, this, [ 'setSize' ] ) ); } }); lm.items.Stack = function( layoutManager, config, parent ) { lm.items.AbstractContentItem.call( this, layoutManager, config, parent ); this.element = $( '<div class="lm_item lm_stack"></div>' ); this._activeContentItem = null; this._dropZones = {}; this._dropSegment = null; this._contentAreaDimensions = null; this._dropIndex = null; this.isStack = true; this.childElementContainer = $( '<div class="lm_items"></div>' ); this.header = new lm.controls.Header( layoutManager, this ); if( layoutManager.config.settings.hasHeaders === true ) { this.element.append( this.header.element ); } this.element.append( this.childElementContainer ); this._$validateClosability(); }; lm.utils.extend( lm.items.Stack, lm.items.AbstractContentItem ); lm.utils.copy( lm.items.Stack.prototype, { setSize: function() { var i, contentWidth = this.element.width(), contentHeight = this.element.height() - this.layoutManager.config.dimensions.headerHeight; this.childElementContainer.width( contentWidth ); this.childElementContainer.height( contentHeight ); for( i = 0; i < this.contentItems.length; i++ ) { this.contentItems[ i ].element.width( contentWidth ).height( contentHeight ); } this.emit( 'resize' ); this.emitBubblingEvent( 'stateChanged' ); }, _$init: function() { var i, initialItem; if( this.isInitialised === true ) return; lm.items.AbstractContentItem.prototype._$init.call( this ); for( i = 0; i < this.contentItems.length; i++ ) { this.header.createTab( this.contentItems[ i ] ); this.contentItems[ i ]._$hide(); } if( this.contentItems.length > 0 ) { initialItem = this.contentItems[ this.config.activeItemIndex || 0 ]; if( !initialItem ) { throw new Error( 'Configured activeItemIndex out of bounds' ); } this.setActiveContentItem( initialItem ); } }, setActiveContentItem: function( contentItem ) { if( lm.utils.indexOf( contentItem, this.contentItems ) === -1 ) { throw new Error( 'contentItem is not a child of this stack' ); } if( this._activeContentItem !== null ) { this._activeContentItem._$hide(); } this._activeContentItem = contentItem; this.header.setActiveContentItem( contentItem ); contentItem._$show(); this.emit( 'activeContentItemChanged', contentItem ); this.emitBubblingEvent( 'stateChanged' ); }, getActiveContentItem: function() { return this.header.activeContentItem; }, addChild: function( contentItem, index ) { contentItem = this.layoutManager._$normalizeContentItem( contentItem, this ); lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index ); this.childElementContainer.append( contentItem.element ); this.header.createTab( contentItem, index ); this.setActiveContentItem( contentItem ); this.callDownwards( 'setSize' ); this._$validateClosability(); this.emitBubblingEvent( 'stateChanged' ); }, removeChild: function( contentItem, keepChild ) { var index = lm.utils.indexOf( contentItem, this.contentItems ); lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild ); this.header.removeTab( contentItem ); if( this.contentItems.length > 0 ) { this.setActiveContentItem( this.contentItems[ Math.max( index -1 , 0 ) ] ); } else { this._activeContentItem = null; } this._$validateClosability(); this.emitBubblingEvent( 'stateChanged' ); }, /** * Validates that the stack is still closable or not. If a stack is able * to close, but has a non closable component added to it, the stack is no * longer closable until all components are closable. * * @returns {void} */ _$validateClosability: function() { var contentItem, isClosable, len, i; isClosable = this.header._isClosable(); for ( i = 0, len = this.contentItems.length; i < len; i++ ) { if (!isClosable) { break; } isClosable = this.contentItems[ i ].config.isClosable; } this.header._$setClosable( isClosable ); }, _$destroy: function() { lm.items.AbstractContentItem.prototype._$destroy.call( this ); this.header._$destroy(); }, /** * Ok, this one is going to be the tricky one: The user has dropped {contentItem} onto this stack. * * It was dropped on either the stacks header or the top, right, bottom or left bit of the content area * (which one of those is stored in this._dropSegment). Now, if the user has dropped on the header the case * is relatively clear: We add the item to the existing stack... job done (might be good to have * tab reordering at some point, but lets not sweat it right now) * * If the item was dropped on the content part things are a bit more complicated. If it was dropped on either the * top or bottom region we need to create a new column and place the items accordingly. * Unless, of course if the stack is already within a column... in which case we want * to add the newly created item to the existing column... * either prepend or append it, depending on wether its top or bottom. * * Same thing for rows and left / right drop segments... so in total there are 9 things that can potentially happen * (left, top, right, bottom) * is child of the right parent (row, column) + header drop * * @param {lm.item} contentItem * * @returns {void} */ _$onDrop: function( contentItem ) { /* * The item was dropped on the header area. Just add it as a child of this stack and * get the hell out of this logic */ if( this._dropSegment === 'header' ) { this._resetHeaderDropZone(); this.addChild( contentItem, this._dropIndex ); return; } /* * The stack is empty. Let's just add the element. */ if( this._dropSegment === 'body' ) { this.addChild( contentItem ); return; } /* * The item was dropped on the top-, left-, bottom- or right- part of the content. Let's * aggregate some conditions to make the if statements later on more readable */ var isVertical = this._dropSegment === 'top' || this._dropSegment === 'bottom', isHorizontal = this._dropSegment === 'left' || this._dropSegment === 'right', insertBefore = this._dropSegment === 'top' || this._dropSegment === 'left', hasCorrectParent = ( isVertical && this.parent.isColumn ) || ( isHorizontal && this.parent.isRow ), type = isVertical ? 'column' : 'row', dimension = isVertical ? 'height' : 'width', index, stack, rowOrColumn; /* * The content item can be either a component or a stack. If it is a component, wrap it into a stack */ if( contentItem.isComponent ) { stack = this.layoutManager.createContentItem({ type: 'stack' }, this ); stack._$init(); stack.addChild( contentItem ); contentItem = stack; } /* * If the item is dropped on top or bottom of a column or left and right of a row, it's already * layd out in the correct way. Just add it as a child */ if( hasCorrectParent ) { index = lm.utils.indexOf( this, this.parent.contentItems ); this.parent.addChild( contentItem, insertBefore ? index : index + 1, true ); this.config[ dimension ] *= 0.5; contentItem.config[ dimension ] = this.config[ dimension ]; this.parent.callDownwards( 'setSize' ); /* * This handles items that are dropped on top or bottom of a row or left / right of a column. We need * to create the appropriate contentItem for them to live in */ } else { type = isVertical ? 'column' : 'row'; rowOrColumn = this.layoutManager.createContentItem({ type: type }, this ); this.parent.replaceChild( this, rowOrColumn ); rowOrColumn.addChild( contentItem, insertBefore ? 0 : undefined, true ); rowOrColumn.addChild( this, insertBefore ? undefined : 0, true ); this.config[ dimension ] = 50; contentItem.config[ dimension ] = 50; rowOrColumn.callDownwards( 'setSize' ); } }, /** * If the user hovers above the header part of the stack, indicate drop positions for tabs. * otherwise indicate which segment of the body the dragged item would be dropped on * * @param {Int} x Absolute Screen X * @param {Int} y Absolute Screen Y * * @returns {void} */ _$highlightDropZone: function( x, y ) { var segment, area; for( segment in this._contentAreaDimensions ) { area = this._contentAreaDimensions[ segment ].hoverArea; if( area.x1 < x && area.x2 > x && area.y1 < y && area.y2 > y ) { if( segment === 'header' ) { this._dropSegment = 'header'; this._highlightHeaderDropZone( x ); } else { this._resetHeaderDropZone(); this._highlightBodyDropZone( segment ); } return; } } }, _$getArea: function() { if( this.element.is( ':visible' ) === false ) { return null; } var getArea = lm.items.AbstractContentItem.prototype._$getArea, headerArea = getArea.call( this, this.header.element ), contentArea = getArea.call( this, this.childElementContainer ), contentWidth = contentArea.x2 - contentArea.x1, contentHeight = contentArea.y2 - contentArea.y1; this._contentAreaDimensions = { header: { hoverArea: { x1: headerArea.x1, y1: headerArea.y1, x2: headerArea.x2, y2: headerArea.y2 }, highlightArea: { x1: headerArea.x1, y1: headerArea.y1, x2: headerArea.x2, y2: headerArea.y2 } } }; /** * If this Stack is a parent to rows, columns or other stacks only its * header is a valid dropzone. */ if( this._activeContentItem && this._activeContentItem.isComponent === false ) { return headerArea; } /** * Highlight the entire body if the stack is empty */ if( this.contentItems.length === 0 ) { this._contentAreaDimensions.body = { hoverArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y2 }, highlightArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y2 } }; return getArea.call( this, this.element ); } this._contentAreaDimensions.left = { hoverArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x1 + contentWidth * 0.25, y2: contentArea.y2 }, highlightArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x1 + contentWidth * 0.5, y2: contentArea.y2 } }; this._contentAreaDimensions.top = { hoverArea: { x1: contentArea.x1 + contentWidth * 0.25, y1: contentArea.y1, x2: contentArea.x1 + contentWidth * 0.75, y2: contentArea.y1 + contentHeight * 0.5 }, highlightArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y1 + contentHeight * 0.5 } }; this._contentAreaDimensions.right = { hoverArea: { x1: contentArea.x1 + contentWidth * 0.75, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y2 }, highlightArea: { x1: contentArea.x1 + contentWidth * 0.5, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y2 } }; this._contentAreaDimensions.bottom = { hoverArea: { x1: contentArea.x1 + contentWidth * 0.25, y1: contentArea.y1 + contentHeight * 0.5, x2: contentArea.x1 + contentWidth * 0.75, y2: contentArea.y2 }, highlightArea: { x1: contentArea.x1, y1: contentArea.y1 + contentHeight * 0.5, x2: contentArea.x2, y2: contentArea.y2 } }; return getArea.call( this, this.element ); }, _highlightHeaderDropZone: function( x ) { var i, tabElement, tabsLength = this.header.tabs.length, isAboveTab = false, tabTop, tabLeft, offset, placeHolderLeft, headerOffset, tabWidth, halfX; // Empty stack if( tabsLength === 0 ) { headerOffset = this.header.element.offset(); this.layoutManager.dropTargetIndicator.highlightArea({ x1: headerOffset.left, x2: headerOffset.left + 100, y1: headerOffset.top + this.header.element.height() - 20, y2: headerOffset.top + this.header.element.height() }); return; } for( i = 0; i < tabsLength; i++ ) { tabElement = this.header.tabs[ i ].element; offset = tabElement.offset(); tabLeft = offset.left; tabTop = offset.top; tabWidth = tabElement.width(); if( x > tabLeft && x < tabLeft + tabWidth ) { isAboveTab = true; break; } } if( isAboveTab === false && x < tabLeft ) { return; } halfX = tabLeft + tabWidth / 2; if( x < halfX ) { this._dropIndex = i; tabElement.before( this.layoutManager.tabDropPlaceholder ); } else { this._dropIndex = Math.min( i + 1, tabsLength ); tabElement.after( this.layoutManager.tabDropPlaceholder ); } placeHolderLeft = this.layoutManager.tabDropPlaceholder.offset().left; this.layoutManager.dropTargetIndicator.highlightArea({ x1: placeHolderLeft, x2: placeHolderLeft + this.layoutManager.tabDropPlaceholder.width(), y1: tabTop, y2: tabTop + tabElement.innerHeight() }); }, _resetHeaderDropZone: function() { this.layoutManager.tabDropPlaceholder.remove(); }, _highlightBodyDropZone: function( segment ) { var highlightArea = this._contentAreaDimensions[ segment ].highlightArea; this.layoutManager.dropTargetIndicator.highlightArea( highlightArea ); this._dropSegment = segment; } }); lm.utils.BubblingEvent = function( name, origin ) { this.name = name; this.origin = origin; this.isPropagationStopped = false; }; lm.utils.BubblingEvent.prototype.stopPropagation = function() { this.isPropagationStopped = true; }; /** * Minifies and unminifies configs by replacing frequent keys * and values with one letter substitutes * * @constructor */ lm.utils.ConfigMinifier = function(){ this._keys = [ 'settings', 'hasHeaders', 'constrainDragToContainer', 'selectionEnabled', 'dimensions', 'borderWidth', 'minItemHeight', 'minItemWidth', 'headerHeight', 'dragProxyWidth', 'dragProxyHeight', 'labels', 'close', 'maximise', 'minimise', 'popout', 'content', 'componentName', 'componentState', 'id', 'width', 'type', 'height', 'isClosable', 'title', 'popoutWholeStack', 'openPopouts', 'parentId', 'activeItemIndex', 'reorderEnabled' //Maximum 36 entries, do not cross this line! ]; this._values = [ true, false, 'row', 'column', 'stack', 'component', 'close', 'maximise', 'minimise', 'open in new window' ]; }; lm.utils.copy( lm.utils.ConfigMinifier.prototype, { /** * Takes a GoldenLayout configuration object and * replaces its keys and values recursively with * one letter counterparts * * @param {Object} config A GoldenLayout config object * * @returns {Object} minified config */ minifyConfig: function( config ) { var min = {}; this._nextLevel( config, min, '_min' ); return min; }, /** * Takes a configuration Object that was previously minified * using minifyConfig and returns its original version * * @param {Object} minifiedConfig * * @returns {Object} the original configuration */ unminifyConfig: function( minifiedConfig ) { var orig = {}; this._nextLevel( minifiedConfig, orig, '_max' ); return orig; }, /** * Recursive function, called for every level of the config structure * * @param {Array|Object} orig * @param {Array|Object} min * @param {String} translationFn * * @returns {void} */ _nextLevel: function( from, to, translationFn ) { var key, minKey; for( key in from ) { /** * For in returns array indices as keys, so let's cast them to numbers */ if( from instanceof Array ) key = parseInt( key, 10 ); /** * In case something has extended Object prototypes */ if( !from.hasOwnProperty( key ) ) continue; /** * Translate the key to a one letter substitute */ minKey = this[ translationFn ]( key, this._keys ); /** * For Arrays and Objects, create a new Array/Object * on the minified object and recurse into it */ if( typeof from[ key ] === 'object' ) { to[ minKey ] = from[ key ] instanceof Array ? [] : {}; this._nextLevel( from[ key ], to[ minKey ], translationFn ); /** * For primitive values (Strings, Numbers, Boolean etc.) * minify the value */ } else { to[ minKey ] = this[ translationFn ]( from[ key ], this._values ); } } }, /** * Minifies value based on a dictionary * * @param {String|Boolean} value * @param {Array<String|Boolean>} dictionary * * @returns {String} The minified version */ _min: function( value, dictionary ) { /** * If a value actually is a single character, prefix it * with ___ to avoid mistaking it for a minification code */ if( typeof value === 'string' && value.length === 1 ) { return '___' + value; } var index = lm.utils.indexOf( value, dictionary ); /** * value not found in the dictionary, return it unmodified */ if( index === -1 ) { return value; /** * value found in dictionary, return its base36 counterpart */ } else { return index.toString( 36 ); } }, _max: function( value, dictionary ) { /** * value is a single character. Assume that it's a translation * and return the original value from the dictionary */ if( typeof value === 'string' && value.length === 1 ) { return dictionary[ parseInt( value, 36 ) ]; } /** * value originally was a single character and was prefixed with ___ * to avoid mistaking it for a translation. Remove the prefix * and return the original character */ if( typeof value === 'string' && value.substr( 0, 3 ) === '___' ) { return value[ 3 ]; } /** * value was not minified */ return value; } }); /** * An EventEmitter singleton that propagates events * across multiple windows. This is a little bit trickier since * windows are allowed to open childWindows in their own right * * This means that we deal with a tree of windows. Hence the rules for event propagation are: * * - Propagate events from this layout to both parents and children * - Propagate events from parent to this and children * - Propagate events from children to the other children (but not the emitting one) and the parent * * @constructor * * @param {lm.LayoutManager} layoutManager */ lm.utils.EventHub = function( layoutManager ) { lm.utils.EventEmitter.call( this ); this._layoutManager = layoutManager; this._dontPropagateToParent = null; this._childEventSource = null; this.on( lm.utils.EventEmitter.ALL_EVENT, lm.utils.fnBind( this._onEventFromThis, this ) ); this._boundOnEventFromChild = lm.utils.fnBind( this._onEventFromChild, this ); $(window).on( 'gl_child_event', this._boundOnEventFromChild ); }; /** * Called on every event emitted on this eventHub, regardles of origin. * * @private * * @param {Mixed} * * @returns {void} */ lm.utils.EventHub.prototype._onEventFromThis = function() { var args = Array.prototype.slice.call( arguments ); if( this._layoutManager.isSubWindow && args[ 0 ] !== this._dontPropagateToParent ) { this._propagateToParent( args ); } this._propagateToChildren( args ); //Reset this._dontPropagateToParent = null; this._childEventSource = null; }; /** * Called by the parent layout. * * @param {Array} args Event name + arguments * * @returns {void} */ lm.utils.EventHub.prototype._$onEventFromParent = function( args ) { this._dontPropagateToParent = args[ 0 ]; this.emit.apply( this, args ); }; /** * Callback for child events raised on the window * * @param {DOMEvent} event * @private * * @returns {void} */ lm.utils.EventHub.prototype._onEventFromChild = function( event ) { this._childEventSource = event.originalEvent.__gl; this.emit.apply( this, event.originalEvent.__glArgs ); }; /** * Propagates the event to the parent by emitting * it on the parent's DOM window * * @param {Array} args Event name + arguments * @private * * @returns {void} */ lm.utils.EventHub.prototype._propagateToParent = function( args ) { var event, eventName = 'gl_child_event'; if (document.createEvent) { event = window.opener.document.createEvent( 'HTMLEvents' ); event.initEvent( eventName, true, true); } else { event = window.opener.document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; event.__glArgs = args; event.__gl = this._layoutManager; if (document.createEvent) { window.opener.dispatchEvent(event); } else { window.opener.fireEvent( 'on' + event.eventType, event ); } }; /** * Propagate events to children * * @param {Array} args Event name + arguments * @private * * @returns {void} */ lm.utils.EventHub.prototype._propagateToChildren = function( args ) { var childGl, i; for( i = 0; i < this._layoutManager.openPopouts.length; i++ ) { childGl = this._layoutManager.openPopouts[ i ].getGlInstance(); if( childGl !== this._childEventSource ) { childGl.eventHub._$onEventFromParent( args ); } } }; /** * Destroys the EventHub * * @public * @returns {void} */ lm.utils.EventHub.prototype.destroy = function() { $(window).off( 'gl_child_event', this._boundOnEventFromChild ); }; /** * A specialised GoldenLayout component that binds GoldenLayout container * lifecycle events to react components * * @constructor * * @param {lm.container.ItemContainer} container * @param {Object} state state is not required for react components */ lm.utils.ReactComponentHandler = function( container, state ) { this._reactComponent = null; this._originalComponentWillUpdate = null; this._container = container; this._initialState = state; this._reactClass = this._getReactClass(); this._container.on( 'open', this._render, this ); this._container.on( 'destroy', this._destroy, this ); }; lm.utils.copy( lm.utils.ReactComponentHandler.prototype, { /** * Creates the react class and component and hydrates it with * the initial state - if one is present * * By default, react's getInitialState will be used * * @private * @returns {void} */ _render: function() { this._reactComponent = ReactDOM.render( this._getReactComponent(), this._container.getElement()[ 0 ]); this._originalComponentWillUpdate = this._reactComponent.componentWillUpdate || function(){}; this._reactComponent.componentWillUpdate = this._onUpdate.bind( this ); if( this._container.getState() ) { this._reactComponent.setState( this._container.getState() ); } }, /** * Removes the component from the DOM and thus invokes React's unmount lifecycle * * @private * @returns {void} */ _destroy: function() { ReactDOM.unmountComponentAtNode( this._container.getElement()[ 0 ]); this._container.off( 'open', this._render, this ); this._container.off( 'destroy', this._destroy, this ); }, /** * Hooks into React's state management and applies the componentstate * to GoldenLayout * * @private * @returns {void} */ _onUpdate: function( nextProps, nextState ) { this._container.setState( nextState ); this._originalComponentWillUpdate.call( this._reactComponent, nextProps, nextState ); }, /** * Retrieves the react class from GoldenLayout's registry * * @private * @returns {React.Class} */ _getReactClass: function() { var componentName = this._container._config.component; var reactClass; if( !componentName ) { throw new Error( 'No react component name. type: react-component needs a field `component`' ); } reactClass = this._container.layoutManager.getComponent( componentName ); if( !reactClass ) { throw new Error( 'React component "' + componentName + '" not found. ' + 'Please register all components with GoldenLayout using `registerComponent(name, component)`' ); } return reactClass; }, /** * Copies and extends the properties array and returns the React element * * @private * @returns {React.Element} */ _getReactComponent: function() { var defaultProps = { glEventHub: this._container.layoutManager.eventHub, glContainer: this._container, }; var props = $.extend( defaultProps, this._container._config.props ); return React.createElement( this._reactClass, props ); } });})(window.$);
example/src/components/SliderEntry.js
archriss/react-native-snap-carousel
import React, { Component } from 'react'; import { View, Text, Image, TouchableOpacity } from 'react-native'; import PropTypes from 'prop-types'; import { ParallaxImage } from 'react-native-snap-carousel'; import styles from '../styles/SliderEntry.style'; export default class SliderEntry extends Component { static propTypes = { data: PropTypes.object.isRequired, even: PropTypes.bool, parallax: PropTypes.bool, parallaxProps: PropTypes.object }; get image () { const { data: { illustration }, parallax, parallaxProps, even } = this.props; return parallax ? ( <ParallaxImage source={{ uri: illustration }} containerStyle={[styles.imageContainer, even ? styles.imageContainerEven : {}]} style={styles.image} parallaxFactor={0.35} showSpinner={true} spinnerColor={even ? 'rgba(255, 255, 255, 0.4)' : 'rgba(0, 0, 0, 0.25)'} {...parallaxProps} /> ) : ( <Image source={{ uri: illustration }} style={styles.image} /> ); } render () { const { data: { title, subtitle }, even } = this.props; const uppercaseTitle = title ? ( <Text style={[styles.title, even ? styles.titleEven : {}]} numberOfLines={2} > { title.toUpperCase() } </Text> ) : false; return ( <TouchableOpacity activeOpacity={1} style={styles.slideInnerContainer} onPress={() => { alert(`You've clicked '${title}'`); }} > <View style={styles.shadow} /> <View style={[styles.imageContainer, even ? styles.imageContainerEven : {}]}> { this.image } <View style={[styles.radiusMask, even ? styles.radiusMaskEven : {}]} /> </View> <View style={[styles.textContainer, even ? styles.textContainerEven : {}]}> { uppercaseTitle } <Text style={[styles.subtitle, even ? styles.subtitleEven : {}]} numberOfLines={2} > { subtitle } </Text> </View> </TouchableOpacity> ); } }
assets/javascripts/sso/components/AdminListMemberCard.js
wchaoyi/sso
import StyleSheet from 'react-style'; import React from 'react'; import {Admin} from '../models/Models'; let AdminListMemberCard = React.createClass({ getInitialState() { return { members: [], }; }, componentWillMount() { this.reload(); }, componentWillReceiveProps(nextProps){ const {token, tokenType, group} = nextProps; const members = this.state.members; Admin.listMembers(group, token, tokenType, (members) => { this.setState({ members }); }); }, render() { const {group} = this.props; return ( <div className="mdl-card mdl-shadow--2dp" styles={[this.styles.card, this.props.style]}> <div className="mdl-card__title"> <h2 className="mdl-card__title-text">{group}组用户列表</h2> </div> <table className="mdl-data-table mdl-js-data-table" style={this.styles.table}> <thead> <tr> <th className="mdl-data-table__cell--non-numeric">用户名</th> <th className="mdl-data-table__cell--non-numeric">身份</th> <th className="mdl-data-table__cell--non-numeric"></th> </tr> </thead> <tbody> { this.state.members.map((user, index) => { return ( <tr key={`member-${index}`}> <td className="mdl-data-table__cell--non-numeric">{user.name}</td> <td className="mdl-data-table__cell--non-numeric">{user.role === "admin" ? "管理员" : "成员"}</td> <td className="mdl-data-table__cell--non-numeric"> { user.role === 'admin' ? null : <a href="javascript:;" onClick={(evt) => this.deleteMember(user.name)}>删除</a> } </td> </tr> ); }) } </tbody> </table> <div className="mdl-card__actions"> <button className="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--colored" onClick={this.reload}>刷新</button> </div> </div> ); }, deleteMember(name) { let yes = confirm(`确定要踢掉用户 - ${name} 吗?`); if (yes) { const {group, token, tokenType} = this.props; Admin.deleteMember(group, token, tokenType, name, (ok, status) => ok ? this.reload() : alert(status)); } }, reload() { const {token, tokenType, group} = this.props; Admin.listMembers(group, token, tokenType, (members) => { this.setState({ members }); }); }, styles: StyleSheet.create({ card: { width: '100%', marginBottom: 16, minHeight: 50, }, table: { width: '100%', borderLeft: 'none', borderRight: 'none', }, }), }); export default AdminListMemberCard;
examples/js/shopping-list-redux-hoc/client/components/ShoppingListCreator.js
reimagined/resolve
import React from 'react' import { Button, Col, FormLabel, FormControl, Row } from 'react-bootstrap' import { v4 as uuid } from 'uuid' class ShoppingListCreator extends React.PureComponent { constructor() { super(...arguments) this.state = { shoppingListName: '', } this.updateShoppingListName = (event) => { this.setState({ shoppingListName: event.target.value, }) } this.onShoppingListNamePressEnter = (event) => { if (event.charCode === 13) { event.preventDefault() this.createList() } } this.createList = () => { this.props.createShoppingList(uuid(), { name: this.state.shoppingListName || `Shopping List ${this.props.lists.length + 1}`, }) this.setState({ shoppingListName: '', }) } } render() { return ( <div> <FormLabel>Shopping list name</FormLabel> <Row> <Col md={8}> <FormControl className="example-form-control" type="text" value={this.state.shoppingListName} onChange={this.updateShoppingListName} onKeyPress={this.onShoppingListNamePressEnter} /> </Col> <Col md={4}> <Button className="example-button" variant="success" onClick={this.createList} > Add Shopping List </Button> </Col> </Row> </div> ) } } export default ShoppingListCreator
src/svg-icons/action/compare-arrows.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCompareArrows = (props) => ( <SvgIcon {...props}> <path d="M9.01 14H2v2h7.01v3L13 15l-3.99-4v3zm5.98-1v-3H22V8h-7.01V5L11 9l3.99 4z"/> </SvgIcon> ); ActionCompareArrows = pure(ActionCompareArrows); ActionCompareArrows.displayName = 'ActionCompareArrows'; ActionCompareArrows.muiName = 'SvgIcon'; export default ActionCompareArrows;
src/components/SocialActivities.js
qkevinto/kevinto.me
import React from 'react'; import { root, header, heading, list, listItem } from './SocialActivities.module.scss'; import * as content from '../utils/content'; import Github from './Github'; import Trakt from './Trakt'; import LastFm from './LastFm'; export default class SocialActivities extends React.Component { render() { return ( <aside className={root} aria-label={content.name + ' \'s social activities'}> <header className={header}> <h2 className={heading}>Elsewhere on the internets&hellip;</h2> </header> <ul className={list} aria-label="Elsewhere on the internets&hellip;"> <li className={listItem}> <Github></Github> </li> <li className={listItem}> <LastFm></LastFm> </li> <li className={listItem}> <Trakt></Trakt> </li> </ul> </aside> ); } }
src/pages/vov.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Vov' /> )
packages/material-ui-icons/src/LocalParkingSharp.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M13 3H6v18h4v-6h3c3.31 0 6-2.69 6-6s-2.69-6-6-6zm.2 8H10V7h3.2c1.1 0 2 .9 2 2s-.9 2-2 2z" /></React.Fragment> , 'LocalParkingSharp');
src/routes/Oppgave1Fasit/components/Oppgave1View.js
andreasnc/summer-project-tasks-2017
import React from 'react'; import StarWarsCharacter from './StarWarsCharacter'; import Oppgave1Text from './Oppgave1Text'; const character = require('../data.json'); const Oppgave1View = () => ( <div> <h4>Oppgave 1</h4> <Oppgave1Text /> <StarWarsCharacter {...character} /> </div> ); export default Oppgave1View;
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js
ArmendGashi/react-router
import React from 'react'; import { Link } from 'react-router'; export default class AnnouncementsSidebar extends React.Component { render () { var announcements = COURSES[this.props.params.courseId].announcements; return ( <div> <h3>Sidebar Assignments</h3> <ul> {announcements.map(announcement => ( <li key={announcement.id}> <Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}> {announcement.title} </Link> </li> ))} </ul> </div> ); } }
tests/Formsy-spec.js
sdemjanenko/formsy-react
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import Formsy from './..'; import TestInput from './utils/TestInput'; import immediate from './utils/immediate'; import sinon from 'sinon'; export default { 'Setting up a form': { 'should render a form into the document': function (test) { const form = TestUtils.renderIntoDocument(<Formsy.Form></Formsy.Form>); test.equal(ReactDOM.findDOMNode(form).tagName, 'FORM'); test.done(); }, 'should set a class name if passed': function (test) { const form = TestUtils.renderIntoDocument( <Formsy.Form className="foo"></Formsy.Form>); test.equal(ReactDOM.findDOMNode(form).className, 'foo'); test.done(); }, 'should allow for null/undefined children': function (test) { let model = null; const TestForm = React.createClass({ render() { return ( <Formsy.Form onSubmit={(formModel) => (model = formModel)}> <h1>Test</h1> { null } { undefined } <TestInput name="name" value={ 'foo' } /> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); immediate(() => { TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.deepEqual(model, {name: 'foo'}); test.done(); }); }, 'should allow for inputs being added dynamically': function (test) { const inputs = []; let forceUpdate = null; let model = null; const TestForm = React.createClass({ componentWillMount() { forceUpdate = this.forceUpdate.bind(this); }, render() { return ( <Formsy.Form onSubmit={(formModel) => (model = formModel)}> {inputs} </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); // Wait before adding the input setTimeout(() => { inputs.push(<TestInput name="test" value="" key={inputs.length}/>); forceUpdate(() => { // Wait for next event loop, as that does the form immediate(() => { TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.ok('test' in model); test.done(); }); }); }, 10); }, 'should allow dynamically added inputs to update the form-model': function (test) { const inputs = []; let forceUpdate = null; let model = null; const TestForm = React.createClass({ componentWillMount() { forceUpdate = this.forceUpdate.bind(this); }, render() { return ( <Formsy.Form onSubmit={(formModel) => (model = formModel)}> {inputs} </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); // Wait before adding the input immediate(() => { inputs.push(<TestInput name="test" key={inputs.length}/>); forceUpdate(() => { // Wait for next event loop, as that does the form immediate(() => { TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'foo'}}); TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(model.test, 'foo'); test.done(); }); }); }); }, 'should allow a dynamically updated input to update the form-model': function (test) { let forceUpdate = null; let model = null; const TestForm = React.createClass({ componentWillMount() { forceUpdate = this.forceUpdate.bind(this); }, render() { const input = <TestInput name="test" value={this.props.value} />; return ( <Formsy.Form onSubmit={(formModel) => (model = formModel)}> {input} </Formsy.Form>); } }); let form = TestUtils.renderIntoDocument(<TestForm value="foo"/>); // Wait before changing the input immediate(() => { form = TestUtils.renderIntoDocument(<TestForm value="bar"/>); forceUpdate(() => { // Wait for next event loop, as that does the form immediate(() => { TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(model.test, 'bar'); test.done(); }); }); }); } }, 'validations': { 'should run when the input changes': function (test) { const runRule = sinon.spy(); const notRunRule = sinon.spy(); Formsy.addValidationRule('runRule', runRule); Formsy.addValidationRule('notRunRule', notRunRule); const form = TestUtils.renderIntoDocument( <Formsy.Form> <TestInput name="one" validations="runRule" value="foo"/> </Formsy.Form> ); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(runRule.calledWith({one: 'bar'}, 'bar', true), true); test.equal(notRunRule.called, false); test.done(); }, 'should allow the validation to be changed': function (test) { const ruleA = sinon.spy(); const ruleB = sinon.spy(); Formsy.addValidationRule('ruleA', ruleA); Formsy.addValidationRule('ruleB', ruleB); class TestForm extends React.Component { constructor(props) { super(props); this.state = {rule: 'ruleA'}; } changeRule() { this.setState({ rule: 'ruleB' }); } render() { return ( <Formsy.Form> <TestInput name="one" validations={this.state.rule} value="foo"/> </Formsy.Form> ); } } const form = TestUtils.renderIntoDocument(<TestForm/>); form.changeRule(); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(ruleB.calledWith({one: 'bar'}, 'bar', true), true); test.done(); }, 'should invalidate a form if dynamically inserted input is invalid': function (test) { const isInValidSpy = sinon.spy(); class TestForm extends React.Component { constructor(props) { super(props); this.state = {showSecondInput: false}; } addInput() { this.setState({ showSecondInput: true }); } render() { return ( <Formsy.Form ref="formsy" onInvalid={isInValidSpy}> <TestInput name="one" validations="isEmail" value="[email protected]"/> { this.state.showSecondInput ? <TestInput name="two" validations="isEmail" value="foo@bar"/> : null } </Formsy.Form> ); } } const form = TestUtils.renderIntoDocument(<TestForm/>); test.equal(form.refs.formsy.state.isValid, true); form.addInput(); immediate(() => { test.equal(isInValidSpy.called, true); test.done(); }); }, 'should validate a form when removing an invalid input': function (test) { const isValidSpy = sinon.spy(); class TestForm extends React.Component { constructor(props) { super(props); this.state = {showSecondInput: true}; } removeInput() { this.setState({ showSecondInput: false }); } render() { return ( <Formsy.Form ref="formsy" onValid={isValidSpy}> <TestInput name="one" validations="isEmail" value="[email protected]"/> { this.state.showSecondInput ? <TestInput name="two" validations="isEmail" value="foo@bar"/> : null } </Formsy.Form> ); } } const form = TestUtils.renderIntoDocument(<TestForm/>); test.equal(form.refs.formsy.state.isValid, false); form.removeInput(); immediate(() => { test.equal(isValidSpy.called, true); test.done(); }); }, 'runs multiple validations': function (test) { const ruleA = sinon.spy(); const ruleB = sinon.spy(); Formsy.addValidationRule('ruleA', ruleA); Formsy.addValidationRule('ruleB', ruleB); const form = TestUtils.renderIntoDocument( <Formsy.Form> <TestInput name="one" validations="ruleA,ruleB" value="foo" /> </Formsy.Form> ); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(ruleA.calledWith({one: 'bar'}, 'bar', true), true); test.equal(ruleB.calledWith({one: 'bar'}, 'bar', true), true); test.done(); } }, 'should not trigger onChange when form is mounted': function (test) { const hasChanged = sinon.spy(); const TestForm = React.createClass({ render() { return <Formsy.Form onChange={hasChanged}></Formsy.Form>; } }); TestUtils.renderIntoDocument(<TestForm/>); test.equal(hasChanged.called, false); test.done(); }, 'should trigger onChange once when form element is changed': function (test) { const hasChanged = sinon.spy(); const form = TestUtils.renderIntoDocument( <Formsy.Form onChange={hasChanged}> <TestInput name="foo"/> </Formsy.Form> ); TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'bar'}}); test.equal(hasChanged.calledOnce, true); test.done(); }, 'should trigger onChange once when new input is added to form': function (test) { const hasChanged = sinon.spy(); const TestForm = React.createClass({ getInitialState() { return { showInput: false }; }, addInput() { this.setState({ showInput: true }) }, render() { return ( <Formsy.Form onChange={hasChanged}> { this.state.showInput ? <TestInput name="test"/> : null } </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); form.addInput(); immediate(() => { test.equal(hasChanged.calledOnce, true); test.done(); }); }, 'Update a form': { 'should allow elements to check if the form is disabled': function (test) { const TestForm = React.createClass({ getInitialState() { return { disabled: true }; }, enableForm() { this.setState({ disabled: false }); }, render() { return ( <Formsy.Form disabled={this.state.disabled}> <TestInput name="foo"/> </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(input.isFormDisabled(), true); form.enableForm(); immediate(() => { test.equal(input.isFormDisabled(), false); test.done(); }); }, 'should be possible to pass error state of elements by changing an errors attribute': function (test) { const TestForm = React.createClass({ getInitialState() { return { validationErrors: { foo: 'bar' } }; }, onChange(values) { this.setState(values.foo ? { validationErrors: {} } : { validationErrors: {foo: 'bar'} }); }, render() { return ( <Formsy.Form onChange={this.onChange} validationErrors={this.state.validationErrors}> <TestInput name="foo"/> </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); // Wait for update immediate(() => { const input = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(input.getErrorMessage(), 'bar'); input.setValue('gotValue'); // Wait for update immediate(() => { test.equal(input.getErrorMessage(), null); test.done(); }); }); }, 'should trigger an onValidSubmit when submitting a valid form': function (test) { let isCalled = sinon.spy(); const TestForm = React.createClass({ render() { return ( <Formsy.Form onValidSubmit={isCalled}> <TestInput name="foo" validations="isEmail" value="[email protected]"/> </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const FoundForm = TestUtils.findRenderedComponentWithType(form, TestForm); TestUtils.Simulate.submit(ReactDOM.findDOMNode(FoundForm)); test.equal(isCalled.called,true); test.done(); }, 'should trigger an onInvalidSubmit when submitting an invalid form': function (test) { let isCalled = sinon.spy(); const TestForm = React.createClass({ render() { return ( <Formsy.Form onInvalidSubmit={isCalled}> <TestInput name="foo" validations="isEmail" value="foo@bar"/> </Formsy.Form>); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const FoundForm = TestUtils.findRenderedComponentWithType(form, TestForm); TestUtils.Simulate.submit(ReactDOM.findDOMNode(FoundForm)); test.equal(isCalled.called, true); test.done(); } }, 'value === false': { 'should call onSubmit correctly': function (test) { const onSubmit = sinon.spy(); const TestForm = React.createClass({ render() { return ( <Formsy.Form onSubmit={onSubmit}> <TestInput name="foo" value={false} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(onSubmit.calledWith({foo: false}), true); test.done(); }, 'should allow dynamic changes to false': function (test) { const onSubmit = sinon.spy(); const TestForm = React.createClass({ getInitialState() { return { value: true }; }, changeValue() { this.setState({ value: false }); }, render() { return ( <Formsy.Form onSubmit={onSubmit}> <TestInput name="foo" value={this.state.value} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); form.changeValue(); TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(onSubmit.calledWith({foo: false}), true); test.done(); }, 'should say the form is submitted': function (test) { const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" value={true} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(input.isFormSubmitted(), false); TestUtils.Simulate.submit(ReactDOM.findDOMNode(form)); test.equal(input.isFormSubmitted(), true); test.done(); }, 'should be able to reset the form to its pristine state': function (test) { const TestForm = React.createClass({ getInitialState() { return { value: true }; }, changeValue() { this.setState({ value: false }); }, render() { return ( <Formsy.Form> <TestInput name="foo" value={this.state.value} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form); test.equal(input.getValue(), true); form.changeValue(); test.equal(input.getValue(), false); formsyForm.reset(); test.equal(input.getValue(), true); test.done(); }, 'should be able to reset the form using custom data': function (test) { const TestForm = React.createClass({ getInitialState() { return { value: true }; }, changeValue() { this.setState({ value: false }); }, render() { return ( <Formsy.Form> <TestInput name="foo" value={this.state.value} type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form); test.equal(input.getValue(), true); form.changeValue(); test.equal(input.getValue(), false); formsyForm.reset({ foo: 'bar' }); test.equal(input.getValue(), 'bar'); test.done(); } }, 'should be able to reset the form to empty values': function (test) { const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" value="42" type="checkbox" /> <button type="submit">Save</button> </Formsy.Form> ); } }); const form = TestUtils.renderIntoDocument(<TestForm/>); const input = TestUtils.findRenderedComponentWithType(form, TestInput); const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form); formsyForm.reset({ foo: '' }); test.equal(input.getValue(), ''); test.done(); }, '.isChanged()': { 'initially returns false': function (test) { const hasOnChanged = sinon.spy(); const form = TestUtils.renderIntoDocument( <Formsy.Form onChange={hasOnChanged}> <TestInput name="one" value="foo" /> </Formsy.Form> ); test.equal(form.isChanged(), false); test.equal(hasOnChanged.called, false); test.done(); }, 'returns true when changed': function (test) { const hasOnChanged = sinon.spy(); const form = TestUtils.renderIntoDocument( <Formsy.Form onChange={hasOnChanged}> <TestInput name="one" value="foo" /> </Formsy.Form> ); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(form.isChanged(), true); test.equal(hasOnChanged.calledWith({one: 'bar'}), true); test.done(); }, 'returns false if changes are undone': function (test) { const hasOnChanged = sinon.spy(); const form = TestUtils.renderIntoDocument( <Formsy.Form onChange={hasOnChanged}> <TestInput name="one" value="foo" /> </Formsy.Form> ); const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}}); test.equal(hasOnChanged.calledWith({one: 'bar'}, true), true); TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'foo'}}); test.equal(form.isChanged(), false); test.equal(hasOnChanged.calledWith({one: 'foo'}, false), true); test.done(); } } };
dashboard/src/components/dashboard/history/Incident.js
leapfrogtechnology/chill
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import ToolTip from 'react-tooltip'; import { getFormattedDate } from '../../../utils/date'; import * as statusService from '../../../services/status'; /** * Renders by getting all the information of incidents * from HistoryList according to the date. * * @param {Object} data */ const Incident = ({ data }) => { const service = JSON.parse(data.service); const status = JSON.parse(data.status); const time = new Date(data.createdAt); const timestamp = time.toString(); const formattedTime = getFormattedDate(time, 'time'); const tooltipId = `tooltip-incident-${timestamp}`; const serviceStatus = statusService.getServiceStatus(status); const incidentStatusClass = classNames({ 'status-update': true, 'status-down': serviceStatus.down, 'status-success': serviceStatus.up, 'status-pending': serviceStatus.pending, 'status-under-maintenance': serviceStatus['under maintenance'] }); return ( <ul className="status-update-list"> <li className={incidentStatusClass}> {service.name} was <span className="state">{status.name.toLowerCase()}</span> on <ToolTip place="top" id={tooltipId} type="dark"> <span>{timestamp}</span> </ToolTip> <span className="time" data-tip aria-hidden="true" data-for={tooltipId}> {formattedTime}</span> </li> </ul> ); }; Incident.propTypes = { data: PropTypes.object }; export default Incident;
ReactNativeDemo/app/main/Navigator.js
zxpLearnios/ReactNativeDemo
/** * Created by jingnanzhang on 2017/5/31. */ // 这里只写tab页 import React, { Component } from 'react'; import { Button, Text, } from 'react-native'; import { TabNavigator, StackNavigator, TabBarBottom, }from 'react-navigation'; // npm install --save react-navigation 来安装词库 // 导入js类 import HomePage from '../home/Home' import MinePage from '../mine/Mine' import LoginPage from '../mine/Login' import CustomeNavigationBar from '../customeComponents/NavigationBar' import TabBarItem from '../main/TabBarItem' import NavBarItem from '../main/NavBarItem' import MineDetailPage from '../mine/MineDetail' import TestListViewPage from '../mine/TestListView' import GesturePwdPage from '../customeComponents/GesturePwd' import * as conster from '../const/Const' let navRightItemImg = require('../img/plus.png'); export default class Navigator extends Component{ render(){ return <AppNavigator/>; } test(){ } } // 几个table页面 const AppTab = TabNavigator({ HomePage: { screen: HomePage, navigationOptions: { title: '主页', tabBarIcon: ({focused, tintColor}) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('../img/icon_tabbar_misc.png')} selectedImage={require('../img/icon_tabbar_misc_selected.png')} /> ) } }, MinePage: { screen: MinePage, navigationOptions: { title: '我的', tabBarIcon: ({focused, tintColor}) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('../img/icon_tabbar_mine.png')} selectedImage={require('../img/icon_tabbar_mine_selected.png')} /> ) } }, }, // 设置 tabbar { tabBarOptions: { activeTintColor: 'orange', // 选中tabItem inactiveTintColor: 'gray', // 普通tabItem labelStyle:{fontSize: 12}, // 文字大小 style: {backgroundColor: '#fff'}, // TabBar 背景色, }, tabBarComponent: TabBarBottom, tabBarPosition: 'bottom', swipeEnabled: false, // 左右滑动 animationEnabled: false, // 页面切换时不需要动画 lazy: true, initialRouteName: 'MinePage', // 默认显示的tab MinePage HomePage backBehavior:'none', // 回调 }, ); /* * 1. 所有需要push的页面均需加入此screen组里 * 2. 下面的StackNavigator默认显示里面的第一个screen * * */ const AppNavigator = StackNavigator({ // 登录的导航栏在LoginPage设置 LoginPage:{ screen: LoginPage, // navigationOptions: CustomeNavigationBar('wetft'), // 测试自定义的导航栏 }, TabPage: { screen: AppTab, // 设置navigation NavBarItem, 使tab页左右都有按钮 navigationOptions:{ headerLeft: <NavBarItem type={'btn'} onPress={() => alert('点击了left-navigation')}/>, headerRight: <NavBarItem type={'img'} img={navRightItemImg} onPress={() => alert('点击了right-navigation')}/> }, }, MineDetail:{ screen: MineDetailPage, navigationOptions:{ headerTitle:'我的详情', }, }, TestListView:{ screen: TestListViewPage, header:{ // visible: false, // 是否顯示導航欄 }, }, GesturePwd:{ screen: GesturePwdPage, }, }, { // headerMode: 导航栏的显示模式: screen: 有渐变透明效果, float: 无透明效果, none: 隐藏导航栏 mode: this.modeType,//页面切换模式: 左右是card(相当于iOS中的push效果), 上下是- - (相当于iOS中的 效果) // onTransitionStart: ()=>{ console.log('导航栏切换开始'); }, // 回调 // onTransitionEnd: ()=>{ console.log('导航栏切换结束'); } });
public/js/src.js
hkdnet/GitRec
'use strict'; import React from 'react'; import { render } from 'react-dom'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import gitRecApp from './public/js/reducers.js' import Screen from './public/js/components/Screen.js' let store = createStore(gitRecApp); render( <Provider store={store}> <Screen /> </Provider>, document.getElementById('content') );
wrappers/yaml.js
frontendyteam/www.frontendy.com
import React from 'react' import yaml from 'js-yaml' import DocumentTitle from 'react-document-title' import { config } from 'config' module.exports = React.createClass({ propTypes () { return { route: React.PropTypes.object, } }, render () { const data = this.props.route.page.data return ( <DocumentTitle title={`${config.siteTitle} | ${data.title}`}> <div> <h1>{data.title}</h1> <p>Raw view of yaml file</p> <pre dangerouslySetInnerHTML={{ __html: yaml.safeDump(data) }} /> </div> </DocumentTitle> ) }, })
src/routes.js
ClaudiuCeia/mioritic
// @flow import React from 'react'; import { Router, Route } from 'react-router'; import Home from './components/Home'; import CoursePage from './components/CoursePage'; import NotFound from './components/NotFound'; const Routes = (props: any) => ( <Router {...props}> <Route path="/" component={Home} /> <Route path="/course/*" component={CoursePage} /> <Route path="*" component={NotFound} /> </Router> ); export default Routes;
src/averageReviewTimeReport.js
Earthstar/gerrit-report-dashboard
import React from 'react'; // "Pure Function" way of declaring React classes. Useful if don't need to store state const AverageReviewTimeReport = (props) => <div className="report-container"> <h2>Average Review Time</h2> <span className="large-report">{props.averageHours} hours</span> </div>; export { AverageReviewTimeReport };
pages/glossary.js
maven-hackathon/TheQueerTour
import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>Glossary</h1> <p>Coming soon.</p> </div> ); } }
ajax/libs/react-bootstrap-typeahead/0.1.5/react-bootstrap-typeahead.min.js
brix/cdnjs
!function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={exports:{},id:o,loaded:!1};return e[o].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),a=o(r),s=n(11),i=o(s),l=n(12),u=o(l),d=n(13),p=o(d),c=n(9),f=n(2),h=n(7),v=o(h),m=a["default"].PropTypes;n(8);var y=a["default"].createClass({displayName:"Typeahead",mixins:[v["default"]],propTypes:{defaultSelected:m.array,emptyLabel:m.string,labelKey:m.string,maxHeight:m.number,multiple:m.bool,options:m.array.isRequired,placeholder:m.string,selected:m.array},getDefaultProps:function(){return{defaultSelected:[],labelKey:"label",multiple:!1,selected:[]}},getInitialState:function(){var e=this.props,t=e.defaultSelected,n=e.selected;return{activeIndex:0,selected:(0,c.isEmpty)(t)?n:t,showMenu:!1,text:""}},componentWillReceiveProps:function(e){(0,c.isEqual)(this.props.selected,e.selected)||this.setState({selected:e.selected}),this.props.multiple!==e.multiple&&this.setState({text:""})},render:function(){var e=this.props,t=e.labelKey,n=e.multiple,o=e.options,r=this.state,s=r.activeIndex,l=r.selected,d=r.text,f=o.filter(function(e){return!(-1===e[t].toLowerCase().indexOf(d.toLowerCase())||n&&(0,c.find)(l,e))}),h=void 0;this.state.showMenu&&(h=a["default"].createElement(p["default"],{activeIndex:s,emptyLabel:this.props.emptyLabel,labelKey:t,maxHeight:this.props.maxHeight,onClick:this._handleAddOption,options:f}));var v=i["default"];return n||(v=u["default"],l=(0,c.head)(l),d=l&&l[t]||d),a["default"].createElement("div",{className:"bootstrap-typeahead open",style:{position:"relative"}},a["default"].createElement(v,{filteredOptions:f,labelKey:t,onAdd:this._handleAddOption,onChange:this._handleTextChange,onFocus:this._handleFocus,onKeyDown:this._handleKeydown.bind(null,f),onRemove:this._handleRemoveOption,placeholder:this.props.placeholder,ref:"input",selected:l,text:d}),h)},_handleFocus:function(){this.setState({showMenu:!0})},_handleTextChange:function(e){this.setState({activeIndex:0,showMenu:!0,text:e.target.value})},_handleKeydown:function(e,t){var n=this.state.activeIndex;switch(t.keyCode){case f.BACKSPACE:t.stopPropagation();break;case f.UP:t.preventDefault(),n--,0>n&&(n=e.length-1),this.setState({activeIndex:n});break;case f.DOWN:case f.TAB:t.preventDefault(),n++,n===e.length&&(n=0),this.setState({activeIndex:n});break;case f.ESC:t.stopPropagation(),this._hideDropdown();break;case f.RETURN:var o=e[n];o&&this._handleAddOption(o)}},_handleAddOption:function(e){var t=this.props,n=t.multiple,o=t.labelKey,r=t.onChange,a=void 0,s=void 0;n?(a=this.state.selected.concat(e),s=""):(a=[e],s=e[o]),this.setState({activeIndex:0,selected:a,showMenu:!1,text:s}),r&&r(a)},_handleRemoveOption:function(e){var t=this.state.selected.slice();t=t.filter(function(t){return!(0,c.isEqual)(t,e)}),this.setState({activeIndex:0,selected:t,showMenu:!1}),this.props.onChange&&this.props.onChange(t)},handleClickOutside:function(e){this._hideDropdown()},_hideDropdown:function(){this.setState({activeIndex:0,showMenu:!1})}});t["default"]=y},function(e,t){e.exports=React},function(e,t){"use strict";e.exports={BACKSPACE:8,TAB:9,RETURN:13,ESC:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40}},function(e,t,n){var o;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function r(){for(var e="",t=0;t<arguments.length;t++){var n=arguments[t];if(n){var o=typeof n;if("string"===o||"number"===o)e+=" "+n;else if(Array.isArray(n))e+=" "+r.apply(null,n);else if("object"===o)for(var s in n)a.call(n,s)&&n[s]&&(e+=" "+s)}}return e.substr(1)}var a={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=r:(o=function(){return r}.call(t,n,t,e),!(void 0!==o&&(e.exports=o)))}()},function(e,t){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var n=this[t];n[2]?e.push("@media "+n[2]+"{"+n[1]+"}"):e.push(n[1])}return e.join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var o={},r=0;r<this.length;r++){var a=this[r][0];"number"==typeof a&&(o[a]=!0)}for(r=0;r<t.length;r++){var s=t[r];"number"==typeof s[0]&&o[s[0]]||(n&&!s[2]?s[2]=n:n&&(s[2]="("+s[2]+") and ("+n+")"),e.push(s))}},e}},function(e,t,n){function o(e,t){for(var n=0;n<e.length;n++){var o=e[n],r=f[o.id];if(r){r.refs++;for(var a=0;a<r.parts.length;a++)r.parts[a](o.parts[a]);for(;a<o.parts.length;a++)r.parts.push(u(o.parts[a],t))}else{for(var s=[],a=0;a<o.parts.length;a++)s.push(u(o.parts[a],t));f[o.id]={id:o.id,refs:1,parts:s}}}}function r(e){for(var t=[],n={},o=0;o<e.length;o++){var r=e[o],a=r[0],s=r[1],i=r[2],l=r[3],u={css:s,media:i,sourceMap:l};n[a]?n[a].parts.push(u):t.push(n[a]={id:a,parts:[u]})}return t}function a(e,t){var n=m(),o=g[g.length-1];if("top"===e.insertAt)o?o.nextSibling?n.insertBefore(t,o.nextSibling):n.appendChild(t):n.insertBefore(t,n.firstChild),g.push(t);else{if("bottom"!==e.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(t)}}function s(e){e.parentNode.removeChild(e);var t=g.indexOf(e);t>=0&&g.splice(t,1)}function i(e){var t=document.createElement("style");return t.type="text/css",a(e,t),t}function l(e){var t=document.createElement("link");return t.rel="stylesheet",a(e,t),t}function u(e,t){var n,o,r;if(t.singleton){var a=b++;n=y||(y=i(t)),o=d.bind(null,n,a,!1),r=d.bind(null,n,a,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=l(t),o=c.bind(null,n),r=function(){s(n),n.href&&URL.revokeObjectURL(n.href)}):(n=i(t),o=p.bind(null,n),r=function(){s(n)});return o(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;o(e=t)}else r()}}function d(e,t,n,o){var r=n?"":o.css;if(e.styleSheet)e.styleSheet.cssText=x(t,r);else{var a=document.createTextNode(r),s=e.childNodes;s[t]&&e.removeChild(s[t]),s.length?e.insertBefore(a,s[t]):e.appendChild(a)}}function p(e,t){var n=t.css,o=t.media;t.sourceMap;if(o&&e.setAttribute("media",o),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function c(e,t){var n=t.css,o=(t.media,t.sourceMap);o&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */");var r=new Blob([n],{type:"text/css"}),a=e.href;e.href=URL.createObjectURL(r),a&&URL.revokeObjectURL(a)}var f={},h=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},v=h(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),m=h(function(){return document.head||document.getElementsByTagName("head")[0]}),y=null,b=0,g=[];e.exports=function(e,t){t=t||{},"undefined"==typeof t.singleton&&(t.singleton=v()),"undefined"==typeof t.insertAt&&(t.insertAt="bottom");var n=r(e);return o(n,t),function(e){for(var a=[],s=0;s<n.length;s++){var i=n[s],l=f[i.id];l.refs--,a.push(l)}if(e){var u=r(e);o(u,t)}for(var s=0;s<a.length;s++){var l=a[s];if(0===l.refs){for(var d=0;d<l.parts.length;d++)l.parts[d]();delete f[l.id]}}}};var x=function(){var e=[];return function(t,n){return e[t]=n,e.filter(Boolean).join("\n")}}()},function(e,t){e.exports=ReactDOM},function(e,t){e.exports=onClickOutside},function(e,t,n){var o=n(16);"string"==typeof o&&(o=[[e.id,o,""]]);n(5)(o,{});o.locals&&(e.exports=o.locals)},function(e,t){e.exports=lodash},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),a=o(r),s=n(6),i=n(3),l=o(i),u=n(2),d=o(u),p=n(7),c=o(p);n(17);var f=a["default"].createClass({displayName:"Token",mixins:[c["default"]],propTypes:{onRemove:a["default"].PropTypes.func},getInitialState:function(){return{selected:!1}},render:function(){return this.props.onRemove?this._renderRemoveableToken():this._renderToken()},_renderRemoveableToken:function(){return a["default"].createElement("button",{className:(0,l["default"])("token","token-removeable",{"token-selected":this.state.selected},this.props.className),onBlur:this._handleBlur,onClick:this._handleSelect,onFocus:this._handleSelect,onKeyDown:this._handleKeyDown,tabIndex:0},this.props.children,a["default"].createElement("span",{className:"token-close-button",onClick:this._handleRemove},"×"))},_renderToken:function(){var e=(0,l["default"])("token",this.props.className);return this.props.href?a["default"].createElement("a",{className:e,href:this.props.href},this.props.children):a["default"].createElement("div",{className:e},this.props.children)},_handleBlur:function(e){(0,s.findDOMNode)(this).blur(),this.setState({selected:!1})},_handleKeyDown:function(e){switch(e.keyCode){case d["default"].BACKSPACE:this.state.selected&&(e.preventDefault(),this._handleRemove())}},handleClickOutside:function(e){this._handleBlur()},_handleRemove:function(e){this.props.onRemove&&this.props.onRemove()},_handleSelect:function(e){e.stopPropagation(),this.setState({selected:!0})}});t["default"]=f},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};Object.defineProperty(t,"__esModule",{value:!0});var a=n(19),s=o(a),i=n(1),l=o(i),u=n(10),d=o(u),p=n(3),c=o(p),f=n(6),h=n(2),v=o(h),m=l["default"].PropTypes;n(18);var y=l["default"].createClass({displayName:"TokenizerInput",propTypes:{labelKey:m.string,placeholder:m.string,selected:m.array},render:function(){var e=this.props,t=e.className,n=e.placeholder,o=e.selected,a=e.text;return l["default"].createElement("div",{className:(0,c["default"])("bootstrap-tokenizer","form-control","clearfix",t),onClick:this._handleInputFocus,onFocus:this._handleInputFocus,tabIndex:0},o.map(this._renderToken),l["default"].createElement(s["default"],r({},this.props,{className:"bootstrap-tokenizer-input",inputStyle:{backgroundColor:"inherit",border:0,outline:"none",padding:0},onKeyDown:this._handleKeydown,placeholder:o.length?null:n,ref:"input",type:"text",value:a})))},_renderToken:function(e,t){var n=this.props,o=n.onRemove,r=n.labelKey;return l["default"].createElement(d["default"],{key:t,onRemove:o.bind(null,e)},e[r])},_handleKeydown:function(e){switch(e.keyCode){case v["default"].LEFT:case v["default"].RIGHT:break;case v["default"].BACKSPACE:var t=(0,f.findDOMNode)(this.refs.input);if(t&&t.contains(document.activeElement)&&!this.props.text){var n=t.previousSibling;n&&n.focus()}}this.props.onKeyDown&&this.props.onKeyDown(e)},_handleInputFocus:function(e){this.refs.input.focus()}});t["default"]=y},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=o(a),i=n(3),l=o(i),u=n(9),d=n(2),p=o(d),c=n(7),f=o(c),h=s["default"].PropTypes;n(8);var v=s["default"].createClass({displayName:"TypeaheadInput",mixins:[f["default"]],propTypes:{filteredOptions:h.array,labelKey:h.string,onChange:h.func,selected:h.object,text:h.string},render:function(){return s["default"].createElement("div",{className:(0,l["default"])("bootstrap-typeahead-input",this.props.className),onClick:this._handleInputFocus,onFocus:this._handleInputFocus,tabIndex:0},s["default"].createElement("input",r({},this.props,{className:(0,l["default"])("bootstrap-typeahead-input-main","form-control",{"has-selection":!this.props.selected}),onKeyDown:this._handleKeydown,ref:"input",style:{backgroundColor:"transparent",display:"block",position:"relative",zIndex:1},type:"text",value:this._getInputValue()})),s["default"].createElement("input",{className:"bootstrap-typeahead-input-hint form-control",style:{borderColor:"transparent",bottom:0,display:"block",position:"absolute",top:0,width:"100%",zIndex:0},value:this._getHintText()}))},_getInputValue:function(){var e=this.props,t=e.labelKey,n=e.selected,o=e.text;return n?n[t]:o},_getHintText:function(){var e=this.props,t=e.filteredOptions,n=e.labelKey,o=e.text,r=(0,u.head)(t);return this.refs.input===document.activeElement&&o&&r&&0===r[n].indexOf(o)?r[n]:void 0},_handleInputFocus:function(e){this.refs.input.focus()},_handleKeydown:function(e){var t=this.props,n=t.filteredOptions,o=t.onAdd,r=t.onRemove,a=t.selected;switch(e.keyCode){case p["default"].ESC:this.refs.input.blur();break;case p["default"].RIGHT:this._getHintText()&&!a&&o&&o((0,u.head)(n));break;case p["default"].BACKSPACE:a&&r&&r(a)}this.props.onKeyDown&&this.props.onKeyDown(e)},handleClickOutside:function(e){this.refs.input.blur()}});t["default"]=v},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=o(a),i=n(6),l=n(3),u=o(l),d=s["default"].PropTypes,p=s["default"].createClass({displayName:"Menu",render:function(){return s["default"].createElement("ul",r({},this.props,{className:(0,u["default"])("dropdown-menu",this.props.className)}),this.props.children)}}),c=s["default"].createClass({displayName:"MenuItem",componentWillReceiveProps:function(e){e.active&&(0,i.findDOMNode)(this).firstChild.focus()},render:function(){return s["default"].createElement("li",{className:(0,u["default"])({active:this.props.active,disabled:this.props.disabled})},s["default"].createElement("a",{href:"#",onClick:this._handleClick},this.props.children))},_handleClick:function(e){e.preventDefault(),this.props.onClick&&this.props.onClick()}}),f=s["default"].createClass({displayName:"TypeaheadMenu",propTypes:{activeIndex:d.number,emptyLabel:d.string,labelKey:d.string.isRequired,maxHeight:d.number,options:d.array},getDefaultProps:function(){return{emptyLabel:"No matches found.",maxHeight:300}},render:function(){var e=this.props,t=e.maxHeight,n=e.options,o=n.length?n.map(this._renderDropdownItem):s["default"].createElement(c,{disabled:!0},this.props.emptyLabel);return s["default"].createElement(p,{style:{maxHeight:t+"px",right:0}},o)},_renderDropdownItem:function(e,t){var n=this.props,o=n.activeIndex,r=n.onClick;return s["default"].createElement(c,{active:t===o,key:t,onClick:r.bind(null,e)},e[this.props.labelKey])}});t["default"]=f},function(e,t,n){t=e.exports=n(4)(),t.push([e.id,".token{background-color:#e7f4ff;border:0;border-radius:2px;color:#1f8dd6;display:inline-block;line-height:1em;padding:4px 7px;position:relative}.token-removeable,.token:focus{padding-right:21px}.token-selected{background-color:#1f8dd6;color:#fff;outline:none;text-decoration:none}.bootstrap-tokenizer .token{margin:0 3px 3px 0}.token-close-button{bottom:0;padding:3px 7px;position:absolute;right:0;top:0}",""])},function(e,t,n){t=e.exports=n(4)(),t.push([e.id,".bootstrap-tokenizer{cursor:text;height:auto;padding:5px 12px 2px}.bootstrap-tokenizer-input{margin:1px 0 4px}",""])},function(e,t,n){t=e.exports=n(4)(),t.push([e.id,".bootstrap-typeahead .dropdown-menu{overflow:scroll}.bootstrap-typeahead .dropdown-menu>li a:focus{outline:none}.bootstrap-typeahead-input-hint{color:#aaa}",""])},function(e,t,n){var o=n(14);"string"==typeof o&&(o=[[e.id,o,""]]);n(5)(o,{});o.locals&&(e.exports=o.locals)},function(e,t,n){var o=n(15);"string"==typeof o&&(o=[[e.id,o,""]]);n(5)(o,{});o.locals&&(e.exports=o.locals)},function(e,t){e.exports=AutosizeInput}]); //# sourceMappingURL=react-bootstrap-typeahead.min.js.map
lib/components/notifications.js
spncrgr/hyper
import React from 'react'; import Component from '../component'; import {decorate} from '../utils/plugins'; import Notification_ from './notification'; const Notification = decorate(Notification_); export default class Notifications extends Component { template(css) { return (<div className={css('view')}> { this.props.customChildrenBefore } { this.props.fontShowing && <Notification key="font" backgroundColor="rgba(255, 255, 255, .2)" text={`${this.props.fontSize}px`} userDismissable={false} onDismiss={this.props.onDismissFont} dismissAfter={1000} /> } { this.props.resizeShowing && <Notification key="resize" backgroundColor="rgba(255, 255, 255, .2)" text={`${this.props.cols}x${this.props.rows}`} userDismissable={false} onDismiss={this.props.onDismissResize} dismissAfter={1000} /> } { this.props.messageShowing && <Notification key="message" backgroundColor="#FE354E" text={this.props.messageText} onDismiss={this.props.onDismissMessage} userDismissable={this.props.messageDismissable} userDismissColor="#AA2D3C" >{ this.props.messageURL ? [ this.props.messageText, ' (', <a key="link" style={{color: '#fff'}} onClick={ev => { window.require('electron').shell.openExternal(ev.target.href); ev.preventDefault(); }} href={this.props.messageURL} >more</a>, ')' ] : null } </Notification> } { this.props.updateShowing && <Notification key="update" backgroundColor="#7ED321" text={`Version ${this.props.updateVersion} ready`} onDismiss={this.props.onDismissUpdate} userDismissable > Version <b>{this.props.updateVersion}</b> ready. {this.props.updateNote && ` ${this.props.updateNote.trim().replace(/\.$/, '')}`} {' '} (<a style={{color: '#fff'}} onClick={ev => { window.require('electron').shell.openExternal(ev.target.href); ev.preventDefault(); }} href={`https://github.com/zeit/hyper/releases/tag/${this.props.updateVersion}`} >notes</a>). {' '} <a style={{ cursor: 'pointer', textDecoration: 'underline', fontWeight: 'bold' }} onClick={this.props.onUpdateInstall} > Restart </a>. { ' ' } </Notification> } { this.props.customChildren } </div>); } styles() { return { view: { position: 'fixed', bottom: '20px', right: '20px' } }; } }
src/core/display/App/Navigation/Horizontal/CategoryNavigation.js
JulienPradet/pigment-store
import React from 'react' import {Match, Miss, Link} from 'react-router' import {Container, Item} from '../../util/View/HorizontalList' import ComponentNavigation from './ComponentNavigation' import ChildrenLinks from './ChildrenLinks' const extractCategoryChildren = (prefix, category) => [ ...category.categories.map((category) => ({ pattern: `${prefix}/category-${category.name}`, name: category.name, render: ({pathname}) => <CategoryNavigation prefix={pathname} parentPathname={prefix} category={category} /> })), ...category.components.map((component) => ({ pattern: `${prefix}/component-${component.name}`, name: component.name, render: ({pathname}) => <ComponentNavigation prefix={pathname} parentPathname={prefix} component={component} /> })) ] const CategoryNavigation = ({category, prefix, parentPathname}) => ( <Container> <Item> <Link to={parentPathname}>{category.name}</Link> </Item> {extractCategoryChildren(prefix, category).map(({pattern, render}) => ( <Match key={pattern} pattern={pattern} render={(...args) => <Item>{render(...args)}</Item>} /> ))} <Miss render={() => ( <Item> <ChildrenLinks children={extractCategoryChildren(prefix, category)} /> </Item> )} /> </Container> ) export default CategoryNavigation
src/components/MainPage/FormTable/TradingInfo/TradingInfo.js
coolshare/ReactReduxStarterKit
import React from 'react' import ReactDataGrid from 'react-data-grid'; import {connect} from 'react-redux' import { Editors, Formatters } from 'react-data-grid-addons'; import cs from '../../../../services/CommunicationService' import $ from "jquery"; class _TradingInfo extends React.Component{ constructor(props) { super(props); this.state = { data:[] } this._columns = [ { key: 'name', name: 'Name', resizable: true }, { key: 'price', name: 'Price', resizable: true }, { key: 'symbol', name: 'Symbol', resizable: true}, { key: 'type', name: 'Type', resizable: true}, { key: 'utctime', name: 'UTC Time', resizable: true}, { key: 'volume', name: 'Volume', resizable: true}]; this.rowGetter = this.rowGetter.bind(this); cs.registerGlobal("tradingJSONPCallback", function(data){ cs.dispatch({"type":"LoadTrading", "data":data.list.resources}); }); } rowGetter(i) { let d = this.props.data[i]; let a = d.resource.fields; return {"name":a.name, "price":a.price, "symbol":a.symbol, "type":a.type, "utctime":a.utctime, "volume":a.volume} } componentWillMount () { $.ajax({ url: 'https://verdant.tchmachines.com/~coolsha/markqian/AngularJS/Directives/RoutedTab/data/Trade_JSONP.json', dataType: "jsonp", crossDomain: true, jsonpCallback:'aaa',//<<< success: function() { console.log("success"); }, error: function() { console.log("error"); } }); } /** * render * @return {ReactElement} markup */ render(){ return ( <div id="todoList" style={{backgroundColor:'#b0e0e6', minHeight:'500px', marginTop:'-10px', marginLeft:'-20px'}}> <h4>Trading Info (JSONP)</h4> <div style={{minHeight:'250px'}}> <ReactDataGrid columns={this._columns} rowGetter={this.rowGetter} rowsCount={this.props.data.length} minHeight={500} emptyRowsView={EmptyRowsView} /> </div> </div> ) } } import createReactClass from 'create-react-class' const EmptyRowsView = createReactClass({ render() { return (<div>[Trade list is empty]</div>); } }); const TradingInfo = connect( store => { return { data: store.TradingReducer.data }; } )(_TradingInfo); export default TradingInfo
ajax/libs/react-dom/16.0.0-alpha.10/umd/react-dom.production.min.js
joeyparrish/cdnjs
/** * react-dom.production.min.js v16.0.0-alpha.10 */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):e.ReactDOM=t(e.React)}(this,function(e){"use strict";function t(e){for(var t=arguments.length-1,n="Minified React error #"+e+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);n+=" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";var o=new Error(n);throw o.name="Invariant Violation",o.framesToPop=1,o}function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(e,t,n,r,o,a,i,l){if(Hn(t),!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var s=[n,r,o,a,i,l],c=0;u=new Error(t.replace(/%s/g,function(){return s[c++]})),u.name="Invariant Violation"}throw u.framesToPop=1,u}}function o(){if(Wn)for(var e in Vn){var t=Vn[e],n=Wn.indexOf(e);if(n>-1||Fn("96",e),!Bn.plugins[n]){t.extractEvents||Fn("97",e),Bn.plugins[n]=t;var r=t.eventTypes;for(var o in r)a(r[o],t,o)||Fn("98",o,e)}}}function a(e,t,n){Bn.eventNameDispatchConfigs.hasOwnProperty(n)&&Fn("99",n),Bn.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var a=r[o];i(a,t,n)}return!0}return!!e.registrationName&&(i(e.registrationName,t,n),!0)}function i(e,t,n){Bn.registrationNameModules[e]&&Fn("100",e),Bn.registrationNameModules[e]=t,Bn.registrationNameDependencies[e]=t.eventTypes[n].dependencies}function l(e){return function(){return e}}function u(e){return"topMouseUp"===e||"topTouchEnd"===e||"topTouchCancel"===e}function s(e){return"topMouseMove"===e||"topTouchMove"===e}function c(e){return"topMouseDown"===e||"topTouchStart"===e}function d(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=er.getNodeFromInstance(r),$n.invokeGuardedCallbackAndCatchFirstError(o,n,void 0,e),e.currentTarget=null}function p(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)d(e,t,n[o],r[o]);else n&&d(e,t,n,r);e._dispatchListeners=null,e._dispatchInstances=null}function f(e){var t=e._dispatchListeners,n=e._dispatchInstances;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function m(e){var t=f(e);return e._dispatchInstances=null,e._dispatchListeners=null,t}function h(e){var t=e._dispatchListeners,n=e._dispatchInstances;Array.isArray(t)&&Fn("103"),e.currentTarget=t?er.getNodeFromInstance(n):null;var r=t?t(e):null;return e.currentTarget=null,e._dispatchListeners=null,e._dispatchInstances=null,r}function g(e){return!!e._dispatchListeners}function v(e,t){return null==t&&Fn("30"),null==e?t:Array.isArray(e)?Array.isArray(t)?(e.push.apply(e,t),e):(e.push(t),e):Array.isArray(t)?[e].concat(t):[e,t]}function y(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}function b(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}function C(e,t,n){switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":return!(!n.disabled||!b(t));default:return!1}}function k(e){sr.enqueueEvents(e),sr.processEventQueue(!1)}function P(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}function E(e){if(gr[e])return gr[e];if(!hr[e])return e;var t=hr[e];for(var n in t)if(t.hasOwnProperty(n)&&n in vr)return gr[e]=t[n];return""}function T(e,t){if(!mr.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var o=document.createElement("div");o.setAttribute(n,"return;"),r="function"==typeof o[n]}return!r&&yr&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}function w(e){return Object.prototype.hasOwnProperty.call(e,Tr)||(e[Tr]=Pr++,kr[e[Tr]]={}),kr[e[Tr]]}function x(e){var t=tr.getInstanceFromNode(e);if(t){if("number"==typeof t.tag){jn(Nr&&"function"==typeof Nr.restoreControlledState,"Fiber needs to be injected to handle a fiber target for controlled events.");var n=tr.getFiberCurrentPropsFromNode(t.stateNode);return void Nr.restoreControlledState(t.stateNode,t.type,n)}jn("function"==typeof t.restoreControlledState,"The internal instance must be a React host component."),t.restoreControlledState()}}function N(e,t){return(e&t)===t}function S(e,t){return e.nodeType===zr&&e.getAttribute(Yr)===""+t||e.nodeType===Kr&&e.nodeValue===" react-text: "+t+" "||e.nodeType===Kr&&e.nodeValue===" react-empty: "+t+" "}function _(e){for(var t;t=e._renderedComponent;)e=t;return e}function O(e,t){var n=_(e);n._hostNode=t,t[$r]=n}function R(e,t){t[$r]=e}function A(e){var t=e._hostNode;t&&(delete t[$r],e._hostNode=null)}function M(e,t){if(!(e._flags&qr.hasCachedChildNodes)){var n=e._renderedChildren,r=t.firstChild;e:for(var o in n)if(n.hasOwnProperty(o)){var a=n[o],i=_(a)._domID;if(0!==i){for(;null!==r;r=r.nextSibling)if(S(r,i)){O(a,r);continue e}Fn("32",i)}}e._flags|=qr.hasCachedChildNodes}}function F(e){if(e[$r])return e[$r];for(var t=[];!e[$r];){if(t.push(e),!e.parentNode)return null;e=e.parentNode}var n,r=e[$r];if(r.tag===Vr||r.tag===Br)return r;for(;e&&(r=e[$r]);e=t.pop())n=r,t.length&&M(r,e);return n}function D(e){var t=e[$r];return t?t.tag===Vr||t.tag===Br?t:t._hostNode===e?t:null:(t=F(e),null!=t&&t._hostNode===e?t:null)}function I(e){if(e.tag===Vr||e.tag===Br)return e.stateNode;if(void 0===e._hostNode&&Fn("33"),e._hostNode)return e._hostNode;for(var t=[];!e._hostNode;)t.push(e),e._hostParent||Fn("34"),e=e._hostParent;for(;t.length;e=t.pop())M(e,e._hostNode);return e._hostNode}function U(e){return e[Xr]||null}function L(e,t){e[Xr]=t}function H(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}function j(e,t,n){return null==t||"boolean"==typeof t||""===t?"":"number"!=typeof t||0===t||uo.hasOwnProperty(e)&&uo[e]?(""+t).trim():t+"px"}function W(e){if("function"==typeof e.getName){return e.getName()}if("number"==typeof e.tag){var t=e,n=t.type;if("string"==typeof n)return n;if("function"==typeof n)return n.displayName||n.name}return null}function V(e){return e.replace(po,"-$1").toLowerCase()}function B(e){return fo(e).replace(mo,"-ms-")}function z(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}function K(e){var t=""+e,n=wo.exec(t);if(!n)return t;var r,o="",a=0,i=0;for(a=n.index;a<t.length;a++){switch(t.charCodeAt(a)){case 34:r="&quot;";break;case 38:r="&amp;";break;case 39:r="&#x27;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}i!==a&&(o+=t.substring(i,a)),i=a+1,o+=r}return i!==a?o+t.substring(i,a):o}function Y(e){return"boolean"==typeof e||"number"==typeof e?""+e:K(e)}function q(e){return'"'+xo(e)+'"'}function Q(e){return!!Oo.hasOwnProperty(e)||!_o.hasOwnProperty(e)&&(So.test(e)?(Oo[e]=!0,!0):(_o[e]=!0,!1))}function $(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&t<1||e.hasOverloadedBooleanValue&&!1===t}function X(e){return"checkbox"===e.type||"radio"===e.type?null!=e.checked:null!=e.value}function G(e,t){var n=t.name;if("radio"===t.type&&null!=n){for(var r=e;r.parentNode;)r=r.parentNode;for(var o=r.querySelectorAll("input[name="+JSON.stringify(""+n)+'][type="radio"]'),a=0;a<o.length;a++){var i=o[a];if(i!==e&&i.form===e.form){var l=Zr.getFiberCurrentPropsFromNode(i);l||Fn("90"),Fo.updateWrapper(i,l)}}}}function Z(t){var n="";return e.Children.forEach(t,function(e){null!=e&&("string"!=typeof e&&"number"!=typeof e||(n+=e))}),n}function J(e,t,n){var r=e.options;if(t){for(var o=n,a={},i=0;i<o.length;i++)a[""+o[i]]=!0;for(var l=0;l<r.length;l++){var u=a.hasOwnProperty(r[l].value);r[l].selected!==u&&(r[l].selected=u)}}else{for(var s=""+n,c=0;c<r.length;c++)if(r[c].value===s)return void(r[c].selected=!0);r.length&&(r[0].selected=!0)}}function ee(e){var t=e.type,n=e.nodeName;return n&&"input"===n.toLowerCase()&&("checkbox"===t||"radio"===t)}function te(e){return"number"==typeof e.tag&&(e=e.stateNode),e._wrapperState.valueTracker}function ne(e,t){e._wrapperState.valueTracker=t}function re(e){delete e._wrapperState.valueTracker}function oe(e){var t;return e&&(t=ee(e)?""+e.checked:e.value),t}function ae(e,t){var n=ee(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),o=""+e[n];if(!e.hasOwnProperty(n)&&"function"==typeof r.get&&"function"==typeof r.set){Object.defineProperty(e,n,{enumerable:r.enumerable,configurable:!0,get:function(){return r.get.call(this)},set:function(e){o=""+e,r.set.call(this,e)}});return{getValue:function(){return o},setValue:function(e){o=""+e},stopTracking:function(){re(t),delete e[n]}}}}function ie(){return""}function le(e,t){t&&(pa[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML)&&Fn("137",e,ie()),null!=t.dangerouslySetInnerHTML&&(null!=t.children&&Fn("60"),"object"==typeof t.dangerouslySetInnerHTML&&ia in t.dangerouslySetInnerHTML||Fn("61")),null!=t.style&&"object"!=typeof t.style&&Fn("62",ie()))}function ue(e,t){var n=e.nodeType===Jo,r=n?e:e.ownerDocument;ea(t,r)}function se(e){e.onclick=Zn}function ce(e,t){switch(t){case"iframe":case"object":xr.trapBubbledEvent("topLoad","load",e);break;case"video":case"audio":for(var n in ca)ca.hasOwnProperty(n)&&xr.trapBubbledEvent(n,ca[n],e);break;case"source":xr.trapBubbledEvent("topError","error",e);break;case"img":case"image":xr.trapBubbledEvent("topError","error",e),xr.trapBubbledEvent("topLoad","load",e);break;case"form":xr.trapBubbledEvent("topReset","reset",e),xr.trapBubbledEvent("topSubmit","submit",e);break;case"input":case"select":case"textarea":xr.trapBubbledEvent("topInvalid","invalid",e);break;case"details":xr.trapBubbledEvent("topToggle","toggle",e)}}function de(e,t){return e.indexOf("-")>=0||null!=t.is}function pe(e,t,n,r){for(var o in n){var a=n[o];if(n.hasOwnProperty(o))if(o===aa)Po.setValueForStyles(e,a);else if(o===na){var i=a?a[ia]:void 0;null!=i&&Yo(e,i)}else o===oa?"string"==typeof a?$o(e,a):"number"==typeof a&&$o(e,""+a):o===ra||(ta.hasOwnProperty(o)?a&&ue(t,o):r?Ao.setValueForAttribute(e,o,a):(Ir.properties[o]||Ir.isCustomAttribute(o))&&null!=a&&Ao.setValueForProperty(e,o,a))}}function fe(e,t,n,r){for(var o=0;o<t.length;o+=2){var a=t[o],i=t[o+1];a===aa?Po.setValueForStyles(e,i):a===na?Yo(e,i):a===oa?$o(e,i):r?null!=i?Ao.setValueForAttribute(e,a,i):Ao.deleteValueForAttribute(e,a):(Ir.properties[a]||Ir.isCustomAttribute(a))&&(null!=i?Ao.setValueForProperty(e,a,i):Ao.deleteValueForProperty(e,a))}}function me(e){switch(e){case"svg":return ua;case"math":return sa;default:return la}}function he(e){if(void 0!==e._hostParent)return e._hostParent;if("number"==typeof e.tag){do{e=e.return}while(e&&e.tag!==Ma);if(e)return e}return null}function ge(e,t){for(var n=0,r=e;r;r=he(r))n++;for(var o=0,a=t;a;a=he(a))o++;for(;n-o>0;)e=he(e),n--;for(;o-n>0;)t=he(t),o--;for(var i=n;i--;){if(e===t||e===t.alternate)return e;e=he(e),t=he(t)}return null}function ve(e,t){for(;t;){if(e===t||e===t.alternate)return!0;t=he(t)}return!1}function ye(e){return he(e)}function be(e,t,n){for(var r=[];e;)r.push(e),e=he(e);var o;for(o=r.length;o-- >0;)t(r[o],"captured",n);for(o=0;o<r.length;o++)t(r[o],"bubbled",n)}function Ce(e,t,n,r,o){for(var a=e&&t?ge(e,t):null,i=[];e&&e!==a;)i.push(e),e=he(e);for(var l=[];t&&t!==a;)l.push(t),t=he(t);var u;for(u=0;u<i.length;u++)n(i[u],"bubbled",r);for(u=l.length;u-- >0;)n(l[u],"captured",o)}function ke(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return Da(e,r)}function Pe(e,t,n){var r=ke(e,n,t);r&&(n._dispatchListeners=nr(n._dispatchListeners,r),n._dispatchInstances=nr(n._dispatchInstances,e))}function Ee(e){e&&e.dispatchConfig.phasedRegistrationNames&&Fa.traverseTwoPhase(e._targetInst,Pe,e)}function Te(e){if(e&&e.dispatchConfig.phasedRegistrationNames){var t=e._targetInst,n=t?Fa.getParentInstance(t):null;Fa.traverseTwoPhase(n,Pe,e)}}function we(e,t,n){if(e&&n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=Da(e,r);o&&(n._dispatchListeners=nr(n._dispatchListeners,o),n._dispatchInstances=nr(n._dispatchInstances,e))}}function xe(e){e&&e.dispatchConfig.registrationName&&we(e._targetInst,null,e)}function Ne(e){rr(e,Ee)}function Se(e){rr(e,Te)}function _e(e,t,n,r){Fa.traverseEnterLeave(n,r,we,e,t)}function Oe(e){rr(e,xe)}function Re(){return!qa&&mr.canUseDOM&&(qa="textContent"in document.documentElement?"textContent":"innerText"),qa}function Ae(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}function Me(e,t,n,r){this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var a in o)if(o.hasOwnProperty(a)){var i=o[a];i?this[a]=i(n):"target"===a?this.target=r:this[a]=n[a]}var l=null!=n.defaultPrevented?n.defaultPrevented:!1===n.returnValue;return this.isDefaultPrevented=l?Zn.thatReturnsTrue:Zn.thatReturnsFalse,this.isPropagationStopped=Zn.thatReturnsFalse,this}function Fe(e,t,n,r){return Za.call(this,e,t,n,r)}function De(e,t,n,r){return Za.call(this,e,t,n,r)}function Ie(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function Ue(e){switch(e){case"topCompositionStart":return di.compositionStart;case"topCompositionEnd":return di.compositionEnd;case"topCompositionUpdate":return di.compositionUpdate}}function Le(e,t){return"topKeyDown"===e&&t.keyCode===oi}function He(e,t){switch(e){case"topKeyUp":return-1!==ri.indexOf(t.keyCode);case"topKeyDown":return t.keyCode!==oi;case"topKeyPress":case"topMouseDown":case"topBlur":return!0;default:return!1}}function je(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function We(e,t,n,r){var o,a;if(ai?o=Ue(e):fi?He(e,n)&&(o=di.compositionEnd):Le(e,n)&&(o=di.compositionStart),!o)return null;ui&&(fi||o!==di.compositionStart?o===di.compositionEnd&&fi&&(a=fi.getData()):fi=$a.getPooled(r));var i=ei.getPooled(o,t,n,r);if(a)i.data=a;else{var l=je(n);null!==l&&(i.data=l)}return Ua.accumulateTwoPhaseDispatches(i),i}function Ve(e,t){switch(e){case"topCompositionEnd":return je(t);case"topKeyPress":return t.which!==si?null:(pi=!0,ci);case"topTextInput":var n=t.data;return n===ci&&pi?null:n;default:return null}}function Be(e,t){if(fi){if("topCompositionEnd"===e||!ai&&He(e,t)){var n=fi.getData();return $a.release(fi),fi=null,n}return null}switch(e){case"topPaste":return null;case"topKeyPress":return t.which&&!Ie(t)?String.fromCharCode(t.which):null;case"topCompositionEnd":return ui?null:t.data;default:return null}}function ze(e,t,n,r){var o;if(!(o=li?Ve(e,n):Be(e,n)))return null;var a=ni.getPooled(di.beforeInput,t,n,r);return a.data=o,Ua.accumulateTwoPhaseDispatches(a),a}function Ke(e,t){return vi(e,t)}function Ye(e,t){return gi(Ke,e,t)}function qe(e,t){if(yi)return Ye(e,t);yi=!0;try{return Ye(e,t)}finally{yi=!1,Ar.restoreStateIfNeeded()}}function Qe(e){var t=e.target||e.srcElement||window;return t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===Pi?t.parentNode:t}function $e(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!Ti[e.type]:"textarea"===t}function Xe(e,t,n){var r=Za.getPooled(xi.change,e,t,n);return r.type="change",Ar.enqueueStateRestore(n),Ua.accumulateTwoPhaseDispatches(r),r}function Ge(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function Ze(e){var t=Xe(Si,e,Ei(e));ki.batchedUpdates(Je,t)}function Je(e){sr.enqueueEvents(e),sr.processEventQueue(!1)}function et(e){if(Go.updateValueIfChanged(e))return e}function tt(e,t){if("topChange"===e)return t}function nt(e,t){Ni=e,Si=t,Ni.attachEvent("onpropertychange",ot)}function rt(){Ni&&(Ni.detachEvent("onpropertychange",ot),Ni=null,Si=null)}function ot(e){"value"===e.propertyName&&et(Si)&&Ze(e)}function at(e,t,n){"topFocus"===e?(rt(),nt(t,n)):"topBlur"===e&&rt()}function it(e,t){if("topSelectionChange"===e||"topKeyUp"===e||"topKeyDown"===e)return et(Si)}function lt(e){var t=e.nodeName;return t&&"input"===t.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function ut(e,t){if("topClick"===e)return et(t)}function st(e,t){if("topInput"===e||"topChange"===e)return et(t)}function ct(e,t){if(null!=e){var n=e._wrapperState||t._wrapperState;if(n&&n.controlled&&"number"===t.type){var r=""+t.value;t.getAttribute("value")!==r&&t.setAttribute("value",r)}}}function dt(e,t,n,r){return Za.call(this,e,t,n,r)}function pt(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=Ii[e];return!!r&&!!n[r]}function ft(e){return pt}function mt(e,t,n,r){return Di.call(this,e,t,n,r)}function ht(e){return e.Window&&e instanceof e.Window?{x:e.pageXOffset||e.document.documentElement.scrollLeft,y:e.pageYOffset||e.document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}function gt(e){if("number"==typeof e.tag){for(;e.return;)e=e.return;return e.tag!==Ji?null:e.stateNode.containerInfo}for(;e._hostParent;)e=e._hostParent;return Zr.getNodeFromInstance(e).parentNode}function vt(e,t,n){this.topLevelType=e,this.nativeEvent=t,this.targetInst=n,this.ancestors=[]}function yt(e){var t=e.targetInst,n=t;do{if(!n){e.ancestors.push(n);break}var r=gt(n);if(!r)break;e.ancestors.push(n),n=Zr.getClosestInstanceFromNode(r)}while(n);for(var o=0;o<e.ancestors.length;o++)t=e.ancestors[o],el._handleTopLevel(e.topLevelType,t,e.nativeEvent,Ei(e.nativeEvent))}function bt(e){e(Zi(window))}function Ct(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function kt(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function Pt(e,t){for(var n=Ct(e),r=0,o=0;n;){if(n.nodeType===il){if(o=r+n.textContent.length,r<=t&&o>=t)return{node:n,offset:t-r};r=o}n=Ct(kt(n))}}function Et(e,t,n,r){return e===n&&t===r}function Tt(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,r=t.anchorOffset,o=t.focusNode,a=t.focusOffset,i=t.getRangeAt(0);try{i.startContainer.nodeType,i.endContainer.nodeType}catch(e){return null}var l=Et(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),u=l?0:i.toString().length,s=i.cloneRange();s.selectNodeContents(e),s.setEnd(i.startContainer,i.startOffset);var c=Et(s.startContainer,s.startOffset,s.endContainer,s.endOffset),d=c?0:s.toString().length,p=d+u,f=document.createRange();f.setStart(n,r),f.setEnd(o,a);var m=f.collapsed;return{start:m?p:d,end:m?d:p}}function wt(e,t){if(window.getSelection){var n=window.getSelection(),r=e[Qa()].length,o=Math.min(t.start,r),a=void 0===t.end?o:Math.min(t.end,r);if(!n.extend&&o>a){var i=a;a=o,o=i}var l=ll(e,o),u=ll(e,a);if(l&&u){var s=document.createRange();s.setStart(l.node,l.offset),n.removeAllRanges(),o>a?(n.addRange(s),n.extend(u.node,u.offset)):(s.setEnd(u.node,u.offset),n.addRange(s))}}}function xt(e){var t=e?e.ownerDocument||e:document,n=t.defaultView||window;return!(!e||!("function"==typeof n.Node?e instanceof n.Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}function Nt(e){return cl(e)&&3==e.nodeType}function St(e,t){return!(!e||!t)&&(e===t||!dl(e)&&(dl(t)?St(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}function _t(e){try{e.focus()}catch(e){}}function Ot(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function Rt(e){return pl(document.documentElement,e)}function At(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!==e&&t!==t}function Mt(e,t){if(At(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var o=0;o<n.length;o++)if(!yl.call(t,n[o])||!At(e[n[o]],t[n[o]]))return!1;return!0}function Ft(e){if("selectionStart"in e&&vl.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}}function Dt(e,t){if(xl||null==El||El!==ml())return null;var n=Ft(El);if(!wl||!bl(wl,n)){wl=n;var r=Za.getPooled(Pl.select,Tl,e,t);return r.type="select",r.target=El,Ua.accumulateTwoPhaseDispatches(r),r}return null}function It(e,t,n,r){return Za.call(this,e,t,n,r)}function Ut(e,t,n,r){return Za.call(this,e,t,n,r)}function Lt(e,t,n,r){return Di.call(this,e,t,n,r)}function Ht(e){var t,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,t>=32||13===t?t:0}function jt(e){if(e.key){var t=Ul[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=Il(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?Ll[e.keyCode]||"Unidentified":""}function Wt(e,t,n,r){return Di.call(this,e,t,n,r)}function Vt(e,t,n,r){return Hi.call(this,e,t,n,r)}function Bt(e,t,n,r){return Di.call(this,e,t,n,r)}function zt(e,t,n,r){return Za.call(this,e,t,n,r)}function Kt(e,t,n,r){return Hi.call(this,e,t,n,r)}function Yt(){nu||(nu=!0,xr.injection.injectReactEventListener(tl),sr.injection.injectEventPluginOrder(Mi),tr.injection.injectComponentTree(Zr),sr.injection.injectEventPluginsByName({SimpleEventPlugin:tu,EnterLeaveEventPlugin:Vi,ChangeEventPlugin:Ri,SelectEventPlugin:_l,BeforeInputEventPlugin:hi}),Ir.injection.injectDOMPropertyConfig(Aa),Ir.injection.injectDOMPropertyConfig($i),Ir.injection.injectDOMPropertyConfig(al))}function qt(e,t){return e!==su&&e!==uu||t!==su&&t!==uu?e===lu&&t!==lu?-255:e!==lu&&t===lu?255:e-t:0}function Qt(e){if(null!==e.updateQueue)return e.updateQueue;var t=void 0;return t={first:null,last:null,hasForceUpdate:!1,callbackList:null},e.updateQueue=t,t}function $t(e,t){var n=e.updateQueue;if(null===n)return t.updateQueue=null,null;var r=null!==t.updateQueue?t.updateQueue:{};return r.first=n.first,r.last=n.last,r.hasForceUpdate=!1,r.callbackList=null,r.isProcessing=!1,t.updateQueue=r,r}function Xt(e){return{priorityLevel:e.priorityLevel,partialState:e.partialState,callback:e.callback,isReplace:e.isReplace,isForced:e.isForced,isTopLevelUnmount:e.isTopLevelUnmount,next:null}}function Gt(e,t,n,r){null!==n?n.next=t:(t.next=e.first,e.first=t),null!==r?t.next=r:e.last=t}function Zt(e,t){var n=t.priorityLevel,r=null,o=null;if(null!==e.last&&qt(e.last.priorityLevel,n)<=0)r=e.last;else for(o=e.first;null!==o&&qt(o.priorityLevel,n)<=0;)r=o,o=o.next;return r}function Jt(e,t){var n=Qt(e),r=null!==e.alternate?Qt(e.alternate):null,o=Zt(n,t),a=null!==o?o.next:n.first;if(null===r)return Gt(n,t,o,a),null;var i=Zt(r,t),l=null!==i?i.next:r.first;if(Gt(n,t,o,a),a!==l){var u=Xt(t);return Gt(r,u,i,l),u}return null===i&&(r.first=t),null===l&&(r.last=null),null}function en(e,t,n,r){Jt(e,{priorityLevel:r,partialState:t,callback:n,isReplace:!1,isForced:!1,isTopLevelUnmount:!1,next:null})}function tn(e,t,n,r){Jt(e,{priorityLevel:r,partialState:t,callback:n,isReplace:!0,isForced:!1,isTopLevelUnmount:!1,next:null})}function nn(e,t,n){Jt(e,{priorityLevel:n,partialState:null,callback:t,isReplace:!1,isForced:!0,isTopLevelUnmount:!1,next:null})}function rn(e){return null!==e.first?e.first.priorityLevel:lu}function on(e,t,n,r){var o=null===t.element,a={priorityLevel:r,partialState:t,callback:n,isReplace:!1,isForced:!1,isTopLevelUnmount:o,next:null},i=Jt(e,a);if(o){var l=e.updateQueue,u=null!==e.alternate?e.alternate.updateQueue:null;null!==l&&null!==a.next&&(a.next=null,l.last=a),null!==u&&null!==i&&null!==i.next&&(i.next=null,u.last=a)}}function an(e,t,n,r){var o=e.partialState;if("function"==typeof o){return o.call(t,n,r)}return o}function ln(e,t,n,r,o,a){t.hasForceUpdate=!1;for(var i=r,l=!0,u=null,s=t.first;null!==s&&qt(s.priorityLevel,a)<=0;){t.first=s.next,null===t.first&&(t.last=null);var c=void 0;s.isReplace?(i=an(s,n,i,o),l=!0):(c=an(s,n,i,o))&&(i=l?Ln({},i,c):Ln(i,c),l=!1),s.isForced&&(t.hasForceUpdate=!0),null===s.callback||s.isTopLevelUnmount&&null!==s.next||(u=u||[],u.push(s.callback),e.effectTag|=iu),s=s.next}return t.callbackList=u,null!==t.first||null!==u||t.hasForceUpdate||(e.updateQueue=null),i}function un(e,t,n){var r=t.callbackList;if(null!==r)for(var o=0;o<r.length;o++){var a=r[o];jn("function"==typeof a,"Invalid argument passed as callback. Expected a function. Instead received: %s",a),a.call(n)}}function sn(e){var t=e;if(e.alternate)for(;t.return;)t=t.return;else{if((t.effectTag&Ou)!==_u)return Ru;for(;t.return;)if(t=t.return,(t.effectTag&Ou)!==_u)return Ru}return t.tag===xu?Au:Mu}function cn(e){jn(sn(e)===Au,"Unable to find node on an unmounted component.")}function dn(e){var t=e.alternate;if(!t){var n=sn(e);return jn(n!==Mu,"Unable to find node on an unmounted component."),n===Ru?null:e}for(var r=e,o=t;;){var a=r.return,i=a?a.alternate:null;if(!a||!i)break;if(a.child===i.child){for(var l=a.child;l;){if(l===r)return cn(a),e;if(l===o)return cn(a),t;l=l.sibling}jn(!1,"Unable to find node on an unmounted component.")}if(r.return!==o.return)r=a,o=i;else{for(var u=!1,s=a.child;s;){if(s===r){u=!0,r=a,o=i;break}if(s===o){u=!0,o=a,r=i;break}s=s.sibling}if(!u){for(s=i.child;s;){if(s===r){u=!0,r=i,o=a;break}if(s===o){u=!0,o=i,r=a;break}s=s.sibling}jn(u,"Child was not found in either parent set. This indicates a bug related to the return pointer.")}}jn(r.alternate===o,"Return fibers should always be each others' alternates.")}return jn(r.tag===xu,"Unable to find node on an unmounted component."),r.stateNode.current===r?e:t}function pn(e){return hn(e)?ns:es.current}function fn(e,t,n){var r=e.stateNode;r.__reactInternalMemoizedUnmaskedChildContext=t,r.__reactInternalMemoizedMaskedChildContext=n}function mn(e){return e.tag===$u&&null!=e.type.contextTypes}function hn(e){return e.tag===$u&&null!=e.type.childContextTypes}function gn(e){hn(e)&&(Zu(ts,e),Zu(es,e))}function vn(e,t,n){var r=e.stateNode,o=e.type.childContextTypes;if("function"!=typeof r.getChildContext)return t;var a=void 0;a=r.getChildContext();for(var i in a)i in o||Fn("108",co(e)||"Unknown",i);return qu({},t,a)}function yn(e){return!(!e.prototype||!e.prototype.isReactComponent)}function bn(e,t,n,r){eo.enableAsyncSubtreeAPI&&null!=e&&!0===e.unstable_asyncUpdates&&(n|=_s);var o=void 0;if("function"==typeof e)o=yn(e)?As(bs,t,n):As(ys,t,n),o.type=e;else if("string"==typeof e)o=As(ks,t,n),o.type=e;else if("object"==typeof e&&null!==e&&"number"==typeof e.tag)o=e;else{Fn("130",null==e?e:typeof e,"")}return o}function Cn(e,t,n){return"\n in "+(e||"Unknown")+(t?" (at "+t.fileName.replace(/^.*[\\\/]/,"")+":"+t.lineNumber+")":n?" (created by "+n+")":"")}function kn(e){switch(e.tag){case Ys:case qs:case Qs:case $s:var t=e._debugOwner,n=e._debugSource,r=co(e),o=null;return t&&(o=co(t)),Cn(r,n,o);default:return""}}function Pn(e){var t="",n=e;do{t+=kn(n),n=n.return}while(n);return t}function En(e){if(!1!==Zs(e)){var t=e.error;console.error("React caught an error thrown by one of your components.\n\n"+t.stack)}}function Tn(e){var t=e&&(gc&&e[gc]||e[vc]);if("function"==typeof t)return t}function wn(e,t){var n=t.ref;if(null!==n&&"function"!=typeof n&&t._owner){var r=t._owner,o=void 0;if(r)if("number"==typeof r.tag){var a=r;a.tag!==Rc&&Fn("110"),o=a.stateNode}else o=r.getPublicInstance();jn(o,"Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.",n);var i=""+n;if(null!==e&&null!==e.ref&&e.ref._stringRef===i)return e.ref;var l=function(e){var t=o.refs===Cu?o.refs={}:o.refs;null===e?delete t[i]:t[i]=e};return l._stringRef=i,l}return n}function xn(e,t){if("textarea"!==e.type){Fn("31","[object Object]"===Object.prototype.toString.call(t)?"object with keys {"+Object.keys(t).join(", ")+"}":t,"")}}function Nn(e,t){function n(n,r){if(t){if(!e){if(null===r.alternate)return;r=r.alternate}var o=n.progressedLastDeletion;null!==o?(o.nextEffect=r,n.progressedLastDeletion=r):n.progressedFirstDeletion=n.progressedLastDeletion=r,r.nextEffect=null,r.effectTag=Hc}}function r(e,r){if(!t)return null;for(var o=r;null!==o;)n(e,o),o=o.sibling;return null}function o(e,t){for(var n=new Map,r=t;null!==r;)null!==r.key?n.set(r.key,r):n.set(r.index,r),r=r.sibling;return n}function a(t,n){if(e){var r=Pc(t,n);return r.index=0,r.sibling=null,r}return t.pendingWorkPriority=n,t.effectTag=Uc,t.index=0,t.sibling=null,t}function i(e,n,r){if(e.index=r,!t)return n;var o=e.alternate;if(null!==o){var a=o.index;return a<n?(e.effectTag=Lc,n):a}return e.effectTag=Lc,n}function l(e){return t&&null===e.alternate&&(e.effectTag=Lc),e}function u(e,t,n,r){if(null===t||t.tag!==Ac){var o=wc(n,e.internalContextTag,r);return o.return=e,o}var i=a(t,r);return i.pendingProps=n,i.return=e,i}function s(e,t,n,r){if(null===t||t.type!==n.type){var o=Ec(n,e.internalContextTag,r);return o.ref=wn(t,n),o.return=e,o}var i=a(t,r);return i.ref=wn(t,n),i.pendingProps=n.props,i.return=e,i}function c(e,t,n,r){if(null===t||t.tag!==Fc){var o=xc(n,e.internalContextTag,r);return o.return=e,o}var i=a(t,r);return i.pendingProps=n,i.return=e,i}function d(e,t,n,r){if(null===t||t.tag!==Dc){var o=Nc(n,e.internalContextTag,r);return o.type=n.value,o.return=e,o}var i=a(t,r);return i.type=n.value,i.return=e,i}function p(e,t,n,r){if(null===t||t.tag!==Mc||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation){var o=Sc(n,e.internalContextTag,r);return o.return=e,o}var i=a(t,r);return i.pendingProps=n.children||[],i.return=e,i}function f(e,t,n,r){if(null===t||t.tag!==Ic){var o=Tc(n,e.internalContextTag,r);return o.return=e,o}var i=a(t,r);return i.pendingProps=n,i.return=e,i}function m(e,t,n){if("string"==typeof t||"number"==typeof t){var r=wc(""+t,e.internalContextTag,n);return r.return=e,r}if("object"==typeof t&&null!==t){switch(t.$$typeof){case rc:var o=Ec(t,e.internalContextTag,n);return o.ref=wn(null,t),o.return=e,o;case bc:var a=xc(t,e.internalContextTag,n);return a.return=e,a;case Cc:var i=Nc(t,e.internalContextTag,n);return i.type=t.value,i.return=e,i;case kc:var l=Sc(t,e.internalContextTag,n);return l.return=e,l}if(_c(t)||yc(t)){var u=Tc(t,e.internalContextTag,n);return u.return=e,u}xn(e,t)}return null}function h(e,t,n,r){var o=null!==t?t.key:null;if("string"==typeof n||"number"==typeof n)return null!==o?null:u(e,t,""+n,r);if("object"==typeof n&&null!==n){switch(n.$$typeof){case rc:return n.key===o?s(e,t,n,r):null;case bc:return n.key===o?c(e,t,n,r):null;case Cc:return null===o?d(e,t,n,r):null;case kc:return n.key===o?p(e,t,n,r):null}if(_c(n)||yc(n))return null!==o?null:f(e,t,n,r);xn(e,n)}return null}function g(e,t,n,r,o){if("string"==typeof r||"number"==typeof r){return u(t,e.get(n)||null,""+r,o)}if("object"==typeof r&&null!==r){switch(r.$$typeof){case rc:return s(t,e.get(null===r.key?n:r.key)||null,r,o);case bc:return c(t,e.get(null===r.key?n:r.key)||null,r,o);case Cc:return d(t,e.get(n)||null,r,o);case kc:return p(t,e.get(null===r.key?n:r.key)||null,r,o)}if(_c(r)||yc(r)){return f(t,e.get(n)||null,r,o)}xn(t,r)}return null}function v(e,a,l,u){for(var s=null,c=null,d=a,p=0,f=0,v=null;null!==d&&f<l.length;f++){d.index>f?(v=d,d=null):v=d.sibling;var y=h(e,d,l[f],u);if(null===y){null===d&&(d=v);break}t&&d&&null===y.alternate&&n(e,d),p=i(y,p,f),null===c?s=y:c.sibling=y,c=y,d=v}if(f===l.length)return r(e,d),s;if(null===d){for(;f<l.length;f++){var b=m(e,l[f],u);b&&(p=i(b,p,f),null===c?s=b:c.sibling=b,c=b)}return s}for(var C=o(e,d);f<l.length;f++){var k=g(C,e,f,l[f],u);k&&(t&&null!==k.alternate&&C.delete(null===k.key?f:k.key),p=i(k,p,f),null===c?s=k:c.sibling=k,c=k)}return t&&C.forEach(function(t){return n(e,t)}),s}function y(e,a,l,u){var s=yc(l);jn("function"==typeof s,"An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.");var c=s.call(l);jn(null!=c,"An iterable object provided no iterator.") ;for(var d=null,p=null,f=a,v=0,y=0,b=null,C=c.next();null!==f&&!C.done;y++,C=c.next()){f.index>y?(b=f,f=null):b=f.sibling;var k=h(e,f,C.value,u);if(null===k){f||(f=b);break}t&&f&&null===k.alternate&&n(e,f),v=i(k,v,y),null===p?d=k:p.sibling=k,p=k,f=b}if(C.done)return r(e,f),d;if(null===f){for(;!C.done;y++,C=c.next()){var P=m(e,C.value,u);null!==P&&(v=i(P,v,y),null===p?d=P:p.sibling=P,p=P)}return d}for(var E=o(e,f);!C.done;y++,C=c.next()){var T=g(E,e,y,C.value,u);null!==T&&(t&&null!==T.alternate&&E.delete(null===T.key?y:T.key),v=i(T,v,y),null===p?d=T:p.sibling=T,p=T)}return t&&E.forEach(function(t){return n(e,t)}),d}function b(e,t,n,o){if(null!==t&&t.tag===Ac){r(e,t.sibling);var i=a(t,o);return i.pendingProps=n,i.return=e,i}r(e,t);var l=wc(n,e.internalContextTag,o);return l.return=e,l}function C(e,t,o,i){for(var l=o.key,u=t;null!==u;){if(u.key===l){if(u.type===o.type){r(e,u.sibling);var s=a(u,i);return s.ref=wn(u,o),s.pendingProps=o.props,s.return=e,s}r(e,u);break}n(e,u),u=u.sibling}var c=Ec(o,e.internalContextTag,i);return c.ref=wn(t,o),c.return=e,c}function k(e,t,o,i){for(var l=o.key,u=t;null!==u;){if(u.key===l){if(u.tag===Fc){r(e,u.sibling);var s=a(u,i);return s.pendingProps=o,s.return=e,s}r(e,u);break}n(e,u),u=u.sibling}var c=xc(o,e.internalContextTag,i);return c.return=e,c}function P(e,t,n,o){var i=t;if(null!==i){if(i.tag===Dc){r(e,i.sibling);var l=a(i,o);return l.type=n.value,l.return=e,l}r(e,i)}var u=Nc(n,e.internalContextTag,o);return u.type=n.value,u.return=e,u}function E(e,t,o,i){for(var l=o.key,u=t;null!==u;){if(u.key===l){if(u.tag===Mc&&u.stateNode.containerInfo===o.containerInfo&&u.stateNode.implementation===o.implementation){r(e,u.sibling);var s=a(u,i);return s.pendingProps=o.children||[],s.return=e,s}r(e,u);break}n(e,u),u=u.sibling}var c=Sc(o,e.internalContextTag,i);return c.return=e,c}function T(e,t,n,o){var a=eo.disableNewFiberFeatures,i="object"==typeof n&&null!==n;if(i)if(a)switch(n.$$typeof){case rc:return l(C(e,t,n,o));case kc:return l(E(e,t,n,o))}else switch(n.$$typeof){case rc:return l(C(e,t,n,o));case bc:return l(k(e,t,n,o));case Cc:return l(P(e,t,n,o));case kc:return l(E(e,t,n,o))}if(a)switch(e.tag){case Rc:var u=e.type;null!==n&&!1!==n&&Fn("109",u.displayName||u.name||"Component");break;case Oc:var s=e.type;null!==n&&!1!==n&&Fn("105",s.displayName||s.name||"Component")}if("string"==typeof n||"number"==typeof n)return l(b(e,t,""+n,o));if(_c(n))return v(e,t,n,o);if(yc(n))return y(e,t,n,o);if(i&&xn(e,n),!a&&void 0===n)switch(e.tag){case Rc:case Oc:var c=e.type;jn(!1,"%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.",c.displayName||c.name||"Component")}return r(e,t)}return T}function Sn(e){if(!e)return Cu;var t=Pu.get(e);return"number"==typeof t.tag?af(t):t._processChildContext(t._context)}function _n(e){return!(!e||e.nodeType!==kf&&e.nodeType!==Pf&&e.nodeType!==Ef)}function On(e){if(!_n(e))throw new Error("Target container is not a DOM element.")}function Rn(e,t){switch(e){case"button":case"input":case"select":case"textarea":return!!t.autoFocus}return!1}function An(){Ff=!0}function Mn(e,t,n,r){On(n);var o=n.nodeType===Pf?n.documentElement:n,a=o._reactRootContainer;if(a)Mf.updateContainer(t,a,e,r);else{for(;o.lastChild;)o.removeChild(o.lastChild);var i=Mf.createContainer(o);a=o._reactRootContainer=i,Mf.unbatchedUpdates(function(){Mf.updateContainer(t,i,e,r)})}return Mf.getPublicRootInstance(a)}var Fn=t,Dn=Object.getOwnPropertySymbols,In=Object.prototype.hasOwnProperty,Un=Object.prototype.propertyIsEnumerable,Ln=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,o,a=n(e),i=1;i<arguments.length;i++){r=Object(arguments[i]);for(var l in r)In.call(r,l)&&(a[l]=r[l]);if(Dn){o=Dn(r);for(var u=0;u<o.length;u++)Un.call(r,o[u])&&(a[o[u]]=r[o[u]])}}return a},Hn=function(e){},jn=r,Wn=null,Vn={},Bn={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(e){Wn&&Fn("101"),Wn=Array.prototype.slice.call(e),o()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];Vn.hasOwnProperty(n)&&Vn[n]===r||(Vn[n]&&Fn("102",n),Vn[n]=r,t=!0)}t&&o()}},zn=Bn,Kn=null,Yn=function(e,t,n,r,o,a,i,l,u){var s=Array.prototype.slice.call(arguments,3);try{t.apply(n,s)}catch(e){return e}return null},qn=function(){if(Kn){var e=Kn;throw Kn=null,e}},Qn={injection:{injectErrorUtils:function(e){jn("function"==typeof e.invokeGuardedCallback,"Injected invokeGuardedCallback() must be a function."),Yn=e.invokeGuardedCallback}},invokeGuardedCallback:function(e,t,n,r,o,a,i,l,u){return Yn.apply(this,arguments)},invokeGuardedCallbackAndCatchFirstError:function(e,t,n,r,o,a,i,l,u){var s=Qn.invokeGuardedCallback.apply(this,arguments);null!==s&&null===Kn&&(Kn=s)},rethrowCaughtError:function(){return qn.apply(this,arguments)}},$n=Qn,Xn=function(){};Xn.thatReturns=l,Xn.thatReturnsFalse=l(!1),Xn.thatReturnsTrue=l(!0),Xn.thatReturnsNull=l(null),Xn.thatReturnsThis=function(){return this},Xn.thatReturnsArgument=function(e){return e};var Gn,Zn=Xn,Jn={injectComponentTree:function(e){Gn=e}},er={isEndish:u,isMoveish:s,isStartish:c,executeDirectDispatch:h,executeDispatchesInOrder:p,executeDispatchesInOrderStopAtTrue:m,hasDispatches:g,getFiberCurrentPropsFromNode:function(e){return Gn.getFiberCurrentPropsFromNode(e)},getInstanceFromNode:function(e){return Gn.getInstanceFromNode(e)},getNodeFromInstance:function(e){return Gn.getNodeFromInstance(e)},injection:Jn},tr=er,nr=v,rr=y,or=null,ar=function(e,t){e&&(tr.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},ir=function(e){return ar(e,!0)},lr=function(e){return ar(e,!1)},ur={injection:{injectEventPluginOrder:zn.injectEventPluginOrder,injectEventPluginsByName:zn.injectEventPluginsByName},getListener:function(e,t){var n;if("number"==typeof e.tag){var r=e.stateNode;if(!r)return null;var o=tr.getFiberCurrentPropsFromNode(r);if(!o)return null;if(n=o[t],C(t,e.type,o))return null}else{var a=e._currentElement;if("string"==typeof a||"number"==typeof a)return null;if(!e._rootNodeID)return null;var i=a.props;if(n=i[t],C(t,a.type,i))return null}return n&&"function"!=typeof n&&Fn("94",t,typeof n),n},extractEvents:function(e,t,n,r){for(var o,a=zn.plugins,i=0;i<a.length;i++){var l=a[i];if(l){var u=l.extractEvents(e,t,n,r);u&&(o=nr(o,u))}}return o},enqueueEvents:function(e){e&&(or=nr(or,e))},processEventQueue:function(e){var t=or;or=null,e?rr(t,ir):rr(t,lr),or&&Fn("95"),$n.rethrowCaughtError()}},sr=ur,cr={handleTopLevel:function(e,t,n,r){k(sr.extractEvents(e,t,n,r))}},dr=cr,pr=!("undefined"==typeof window||!window.document||!window.document.createElement),fr={canUseDOM:pr,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:pr&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:pr&&!!window.screen,isInWorker:!pr},mr=fr,hr={animationend:P("Animation","AnimationEnd"),animationiteration:P("Animation","AnimationIteration"),animationstart:P("Animation","AnimationStart"),transitionend:P("Transition","TransitionEnd")},gr={},vr={};mr.canUseDOM&&(vr=document.createElement("div").style,"AnimationEvent"in window||(delete hr.animationend.animation,delete hr.animationiteration.animation,delete hr.animationstart.animation),"TransitionEvent"in window||delete hr.transitionend.transition);var yr,br=E;mr.canUseDOM&&(yr=document.implementation&&document.implementation.hasFeature&&!0!==document.implementation.hasFeature("",""));var Cr=T,kr={},Pr=0,Er={topAbort:"abort",topAnimationEnd:br("animationend")||"animationend",topAnimationIteration:br("animationiteration")||"animationiteration",topAnimationStart:br("animationstart")||"animationstart",topBlur:"blur",topCancel:"cancel",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topChange:"change",topClick:"click",topClose:"close",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topScroll:"scroll",topSeeked:"seeked",topSeeking:"seeking",topSelectionChange:"selectionchange",topStalled:"stalled",topSuspend:"suspend",topTextInput:"textInput",topTimeUpdate:"timeupdate",topToggle:"toggle",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topTransitionEnd:br("transitionend")||"transitionend",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},Tr="_reactListenersID"+(""+Math.random()).slice(2),wr=Ln({},dr,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(wr.handleTopLevel),wr.ReactEventListener=e}},setEnabled:function(e){wr.ReactEventListener&&wr.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!wr.ReactEventListener||!wr.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,r=w(n),o=zn.registrationNameDependencies[e],a=0;a<o.length;a++){var i=o[a];r.hasOwnProperty(i)&&r[i]||("topWheel"===i?Cr("wheel")?wr.ReactEventListener.trapBubbledEvent("topWheel","wheel",n):Cr("mousewheel")?wr.ReactEventListener.trapBubbledEvent("topWheel","mousewheel",n):wr.ReactEventListener.trapBubbledEvent("topWheel","DOMMouseScroll",n):"topScroll"===i?wr.ReactEventListener.trapCapturedEvent("topScroll","scroll",n):"topFocus"===i||"topBlur"===i?(wr.ReactEventListener.trapCapturedEvent("topFocus","focus",n),wr.ReactEventListener.trapCapturedEvent("topBlur","blur",n),r.topBlur=!0,r.topFocus=!0):"topCancel"===i?(Cr("cancel",!0)&&wr.ReactEventListener.trapCapturedEvent("topCancel","cancel",n),r.topCancel=!0):"topClose"===i?(Cr("close",!0)&&wr.ReactEventListener.trapCapturedEvent("topClose","close",n),r.topClose=!0):Er.hasOwnProperty(i)&&wr.ReactEventListener.trapBubbledEvent(i,Er[i],n),r[i]=!0)}},isListeningToAllDependencies:function(e,t){for(var n=w(t),r=zn.registrationNameDependencies[e],o=0;o<r.length;o++){var a=r[o];if(!n.hasOwnProperty(a)||!n[a])return!1}return!0},trapBubbledEvent:function(e,t,n){return wr.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return wr.ReactEventListener.trapCapturedEvent(e,t,n)}}),xr=wr,Nr=null,Sr={injectFiberControlledHostComponent:function(e){Nr=e}},_r=null,Or=null,Rr={injection:Sr,enqueueStateRestore:function(e){_r?Or?Or.push(e):Or=[e]:_r=e},restoreStateIfNeeded:function(){if(_r){var e=_r,t=Or;if(_r=null,Or=null,x(e),t)for(var n=0;n<t.length;n++)x(t[n])}}},Ar=Rr,Mr={MUST_USE_PROPERTY:1,HAS_BOOLEAN_VALUE:4,HAS_NUMERIC_VALUE:8,HAS_POSITIVE_NUMERIC_VALUE:24,HAS_OVERLOADED_BOOLEAN_VALUE:32,injectDOMPropertyConfig:function(e){var t=Mr,n=e.Properties||{},r=e.DOMAttributeNamespaces||{},o=e.DOMAttributeNames||{},a=e.DOMPropertyNames||{},i=e.DOMMutationMethods||{};e.isCustomAttribute&&Dr._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var l in n){Dr.properties.hasOwnProperty(l)&&Fn("48",l);var u=l.toLowerCase(),s=n[l],c={attributeName:u,attributeNamespace:null,propertyName:l,mutationMethod:null,mustUseProperty:N(s,t.MUST_USE_PROPERTY),hasBooleanValue:N(s,t.HAS_BOOLEAN_VALUE),hasNumericValue:N(s,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:N(s,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:N(s,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(c.hasBooleanValue+c.hasNumericValue+c.hasOverloadedBooleanValue<=1||Fn("50",l),o.hasOwnProperty(l)){var d=o[l];c.attributeName=d}r.hasOwnProperty(l)&&(c.attributeNamespace=r[l]),a.hasOwnProperty(l)&&(c.propertyName=a[l]),i.hasOwnProperty(l)&&(c.mutationMethod=i[l]),Dr.properties[l]=c}}},Fr=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",Dr={ID_ATTRIBUTE_NAME:"data-reactid",ROOT_ATTRIBUTE_NAME:"data-reactroot",ATTRIBUTE_NAME_START_CHAR:Fr,ATTRIBUTE_NAME_CHAR:Fr+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<Dr._isCustomAttributeFunctions.length;t++){if((0,Dr._isCustomAttributeFunctions[t])(e))return!0}return!1},injection:Mr},Ir=Dr,Ur={hasCachedChildNodes:1},Lr=Ur,Hr={IndeterminateComponent:0,FunctionalComponent:1,ClassComponent:2,HostRoot:3,HostPortal:4,HostComponent:5,HostText:6,CoroutineComponent:7,CoroutineHandlerPhase:8,YieldComponent:9,Fragment:10},jr={ELEMENT_NODE:1,TEXT_NODE:3,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_FRAGMENT_NODE:11},Wr=jr,Vr=Hr.HostComponent,Br=Hr.HostText,zr=Wr.ELEMENT_NODE,Kr=Wr.COMMENT_NODE,Yr=Ir.ID_ATTRIBUTE_NAME,qr=Lr,Qr=Math.random().toString(36).slice(2),$r="__reactInternalInstance$"+Qr,Xr="__reactEventHandlers$"+Qr,Gr={getClosestInstanceFromNode:F,getInstanceFromNode:D,getNodeFromInstance:I,precacheChildNodes:M,precacheNode:O,uncacheNode:A,precacheFiberNode:R,getFiberCurrentPropsFromNode:U,updateFiberProps:L},Zr=Gr,Jr={logTopLevelRenders:!1,prepareNewChildrenBeforeUnmountInStack:!0,disableNewFiberFeatures:!1,enableAsyncSubtreeAPI:!1},eo=Jr,to={fiberAsyncScheduling:!1,useCreateElement:!0,useFiber:!0},no=to,ro={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},oo=["Webkit","ms","Moz","O"];Object.keys(ro).forEach(function(e){oo.forEach(function(t){ro[H(t,e)]=ro[e]})});var ao={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},io={isUnitlessNumber:ro,shorthandPropertyExpansions:ao},lo=io,uo=lo.isUnitlessNumber,so=j,co=W,po=/([A-Z])/g,fo=V,mo=/^ms-/,ho=B,go=z,vo=go(function(e){return ho(e)}),yo=!1;if(mr.canUseDOM){var bo=document.createElement("div").style;try{bo.font=""}catch(e){yo=!0}}var Co,ko={createMarkupForStyles:function(e,t){var n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];null!=o&&(n+=vo(r)+":",n+=so(r,o,t)+";")}return n||null},setValueForStyles:function(e,t,n){var r=e.style;for(var o in t)if(t.hasOwnProperty(o)){var a=so(o,t[o],n);if("float"===o&&(o="cssFloat"),a)r[o]=a;else{var i=yo&&lo.shorthandPropertyExpansions[o];if(i)for(var l in i)r[l]="";else r[o]=""}}}},Po=ko,Eo={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"},To=Eo,wo=/["'&<>]/,xo=Y,No=q,So=new RegExp("^["+Ir.ATTRIBUTE_NAME_START_CHAR+"]["+Ir.ATTRIBUTE_NAME_CHAR+"]*$"),_o={},Oo={},Ro={createMarkupForID:function(e){return Ir.ID_ATTRIBUTE_NAME+"="+No(e)},setAttributeForID:function(e,t){e.setAttribute(Ir.ID_ATTRIBUTE_NAME,t)},createMarkupForRoot:function(){return Ir.ROOT_ATTRIBUTE_NAME+'=""'},setAttributeForRoot:function(e){e.setAttribute(Ir.ROOT_ATTRIBUTE_NAME,"")},createMarkupForProperty:function(e,t){var n=Ir.properties.hasOwnProperty(e)?Ir.properties[e]:null;if(n){if($(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&!0===t?r+'=""':r+"="+No(t)}return Ir.isCustomAttribute(e)?null==t?"":e+"="+No(t):null},createMarkupForCustomAttribute:function(e,t){return Q(e)&&null!=t?e+"="+No(t):""},setValueForProperty:function(e,t,n){var r=Ir.properties.hasOwnProperty(t)?Ir.properties[t]:null;if(r){var o=r.mutationMethod;if(o)o(e,n);else{if($(r,n))return void Ro.deleteValueForProperty(e,t);if(r.mustUseProperty)e[r.propertyName]=n;else{var a=r.attributeName,i=r.attributeNamespace;i?e.setAttributeNS(i,a,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&!0===n?e.setAttribute(a,""):e.setAttribute(a,""+n)}}}else if(Ir.isCustomAttribute(t))return void Ro.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){Q(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForAttribute:function(e,t){e.removeAttribute(t)},deleteValueForProperty:function(e,t){var n=Ir.properties.hasOwnProperty(t)?Ir.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseProperty){var o=n.propertyName;n.hasBooleanValue?e[o]=!1:e[o]=""}else e.removeAttribute(n.attributeName)}else Ir.isCustomAttribute(t)&&e.removeAttribute(t)}},Ao=Ro,Mo=function(){function e(){jn(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t};return n.checkPropTypes=Zn,n.PropTypes=n,n},Fo=(function(e,t){t={exports:{}},e(t,t.exports),t.exports}(function(e){e.exports=Mo()}),{getHostProps:function(e,t){var n=e,r=t.value,o=t.checked;return Ln({type:void 0,step:void 0,min:void 0,max:void 0},t,{defaultChecked:void 0,defaultValue:void 0,value:null!=r?r:n._wrapperState.initialValue,checked:null!=o?o:n._wrapperState.initialChecked})},mountWrapper:function(e,t){var n=t.defaultValue;e._wrapperState={initialChecked:null!=t.checked?t.checked:t.defaultChecked,initialValue:null!=t.value?t.value:n,controlled:X(t)}},updateWrapper:function(e,t){var n=e,r=t.checked;null!=r&&Ao.setValueForProperty(n,"checked",r||!1);var o=t.value;if(null!=o)if(0===o&&""===n.value)n.value="0";else if("number"===t.type){var a=parseFloat(n.value,10)||0;o!=a&&(n.value=""+o)}else o!=n.value&&(n.value=""+o);else null==t.value&&null!=t.defaultValue&&n.defaultValue!==""+t.defaultValue&&(n.defaultValue=""+t.defaultValue),null==t.checked&&null!=t.defaultChecked&&(n.defaultChecked=!!t.defaultChecked)},postMountWrapper:function(e,t){var n=e;switch(t.type){case"submit":case"reset":break;case"color":case"date":case"datetime":case"datetime-local":case"month":case"time":case"week":n.value="",n.value=n.defaultValue;break;default:n.value=n.value}var r=n.name;""!==r&&(n.name=""),n.defaultChecked=!n.defaultChecked,n.defaultChecked=!n.defaultChecked,""!==r&&(n.name=r)},restoreControlledState:function(e,t){var n=e;Fo.updateWrapper(n,t),G(n,t)}}),Do=Fo,Io={mountWrapper:function(e,t){},postMountWrapper:function(e,t){null!=t.value&&e.setAttribute("value",t.value)},getHostProps:function(e,t){var n=Ln({children:void 0},t),r=Z(t.children);return r&&(n.children=r),n}},Uo=Io,Lo=!1,Ho={getHostProps:function(e,t){return Ln({},t,{value:void 0})},mountWrapper:function(e,t){var n=e,r=t.value;n._wrapperState={initialValue:null!=r?r:t.defaultValue,wasMultiple:!!t.multiple},void 0===t.value||void 0===t.defaultValue||Lo||(Lo=!0),n.multiple=!!t.multiple,null!=r?J(n,!!t.multiple,r):null!=t.defaultValue&&J(n,!!t.multiple,t.defaultValue)},postUpdateWrapper:function(e,t){var n=e;n._wrapperState.initialValue=void 0;var r=n._wrapperState.wasMultiple;n._wrapperState.wasMultiple=!!t.multiple;var o=t.value;null!=o?J(n,!!t.multiple,o):r!==!!t.multiple&&(null!=t.defaultValue?J(n,!!t.multiple,t.defaultValue):J(n,!!t.multiple,t.multiple?[]:""))},restoreControlledState:function(e,t){var n=e,r=t.value;null!=r&&J(n,!!t.multiple,r)}},jo=Ho,Wo={getHostProps:function(e,t){var n=e;return null!=t.dangerouslySetInnerHTML&&Fn("91"),Ln({},t,{value:void 0,defaultValue:void 0,children:""+n._wrapperState.initialValue})},mountWrapper:function(e,t){var n=e,r=t.value,o=r;if(null==r){var a=t.defaultValue,i=t.children;null!=i&&(null!=a&&Fn("92"),Array.isArray(i)&&(i.length<=1||Fn("93"),i=i[0]),a=""+i),null==a&&(a=""),o=a}n._wrapperState={initialValue:""+o}},updateWrapper:function(e,t){var n=e,r=t.value;if(null!=r){var o=""+r;o!==n.value&&(n.value=o),null==t.defaultValue&&(n.defaultValue=o)}null!=t.defaultValue&&(n.defaultValue=t.defaultValue)},postMountWrapper:function(e,t){var n=e,r=n.textContent;r===n._wrapperState.initialValue&&(n.value=r)},restoreControlledState:function(e,t){Wo.updateWrapper(e,t)}},Vo=Wo,Bo=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,o){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,o)})}:e},zo=Bo,Ko=zo(function(e,t){if(e.namespaceURI!==To.svg||"innerHTML"in e)e.innerHTML=t;else{Co=Co||document.createElement("div"),Co.innerHTML="<svg>"+t+"</svg>";for(var n=Co.firstChild;n.firstChild;)e.appendChild(n.firstChild)}}),Yo=Ko,qo=Wr.TEXT_NODE,Qo=function(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===qo)return void(n.nodeValue=t)}e.textContent=t};mr.canUseDOM&&("textContent"in document.documentElement||(Qo=function(e,t){if(e.nodeType===qo)return void(e.nodeValue=t);Yo(e,xo(t))}));var $o=Qo,Xo={_getTrackerFromNode:function(e){return te(Zr.getInstanceFromNode(e))},trackNode:function(e){e._wrapperState.valueTracker||(e._wrapperState.valueTracker=ae(e,e))},track:function(e){if(!te(e)){ne(e,ae(Zr.getNodeFromInstance(e),e))}},updateValueIfChanged:function(e){if(!e)return!1;var t=te(e);if(!t)return"number"==typeof e.tag?Xo.trackNode(e.stateNode):Xo.track(e),!0;var n=t.getValue(),r=oe(Zr.getNodeFromInstance(e));return r!==n&&(t.setValue(r),!0)},stopTracking:function(e){var t=te(e);t&&t.stopTracking()}},Go=Xo,Zo=Ln||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Jo=Wr.DOCUMENT_FRAGMENT_NODE,ea=xr.listenTo,ta=zn.registrationNameModules,na="dangerouslySetInnerHTML",ra="suppressContentEditableWarning",oa="children",aa="style",ia="__html",la=To.html,ua=To.svg,sa=To.mathml,ca={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},da={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},pa=Zo({menuitem:!0},da),fa={getChildNamespace:function(e,t){return null==e||e===la?me(t):e===ua&&"foreignObject"===t?la:e},createElement:function(e,t,n,r){var o,a=n.ownerDocument,i=r;if(i===la&&(i=me(e)),i===la)if("script"===e){var l=a.createElement("div");l.innerHTML="<script></script>";var u=l.firstChild;o=l.removeChild(u)}else o=t.is?a.createElement(e,{is:t.is}):a.createElement(e);else o=a.createElementNS(i,e);return o},setInitialProperties:function(e,t,n,r){var o,a=de(t,n);switch(t){case"audio":case"form":case"iframe":case"img":case"image":case"link":case"object":case"source":case"video":case"details":ce(e,t),o=n;break;case"input":Do.mountWrapper(e,n),o=Do.getHostProps(e,n),ce(e,t),ue(r,"onChange");break;case"option":Uo.mountWrapper(e,n),o=Uo.getHostProps(e,n);break;case"select":jo.mountWrapper(e,n),o=jo.getHostProps(e,n),ce(e,t),ue(r,"onChange");break;case"textarea":Vo.mountWrapper(e,n),o=Vo.getHostProps(e,n),ce(e,t),ue(r,"onChange");break;default:o=n}switch(le(t,o),pe(e,r,o,a),t){case"input":Go.trackNode(e),Do.postMountWrapper(e,n);break;case"textarea":Go.trackNode(e),Vo.postMountWrapper(e,n);break;case"option":Uo.postMountWrapper(e,n);break;default:"function"==typeof o.onClick&&se(e)}},diffProperties:function(e,t,n,r,o){var a,i,l=null;switch(t){case"input":a=Do.getHostProps(e,n),i=Do.getHostProps(e,r),l=[];break;case"option":a=Uo.getHostProps(e,n),i=Uo.getHostProps(e,r),l=[];break;case"select":a=jo.getHostProps(e,n),i=jo.getHostProps(e,r),l=[];break;case"textarea":a=Vo.getHostProps(e,n),i=Vo.getHostProps(e,r),l=[];break;default:a=n,i=r,"function"!=typeof a.onClick&&"function"==typeof i.onClick&&se(e)}le(t,i);var u,s,c=null;for(u in a)if(!i.hasOwnProperty(u)&&a.hasOwnProperty(u)&&null!=a[u])if(u===aa){var d=a[u];for(s in d)d.hasOwnProperty(s)&&(c||(c={}),c[s]="")}else u===na||u===oa||u===ra||(ta.hasOwnProperty(u)?l||(l=[]):(l=l||[]).push(u,null));for(u in i){var p=i[u],f=null!=a?a[u]:void 0;if(i.hasOwnProperty(u)&&p!==f&&(null!=p||null!=f))if(u===aa)if(f){for(s in f)!f.hasOwnProperty(s)||p&&p.hasOwnProperty(s)||(c||(c={}),c[s]="");for(s in p)p.hasOwnProperty(s)&&f[s]!==p[s]&&(c||(c={}),c[s]=p[s])}else c||(l||(l=[]),l.push(u,c)),c=p;else if(u===na){var m=p?p[ia]:void 0,h=f?f[ia]:void 0;null!=m&&h!==m&&(l=l||[]).push(u,""+m)}else u===oa?f===p||"string"!=typeof p&&"number"!=typeof p||(l=l||[]).push(u,""+p):u===ra||(ta.hasOwnProperty(u)?(p&&ue(o,u),l||f===p||(l=[])):(l=l||[]).push(u,p))}return c&&(l=l||[]).push(aa,c),l},updateProperties:function(e,t,n,r,o){switch(fe(e,t,de(n,r),de(n,o)),n){case"input":Do.updateWrapper(e,o);break;case"textarea":Vo.updateWrapper(e,o);break;case"select":jo.postUpdateWrapper(e,o)}},restoreControlledState:function(e,t,n){switch(t){case"input":return void Do.restoreControlledState(e,n);case"textarea":return void Vo.restoreControlledState(e,n);case"select":return void jo.restoreControlledState(e,n)}}},ma=fa,ha=void 0,ga=void 0;if("function"!=typeof requestAnimationFrame)jn(!1,"React depends on requestAnimationFrame. Make sure that you load a polyfill in older browsers.");else if("function"!=typeof requestIdleCallback){var va=null,ya=null,ba=!1,Ca=!1,ka=0,Pa=33,Ea=33,Ta={timeRemaining:"object"==typeof performance&&"function"==typeof performance.now?function(){return ka-performance.now()}:function(){return ka-Date.now()}},wa="__reactIdleCallback$"+Math.random().toString(36).slice(2),xa=function(e){if(e.source===window&&e.data===wa){ba=!1;var t=ya;ya=null,t&&t(Ta)}};window.addEventListener("message",xa,!1);var Na=function(e){Ca=!1;var t=e-ka+Ea;t<Ea&&Pa<Ea?(t<8&&(t=8),Ea=t<Pa?Pa:t):Pa=t,ka=e+Ea,ba||(ba=!0,window.postMessage(wa,"*"));var n=va;va=null,n&&n(e)};ha=function(e){return va=e,Ca||(Ca=!0,requestAnimationFrame(Na)),0},ga=function(e){return ya=e,Ca||(Ca=!0,requestAnimationFrame(Na)),0}}else ha=requestAnimationFrame,ga=requestIdleCallback;var Sa=ha,_a=ga,Oa={rAF:Sa,rIC:_a},Ra={Properties:{"aria-current":0,"aria-details":0,"aria-disabled":0,"aria-hidden":0,"aria-invalid":0,"aria-keyshortcuts":0,"aria-label":0,"aria-roledescription":0,"aria-autocomplete":0,"aria-checked":0,"aria-expanded":0,"aria-haspopup":0,"aria-level":0,"aria-modal":0,"aria-multiline":0,"aria-multiselectable":0,"aria-orientation":0,"aria-placeholder":0,"aria-pressed":0,"aria-readonly":0,"aria-required":0,"aria-selected":0,"aria-sort":0,"aria-valuemax":0,"aria-valuemin":0,"aria-valuenow":0,"aria-valuetext":0,"aria-atomic":0,"aria-busy":0,"aria-live":0,"aria-relevant":0,"aria-dropeffect":0,"aria-grabbed":0,"aria-activedescendant":0,"aria-colcount":0,"aria-colindex":0,"aria-colspan":0,"aria-controls":0,"aria-describedby":0,"aria-errormessage":0,"aria-flowto":0,"aria-labelledby":0,"aria-owns":0,"aria-posinset":0,"aria-rowcount":0,"aria-rowindex":0,"aria-rowspan":0,"aria-setsize":0},DOMAttributeNames:{},DOMPropertyNames:{}},Aa=Ra,Ma=Hr.HostComponent,Fa={isAncestor:ve,getLowestCommonAncestor:ge,getParentInstance:ye,traverseTwoPhase:be,traverseEnterLeave:Ce},Da=sr.getListener,Ia={accumulateTwoPhaseDispatches:Ne,accumulateTwoPhaseDispatchesSkipTarget:Se,accumulateDirectDispatches:Oe,accumulateEnterLeaveDispatches:_e},Ua=Ia,La=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},Ha=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},ja=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},Wa=function(e,t,n,r){var o=this;if(o.instancePool.length){var a=o.instancePool.pop();return o.call(a,e,t,n,r),a}return new o(e,t,n,r)},Va=function(e){var t=this;e instanceof t||Fn("25"),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},Ba=La,za=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||Ba,n.poolSize||(n.poolSize=10),n.release=Va,n},Ka={addPoolingTo:za,oneArgumentPooler:La,twoArgumentPooler:Ha,threeArgumentPooler:ja,fourArgumentPooler:Wa},Ya=Ka,qa=null,Qa=Re;Ln(Ae.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[Qa()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),a=o.length;for(e=0;e<r&&n[e]===o[e];e++);var i=r-e;for(t=1;t<=i&&n[r-t]===o[a-t];t++);var l=t>1?1-t:void 0;return this._fallbackText=o.slice(e,l),this._fallbackText}}),Ya.addPoolingTo(Ae);var $a=Ae,Xa=["dispatchConfig","_targetInst","nativeEvent","isDefaultPrevented","isPropagationStopped","_dispatchListeners","_dispatchInstances"],Ga={type:null,target:null,currentTarget:Zn.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};Ln(Me.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=Zn.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=Zn.thatReturnsTrue)},persist:function(){this.isPersistent=Zn.thatReturnsTrue},isPersistent:Zn.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;for(var n=0;n<Xa.length;n++)this[Xa[n]]=null}}),Me.Interface=Ga,Me.augmentClass=function(e,t){var n=this,r=function(){};r.prototype=n.prototype;var o=new r;Ln(o,e.prototype),e.prototype=o,e.prototype.constructor=e,e.Interface=Ln({},n.Interface,t),e.augmentClass=n.augmentClass,Ya.addPoolingTo(e,Ya.fourArgumentPooler)},Ya.addPoolingTo(Me,Ya.fourArgumentPooler);var Za=Me,Ja={data:null};Za.augmentClass(Fe,Ja);var ei=Fe,ti={data:null};Za.augmentClass(De,ti);var ni=De,ri=[9,13,27,32],oi=229,ai=mr.canUseDOM&&"CompositionEvent"in window,ii=null ;mr.canUseDOM&&"documentMode"in document&&(ii=document.documentMode);var li=mr.canUseDOM&&"TextEvent"in window&&!ii&&!function(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}(),ui=mr.canUseDOM&&(!ai||ii&&ii>8&&ii<=11),si=32,ci=String.fromCharCode(si),di={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["topCompositionEnd","topKeyPress","topTextInput","topPaste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:["topBlur","topCompositionEnd","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:["topBlur","topCompositionStart","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:["topBlur","topCompositionUpdate","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]}},pi=!1,fi=null,mi={eventTypes:di,extractEvents:function(e,t,n,r){return[We(e,t,n,r),ze(e,t,n,r)]}},hi=mi,gi=function(e,t,n,r,o,a){return e(t,n,r,o,a)},vi=function(e,t){return e(t)},yi=!1,bi={injectStackBatchedUpdates:function(e){gi=e},injectFiberBatchedUpdates:function(e){vi=e}},Ci={batchedUpdates:qe,injection:bi},ki=Ci,Pi=Wr.TEXT_NODE,Ei=Qe,Ti={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0},wi=$e,xi={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:["topBlur","topChange","topClick","topFocus","topInput","topKeyDown","topKeyUp","topSelectionChange"]}},Ni=null,Si=null,_i=!1;mr.canUseDOM&&(_i=Cr("input")&&(!document.documentMode||document.documentMode>9));var Oi={eventTypes:xi,_isInputEventSupported:_i,extractEvents:function(e,t,n,r){var o,a,i=t?Zr.getNodeFromInstance(t):window;if(Ge(i)?o=tt:wi(i)?_i?o=st:(o=it,a=at):lt(i)&&(o=ut),o){var l=o(e,t);if(l){return Xe(l,n,r)}}a&&a(e,i,t),"topBlur"===e&&ct(t,i)}},Ri=Oi,Ai=["ResponderEventPlugin","SimpleEventPlugin","TapEventPlugin","EnterLeaveEventPlugin","ChangeEventPlugin","SelectEventPlugin","BeforeInputEventPlugin"],Mi=Ai,Fi={view:function(e){if(e.view)return e.view;var t=Ei(e);if(t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};Za.augmentClass(dt,Fi);var Di=dt,Ii={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"},Ui=ft,Li={screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Ui,button:null,buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)}};Di.augmentClass(mt,Li);var Hi=mt,ji={mouseEnter:{registrationName:"onMouseEnter",dependencies:["topMouseOut","topMouseOver"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["topMouseOut","topMouseOver"]}},Wi={eventTypes:ji,extractEvents:function(e,t,n,r){if("topMouseOver"===e&&(n.relatedTarget||n.fromElement))return null;if("topMouseOut"!==e&&"topMouseOver"!==e)return null;var o;if(r.window===r)o=r;else{var a=r.ownerDocument;o=a?a.defaultView||a.parentWindow:window}var i,l;if("topMouseOut"===e){i=t;var u=n.relatedTarget||n.toElement;l=u?Zr.getClosestInstanceFromNode(u):null}else i=null,l=t;if(i===l)return null;var s=null==i?o:Zr.getNodeFromInstance(i),c=null==l?o:Zr.getNodeFromInstance(l),d=Hi.getPooled(ji.mouseLeave,i,n,r);d.type="mouseleave",d.target=s,d.relatedTarget=c;var p=Hi.getPooled(ji.mouseEnter,l,n,r);return p.type="mouseenter",p.target=c,p.relatedTarget=s,Ua.accumulateEnterLeaveDispatches(d,p,i,l),[d,p]}},Vi=Wi,Bi=Ir.injection.MUST_USE_PROPERTY,zi=Ir.injection.HAS_BOOLEAN_VALUE,Ki=Ir.injection.HAS_NUMERIC_VALUE,Yi=Ir.injection.HAS_POSITIVE_NUMERIC_VALUE,qi=Ir.injection.HAS_OVERLOADED_BOOLEAN_VALUE,Qi={isCustomAttribute:RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+Ir.ATTRIBUTE_NAME_CHAR+"]*$")),Properties:{accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:zi,allowTransparency:0,alt:0,as:0,async:zi,autoComplete:0,autoPlay:zi,capture:zi,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:Bi|zi,cite:0,classID:0,className:0,cols:Yi,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:zi,coords:0,crossOrigin:0,data:0,dateTime:0,default:zi,defer:zi,dir:0,disabled:zi,download:qi,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:zi,formTarget:0,frameBorder:0,headers:0,height:0,hidden:zi,high:0,href:0,hrefLang:0,htmlFor:0,httpEquiv:0,id:0,inputMode:0,integrity:0,is:0,keyParams:0,keyType:0,kind:0,label:0,lang:0,list:0,loop:zi,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:Bi|zi,muted:Bi|zi,name:0,nonce:0,noValidate:zi,open:zi,optimum:0,pattern:0,placeholder:0,playsInline:zi,poster:0,preload:0,profile:0,radioGroup:0,readOnly:zi,referrerPolicy:0,rel:0,required:zi,reversed:zi,role:0,rows:Yi,rowSpan:Ki,sandbox:0,scope:0,scoped:zi,scrolling:0,seamless:zi,selected:Bi|zi,shape:0,size:Yi,sizes:0,slot:0,span:Yi,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:Ki,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:0,width:0,wmode:0,wrap:0,about:0,datatype:0,inlist:0,prefix:0,property:0,resource:0,typeof:0,vocab:0,autoCapitalize:0,autoCorrect:0,autoSave:0,color:0,itemProp:0,itemScope:zi,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{},DOMMutationMethods:{value:function(e,t){if(null==t)return e.removeAttribute("value");"number"!==e.type||!1===e.hasAttribute("value")?e.setAttribute("value",""+t):e.validity&&!e.validity.badInput&&e.ownerDocument.activeElement!==e&&e.setAttribute("value",""+t)}}},$i=Qi,Xi={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:Zn}},registerDefault:function(){}},Gi=Xi,Zi=ht,Ji=Hr.HostRoot;Ln(vt.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.targetInst=null,this.ancestors.length=0}}),Ya.addPoolingTo(vt,Ya.threeArgumentPooler);var el={_enabled:!0,_handleTopLevel:null,setHandleTopLevel:function(e){el._handleTopLevel=e},setEnabled:function(e){el._enabled=!!e},isEnabled:function(){return el._enabled},trapBubbledEvent:function(e,t,n){return n?Gi.listen(n,t,el.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){return n?Gi.capture(n,t,el.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=bt.bind(null,e);Gi.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(el._enabled){var n=Ei(t),r=Zr.getClosestInstanceFromNode(n),o=vt.getPooled(e,t,r);try{ki.batchedUpdates(yt,o)}finally{vt.release(o)}}}},tl=el,nl={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},rl={accentHeight:"accent-height",accumulate:0,additive:0,alignmentBaseline:"alignment-baseline",allowReorder:"allowReorder",alphabetic:0,amplitude:0,arabicForm:"arabic-form",ascent:0,attributeName:"attributeName",attributeType:"attributeType",autoReverse:"autoReverse",azimuth:0,baseFrequency:"baseFrequency",baseProfile:"baseProfile",baselineShift:"baseline-shift",bbox:0,begin:0,bias:0,by:0,calcMode:"calcMode",capHeight:"cap-height",clip:0,clipPath:"clip-path",clipRule:"clip-rule",clipPathUnits:"clipPathUnits",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",contentScriptType:"contentScriptType",contentStyleType:"contentStyleType",cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:"diffuseConstant",direction:0,display:0,divisor:0,dominantBaseline:"dominant-baseline",dur:0,dx:0,dy:0,edgeMode:"edgeMode",elevation:0,enableBackground:"enable-background",end:0,exponent:0,externalResourcesRequired:"externalResourcesRequired",fill:0,fillOpacity:"fill-opacity",fillRule:"fill-rule",filter:0,filterRes:"filterRes",filterUnits:"filterUnits",floodColor:"flood-color",floodOpacity:"flood-opacity",focusable:0,fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",glyphRef:"glyphRef",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",hanging:0,horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",ideographic:0,imageRendering:"image-rendering",in:0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:"kernelMatrix",kernelUnitLength:"kernelUnitLength",kerning:0,keyPoints:"keyPoints",keySplines:"keySplines",keyTimes:"keyTimes",lengthAdjust:"lengthAdjust",letterSpacing:"letter-spacing",lightingColor:"lighting-color",limitingConeAngle:"limitingConeAngle",local:0,markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",markerHeight:"markerHeight",markerUnits:"markerUnits",markerWidth:"markerWidth",mask:0,maskContentUnits:"maskContentUnits",maskUnits:"maskUnits",mathematical:0,mode:0,numOctaves:"numOctaves",offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pathLength:"pathLength",patternContentUnits:"patternContentUnits",patternTransform:"patternTransform",patternUnits:"patternUnits",pointerEvents:"pointer-events",points:0,pointsAtX:"pointsAtX",pointsAtY:"pointsAtY",pointsAtZ:"pointsAtZ",preserveAlpha:"preserveAlpha",preserveAspectRatio:"preserveAspectRatio",primitiveUnits:"primitiveUnits",r:0,radius:0,refX:"refX",refY:"refY",renderingIntent:"rendering-intent",repeatCount:"repeatCount",repeatDur:"repeatDur",requiredExtensions:"requiredExtensions",requiredFeatures:"requiredFeatures",restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:"shape-rendering",slope:0,spacing:0,specularConstant:"specularConstant",specularExponent:"specularExponent",speed:0,spreadMethod:"spreadMethod",startOffset:"startOffset",stdDeviation:"stdDeviation",stemh:0,stemv:0,stitchTiles:"stitchTiles",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",string:0,stroke:0,strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",surfaceScale:"surfaceScale",systemLanguage:"systemLanguage",tableValues:"tableValues",targetX:"targetX",targetY:"targetY",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",textLength:"textLength",to:0,transform:0,u1:0,u2:0,underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicode:0,unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",values:0,vectorEffect:"vector-effect",version:0,vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",viewBox:"viewBox",viewTarget:"viewTarget",visibility:0,widths:0,wordSpacing:"word-spacing",writingMode:"writing-mode",x:0,xHeight:"x-height",x1:0,x2:0,xChannelSelector:"xChannelSelector",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlns:0,xmlnsXlink:"xmlns:xlink",xmlLang:"xml:lang",xmlSpace:"xml:space",y:0,y1:0,y2:0,yChannelSelector:"yChannelSelector",z:0,zoomAndPan:"zoomAndPan"},ol={Properties:{},DOMAttributeNamespaces:{xlinkActuate:nl.xlink,xlinkArcrole:nl.xlink,xlinkHref:nl.xlink,xlinkRole:nl.xlink,xlinkShow:nl.xlink,xlinkTitle:nl.xlink,xlinkType:nl.xlink,xmlBase:nl.xml,xmlLang:nl.xml,xmlSpace:nl.xml},DOMAttributeNames:{}};Object.keys(rl).forEach(function(e){ol.Properties[e]=0,rl[e]&&(ol.DOMAttributeNames[e]=rl[e])});var al=ol,il=Wr.TEXT_NODE,ll=Pt,ul={getOffsets:Tt,setOffsets:wt},sl=ul,cl=xt,dl=Nt,pl=St,fl=_t,ml=Ot,hl=Wr.ELEMENT_NODE,gl={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=ml();return{focusedElem:e,selectionRange:gl.hasSelectionCapabilities(e)?gl.getSelection(e):null}},restoreSelection:function(e){var t=ml(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&Rt(n)){gl.hasSelectionCapabilities(n)&&gl.setSelection(n,r);for(var o=[],a=n;a=a.parentNode;)a.nodeType===hl&&o.push({element:a,left:a.scrollLeft,top:a.scrollTop});fl(n);for(var i=0;i<o.length;i++){var l=o[i];l.element.scrollLeft=l.left,l.element.scrollTop=l.top}}},getSelection:function(e){return("selectionStart"in e?{start:e.selectionStart,end:e.selectionEnd}:sl.getOffsets(e))||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;void 0===r&&(r=n),"selectionStart"in e?(e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length)):sl.setOffsets(e,t)}},vl=gl,yl=Object.prototype.hasOwnProperty,bl=Mt,Cl=Wr.DOCUMENT_NODE,kl=mr.canUseDOM&&"documentMode"in document&&document.documentMode<=11,Pl={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:["topBlur","topContextMenu","topFocus","topKeyDown","topKeyUp","topMouseDown","topMouseUp","topSelectionChange"]}},El=null,Tl=null,wl=null,xl=!1,Nl=xr.isListeningToAllDependencies,Sl={eventTypes:Pl,extractEvents:function(e,t,n,r){var o=r.window===r?r.document:r.nodeType===Cl?r:r.ownerDocument;if(!o||!Nl("onSelect",o))return null;var a=t?Zr.getNodeFromInstance(t):window;switch(e){case"topFocus":(wi(a)||"true"===a.contentEditable)&&(El=a,Tl=t,wl=null);break;case"topBlur":El=null,Tl=null,wl=null;break;case"topMouseDown":xl=!0;break;case"topContextMenu":case"topMouseUp":return xl=!1,Dt(n,r);case"topSelectionChange":if(kl)break;case"topKeyDown":case"topKeyUp":return Dt(n,r)}return null}},_l=Sl,Ol={animationName:null,elapsedTime:null,pseudoElement:null};Za.augmentClass(It,Ol);var Rl=It,Al={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};Za.augmentClass(Ut,Al);var Ml=Ut,Fl={relatedTarget:null};Di.augmentClass(Lt,Fl);var Dl=Lt,Il=Ht,Ul={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Ll={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Hl=jt,jl={key:Hl,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Ui,charCode:function(e){return"keypress"===e.type?Il(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?Il(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};Di.augmentClass(Wt,jl);var Wl=Wt,Vl={dataTransfer:null};Hi.augmentClass(Vt,Vl);var Bl=Vt,zl={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Ui};Di.augmentClass(Bt,zl);var Kl=Bt,Yl={propertyName:null,elapsedTime:null,pseudoElement:null};Za.augmentClass(zt,Yl);var ql=zt,Ql={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};Hi.augmentClass(Kt,Ql);var $l=Kt,Xl={},Gl={};["abort","animationEnd","animationIteration","animationStart","blur","cancel","canPlay","canPlayThrough","click","close","contextMenu","copy","cut","doubleClick","drag","dragEnd","dragEnter","dragExit","dragLeave","dragOver","dragStart","drop","durationChange","emptied","encrypted","ended","error","focus","input","invalid","keyDown","keyPress","keyUp","load","loadedData","loadedMetadata","loadStart","mouseDown","mouseMove","mouseOut","mouseOver","mouseUp","paste","pause","play","playing","progress","rateChange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeUpdate","toggle","touchCancel","touchEnd","touchMove","touchStart","transitionEnd","volumeChange","waiting","wheel"].forEach(function(e){var t=e[0].toUpperCase()+e.slice(1),n="on"+t,r="top"+t,o={phasedRegistrationNames:{bubbled:n,captured:n+"Capture"},dependencies:[r]};Xl[e]=o,Gl[r]=o});var Zl,Jl,eu={eventTypes:Xl,extractEvents:function(e,t,n,r){var o=Gl[e];if(!o)return null;var a;switch(e){case"topAbort":case"topCancel":case"topCanPlay":case"topCanPlayThrough":case"topClose":case"topDurationChange":case"topEmptied":case"topEncrypted":case"topEnded":case"topError":case"topInput":case"topInvalid":case"topLoad":case"topLoadedData":case"topLoadedMetadata":case"topLoadStart":case"topPause":case"topPlay":case"topPlaying":case"topProgress":case"topRateChange":case"topReset":case"topSeeked":case"topSeeking":case"topStalled":case"topSubmit":case"topSuspend":case"topTimeUpdate":case"topToggle":case"topVolumeChange":case"topWaiting":a=Za;break;case"topKeyPress":if(0===Il(n))return null;case"topKeyDown":case"topKeyUp":a=Wl;break;case"topBlur":case"topFocus":a=Dl;break;case"topClick":if(2===n.button)return null;case"topDoubleClick":case"topMouseDown":case"topMouseMove":case"topMouseUp":case"topMouseOut":case"topMouseOver":case"topContextMenu":a=Hi;break;case"topDrag":case"topDragEnd":case"topDragEnter":case"topDragExit":case"topDragLeave":case"topDragOver":case"topDragStart":case"topDrop":a=Bl;break;case"topTouchCancel":case"topTouchEnd":case"topTouchMove":case"topTouchStart":a=Kl;break;case"topAnimationEnd":case"topAnimationIteration":case"topAnimationStart":a=Rl;break;case"topTransitionEnd":a=ql;break;case"topScroll":a=Di;break;case"topWheel":a=$l;break;case"topCopy":case"topCut":case"topPaste":a=Ml}a||Fn("86",e);var i=a.getPooled(o,t,n,r);return Ua.accumulateTwoPhaseDispatches(i),i}},tu=eu,nu=!1,ru={inject:Yt},ou={NoEffect:0,Placement:1,Update:2,PlacementAndUpdate:3,Deletion:4,ContentReset:8,Callback:16,Err:32,Ref:64},au={NoWork:0,SynchronousPriority:1,TaskPriority:2,AnimationPriority:3,HighPriority:4,LowPriority:5,OffscreenPriority:6},iu=ou.Callback,lu=au.NoWork,uu=au.SynchronousPriority,su=au.TaskPriority,cu=$t,du=en,pu=tn,fu=nn,mu=rn,hu=on,gu=ln,vu=un,yu={cloneUpdateQueue:cu,addUpdate:du,addReplaceUpdate:pu,addForceUpdate:fu,getPendingPriority:mu,addTopLevelUpdate:hu,beginUpdateQueue:gu,commitCallbacks:vu},bu={},Cu=bu,ku={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}},Pu=ku,Eu=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Tu={ReactCurrentOwner:Eu.ReactCurrentOwner},wu=Tu,xu=Hr.HostRoot,Nu=Hr.HostComponent,Su=Hr.HostText,_u=ou.NoEffect,Ou=ou.Placement,Ru=1,Au=2,Mu=3,Fu=function(e){return sn(e)===Au},Du=function(e){var t=Pu.get(e);return!!t&&sn(t)===Au},Iu=dn,Uu=function(e){var t=dn(e);if(!t)return null;for(var n=t;;){if(n.tag===Nu||n.tag===Su)return n;if(n.child)n.child.return=n,n=n.child;else{if(n===t)return null;for(;!n.sibling;){if(!n.return||n.return===t)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}}return null},Lu={isFiberMounted:Fu,isMounted:Du,findCurrentFiberUsingSlowPath:Iu,findCurrentHostFiber:Uu},Hu=[],ju=-1,Wu=function(e){return{current:e}},Vu=function(){return-1===ju},Bu=function(e,t){ju<0||(e.current=Hu[ju],Hu[ju]=null,ju--)},zu=function(e,t,n){ju++,Hu[ju]=e.current,e.current=t},Ku=function(){for(;ju>-1;)Hu[ju]=null,ju--},Yu={createCursor:Wu,isEmpty:Vu,pop:Bu,push:zu,reset:Ku},qu=Ln||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Qu=Lu.isFiberMounted,$u=Hr.ClassComponent,Xu=Hr.HostRoot,Gu=Yu.createCursor,Zu=Yu.pop,Ju=Yu.push,es=Gu(Cu),ts=Gu(!1),ns=Cu,rs=pn,os=fn,as=function(e,t){var n=e.type,r=n.contextTypes;if(!r)return Cu;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var a={};for(var i in r)a[i]=t[i];return o&&fn(e,t,a),a},is=function(){return ts.current},ls=mn,us=hn,ss=gn,cs=function(e,t,n){jn(null==es.cursor,"Unexpected context found on stack"),Ju(es,t,e),Ju(ts,n,e)},ds=vn,ps=function(e){if(!hn(e))return!1;var t=e.stateNode,n=t&&t.__reactInternalMemoizedMergedChildContext||Cu;return ns=es.current,Ju(es,n,e),Ju(ts,!1,e),!0},fs=function(e){var t=e.stateNode;jn(t,"Expected to have an instance by this point.");var n=vn(e,ns,!0);t.__reactInternalMemoizedMergedChildContext=n,Zu(ts,e),Zu(es,e),Ju(es,n,e),Ju(ts,!0,e)},ms=function(){ns=Cu,es.current=Cu,ts.current=!1},hs=function(e){jn(Qu(e)&&e.tag===$u,"Expected subtree parent to be a mounted class component");for(var t=e;t.tag!==Xu;){if(hn(t))return t.stateNode.__reactInternalMemoizedMergedChildContext;var n=t.return;jn(n,"Found unexpected detached subtree parent"),t=n}return t.stateNode.context},gs={getUnmaskedContext:rs,cacheContext:os,getMaskedContext:as,hasContextChanged:is,isContextConsumer:ls,isContextProvider:us,popContextProvider:ss,pushTopLevelContextObject:cs,processChildContext:ds,pushContextProvider:ps,invalidateContextProvider:fs,resetContext:ms,findCurrentUnmaskedContext:hs},vs={NoContext:0,AsyncUpdates:1},ys=Hr.IndeterminateComponent,bs=Hr.ClassComponent,Cs=Hr.HostRoot,ks=Hr.HostComponent,Ps=Hr.HostText,Es=Hr.HostPortal,Ts=Hr.CoroutineComponent,ws=Hr.YieldComponent,xs=Hr.Fragment,Ns=au.NoWork,Ss=vs.NoContext,_s=vs.AsyncUpdates,Os=ou.NoEffect,Rs=yu.cloneUpdateQueue,As=function(e,t,n){return{tag:e,key:t,type:null,stateNode:null,return:null,child:null,sibling:null,index:0,ref:null,pendingProps:null,memoizedProps:null,updateQueue:null,memoizedState:null,internalContextTag:n,effectTag:Os,nextEffect:null,firstEffect:null,lastEffect:null,pendingWorkPriority:Ns,progressedPriority:Ns,progressedChild:null,progressedFirstDeletion:null,progressedLastDeletion:null,alternate:null}},Ms=function(e,t){var n=e.alternate;return null!==n?(n.effectTag=Os,n.nextEffect=null,n.firstEffect=null,n.lastEffect=null):(n=As(e.tag,e.key,e.internalContextTag),n.type=e.type,n.progressedChild=e.progressedChild,n.progressedPriority=e.progressedPriority,n.alternate=e,e.alternate=n),n.stateNode=e.stateNode,n.child=e.child,n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n.pendingProps=e.pendingProps,Rs(e,n),n.pendingWorkPriority=t,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n},Fs=function(){return As(Cs,null,Ss)},Ds=function(e,t,n){var r=bn(e.type,e.key,t,null);return r.pendingProps=e.props,r.pendingWorkPriority=n,r},Is=function(e,t,n){var r=As(xs,null,t);return r.pendingProps=e,r.pendingWorkPriority=n,r},Us=function(e,t,n){var r=As(Ps,null,t);return r.pendingProps=e,r.pendingWorkPriority=n,r},Ls=bn,Hs=function(e,t,n){var r=As(Ts,e.key,t);return r.type=e.handler,r.pendingProps=e,r.pendingWorkPriority=n,r},js=function(e,t,n){return As(ws,null,t)},Ws=function(e,t,n){var r=As(Es,e.key,t);return r.pendingProps=e.children||[],r.pendingWorkPriority=n,r.stateNode={containerInfo:e.containerInfo,implementation:e.implementation},r},Vs={cloneFiber:Ms,createHostRootFiber:Fs,createFiberFromElement:Ds,createFiberFromFragment:Is,createFiberFromText:Us,createFiberFromElementType:Ls,createFiberFromCoroutine:Hs,createFiberFromYield:js,createFiberFromPortal:Ws},Bs=Vs.createHostRootFiber,zs=function(e){var t=Bs(),n={current:t,containerInfo:e,isScheduled:!1,nextScheduledRoot:null,context:null,pendingContext:null};return t.stateNode=n,n},Ks={createFiberRoot:zs},Ys=Hr.IndeterminateComponent,qs=Hr.FunctionalComponent,Qs=Hr.ClassComponent,$s=Hr.HostComponent,Xs={getStackAddendumByWorkInProgressFiber:Pn,describeComponentFrame:Cn},Gs=function(){return!0},Zs=Gs,Js={injectDialog:function(e){jn(Zs===Gs,"The custom dialog was already injected."),jn("function"==typeof e,"Injected showDialog() must be a function."),Zs=e}},ec=En,tc={injection:Js,logCapturedError:ec},nc="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,rc=nc;"function"==typeof Symbol&&Symbol.for?(Zl=Symbol.for("react.coroutine"),Jl=Symbol.for("react.yield")):(Zl=60104,Jl=60105);var oc=function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:Zl,key:null==r?null:""+r,children:e,handler:t,props:n}},ac=function(e){return{$$typeof:Jl,value:e}},ic=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===Zl},lc=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===Jl},uc=Jl,sc=Zl,cc={createCoroutine:oc,createYield:ac,isCoroutine:ic,isYield:lc,REACT_YIELD_TYPE:uc,REACT_COROUTINE_TYPE:sc},dc="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.portal")||60106,pc=function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:dc,key:null==r?null:""+r,children:e,containerInfo:t,implementation:n}},fc=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===dc},mc=dc,hc={createPortal:pc,isPortal:fc,REACT_PORTAL_TYPE:mc},gc="function"==typeof Symbol&&Symbol.iterator,vc="@@iterator",yc=Tn,bc=cc.REACT_COROUTINE_TYPE,Cc=cc.REACT_YIELD_TYPE,kc=hc.REACT_PORTAL_TYPE,Pc=Vs.cloneFiber,Ec=Vs.createFiberFromElement,Tc=Vs.createFiberFromFragment,wc=Vs.createFiberFromText,xc=Vs.createFiberFromCoroutine,Nc=Vs.createFiberFromYield,Sc=Vs.createFiberFromPortal,_c=Array.isArray,Oc=Hr.FunctionalComponent,Rc=Hr.ClassComponent,Ac=Hr.HostText,Mc=Hr.HostPortal,Fc=Hr.CoroutineComponent,Dc=Hr.YieldComponent,Ic=Hr.Fragment,Uc=ou.NoEffect,Lc=ou.Placement,Hc=ou.Deletion,jc=Nn(!0,!0),Wc=Nn(!1,!0),Vc=Nn(!1,!1),Bc=function(e,t){if(t.child)if(null!==e&&t.child===e.child){var n=t.child,r=Pc(n,n.pendingWorkPriority);for(t.child=r,r.return=t;null!==n.sibling;)n=n.sibling,r=r.sibling=Pc(n,n.pendingWorkPriority),r.return=t;r.sibling=null}else for(var o=t.child;null!==o;)o.return=t,o=o.sibling},zc={reconcileChildFibers:jc,reconcileChildFibersInPlace:Wc,mountChildFibersInPlace:Vc,cloneChildFibers:Bc},Kc=ou.Update,Yc=gs.cacheContext,qc=gs.getMaskedContext,Qc=gs.getUnmaskedContext,$c=gs.isContextConsumer,Xc=yu.addUpdate,Gc=yu.addReplaceUpdate,Zc=yu.addForceUpdate,Jc=yu.beginUpdateQueue,ed=gs,td=ed.hasContextChanged,nd=Lu.isMounted,rd=Array.isArray,od=function(e,t,n,r){function o(e,t,n,r,o,a){if(null===t||null!==e.updateQueue&&e.updateQueue.hasForceUpdate)return!0;var i=e.stateNode;if("function"==typeof i.shouldComponentUpdate){return i.shouldComponentUpdate(n,o,a)}var l=e.type;return!l.prototype||!l.prototype.isPureReactComponent||(!bl(t,n)||!bl(r,o))}function a(e){var t=e.stateNode,n=t.state;n&&("object"!=typeof n||rd(n))&&Fn("106",co(e)),"function"==typeof t.getChildContext&&"object"!=typeof e.type.childContextTypes&&Fn("107",co(e))}function i(e,t){t.props=e.memoizedProps,t.state=e.memoizedState}function l(e,t){t.updater=p,e.stateNode=t,Pu.set(t,e)}function u(e){var t=e.type,n=e.pendingProps,r=Qc(e),o=$c(e),i=o?qc(e,r):Cu,u=new t(n,i);return l(e,u),a(e),o&&Yc(e,r,i),u}function s(e,t){var n=e.stateNode,r=n.state||null,o=e.pendingProps;jn(o,"There must be pending props for an initial mount. This error is likely caused by a bug in React. Please file an issue.");var a=Qc(e);if(n.props=o,n.state=r,n.refs=Cu,n.context=qc(e,a),"function"==typeof n.componentWillMount){n.componentWillMount();var i=e.updateQueue;null!==i&&(n.state=Jc(e,i,n,r,o,t))}"function"==typeof n.componentDidMount&&(e.effectTag|=Kc)}function c(e,t){var n=e.stateNode;i(e,n);var r=e.memoizedState,a=e.pendingProps;a||(a=e.memoizedProps,jn(null!=a,"There should always be pending or memoized props. This error is likely caused by a bug in React. Please file an issue."));var l=Qc(e),s=qc(e,l);if(!o(e,e.memoizedProps,a,e.memoizedState,r,s))return n.props=a,n.state=r,n.context=s,!1;var c=u(e);c.props=a,c.state=r=c.state||null,c.context=s,"function"==typeof c.componentWillMount&&c.componentWillMount();var d=e.updateQueue;return null!==d&&(c.state=Jc(e,d,c,r,a,t)),"function"==typeof n.componentDidMount&&(e.effectTag|=Kc),!0}function d(e,t,a){var l=t.stateNode;i(t,l);var u=t.memoizedProps,s=t.pendingProps;s||(s=u,jn(null!=s,"There should always be pending or memoized props. This error is likely caused by a bug in React. Please file an issue."));var c=l.context,d=Qc(t),f=qc(t,d);u===s&&c===f||"function"==typeof l.componentWillReceiveProps&&(l.componentWillReceiveProps(s,f),l.state!==t.memoizedState&&p.enqueueReplaceState(l,l.state,null));var m=t.updateQueue,h=t.memoizedState,g=void 0;if(g=null!==m?Jc(t,m,l,h,s,a):h,!(u!==s||h!==g||td()||null!==m&&m.hasForceUpdate))return"function"==typeof l.componentDidUpdate&&(u===e.memoizedProps&&h===e.memoizedState||(t.effectTag|=Kc)),!1;var v=o(t,u,s,h,g,f);return v?("function"==typeof l.componentWillUpdate&&l.componentWillUpdate(s,g,f),"function"==typeof l.componentDidUpdate&&(t.effectTag|=Kc)):("function"==typeof l.componentDidUpdate&&(u===e.memoizedProps&&h===e.memoizedState||(t.effectTag|=Kc)),n(t,s),r(t,g)),l.props=s,l.state=g,l.context=f,v}var p={isMounted:nd,enqueueSetState:function(n,r,o){var a=Pu.get(n),i=t(a,!1);o=void 0===o?null:o,Xc(a,r,o,i),e(a,i)},enqueueReplaceState:function(n,r,o){var a=Pu.get(n),i=t(a,!1);o=void 0===o?null:o,Gc(a,r,o,i),e(a,i)},enqueueForceUpdate:function(n,r){var o=Pu.get(n),a=t(o,!1);r=void 0===r?null:r,Zc(o,r,a),e(o,a)}};return{adoptClassInstance:l,constructClassInstance:u,mountClassInstance:s,resumeMountClassInstance:c,updateClassInstance:d}},ad=zc.mountChildFibersInPlace,id=zc.reconcileChildFibers,ld=zc.reconcileChildFibersInPlace,ud=zc.cloneChildFibers,sd=yu.beginUpdateQueue,cd=gs.getMaskedContext,dd=gs.getUnmaskedContext,pd=gs.hasContextChanged,fd=gs.pushContextProvider,md=gs.pushTopLevelContextObject,hd=gs.invalidateContextProvider,gd=Hr.IndeterminateComponent,vd=Hr.FunctionalComponent,yd=Hr.ClassComponent,bd=Hr.HostRoot,Cd=Hr.HostComponent,kd=Hr.HostText,Pd=Hr.HostPortal,Ed=Hr.CoroutineComponent,Td=Hr.CoroutineHandlerPhase,wd=Hr.YieldComponent,xd=Hr.Fragment,Nd=au.NoWork,Sd=au.OffscreenPriority,_d=ou.Placement,Od=ou.ContentReset,Rd=ou.Err,Ad=ou.Ref,Md=wu.ReactCurrentOwner,Fd=function(e,t,n,r){function o(e,t,n){t.progressedChild=t.child,t.progressedPriority=n,null!==e&&(e.progressedChild=t.progressedChild,e.progressedPriority=t.progressedPriority)}function a(e){e.progressedFirstDeletion=e.progressedLastDeletion=null}function i(e){e.firstEffect=e.progressedFirstDeletion,e.lastEffect=e.progressedLastDeletion}function l(e,t,n){u(e,t,n,t.pendingWorkPriority)}function u(e,t,n,r){t.memoizedProps=null,null===e?t.child=ad(t,t.child,n,r):e.child===t.child?(a(t),t.child=id(t,t.child,n,r),i(t)):(t.child=ld(t,t.child,n,r),i(t)),o(e,t,r)}function s(e,t){var n=t.pendingProps;if(pd())null===n&&(n=t.memoizedProps);else if(null===n||t.memoizedProps===n)return C(e,t);return l(e,t,n),P(t,n),t.child}function c(e,t){var n=t.ref;null===n||e&&e.ref===n||(t.effectTag|=Ad)} function d(e,t){var n=t.type,r=t.pendingProps,o=t.memoizedProps;if(pd())null===r&&(r=o);else{if(null===r||o===r)return C(e,t);if("function"==typeof n.shouldComponentUpdate&&!n.shouldComponentUpdate(o,r))return P(t,r),C(e,t)}var a,i=dd(t),u=cd(t,i);return a=n(r,u),l(e,t,a),P(t,r),t.child}function p(e,t,n){var r=fd(t),o=void 0;return null===e?t.stateNode?o=D(t,n):(M(t),F(t,n),o=!0):o=I(e,t,n),f(e,t,o,r)}function f(e,t,n,r){if(c(e,t),!n)return C(e,t);var o=t.stateNode;Md.current=t;var a=void 0;return a=o.render(),l(e,t,a),E(t,o.state),P(t,o.props),r&&hd(t),t.child}function m(e,t,n){var r=t.stateNode;r.pendingContext?md(t,r.pendingContext,r.pendingContext!==r.context):r.context&&md(t,r.context,!1),O(t,r.containerInfo);var o=t.updateQueue;if(null!==o){var a=t.memoizedState,i=sd(t,o,null,a,null,n);if(a===i)return C(e,t);return l(e,t,i.element),E(t,i),t.child}return C(e,t)}function h(e,t){_(t);var n=t.pendingProps,r=null!==e?e.memoizedProps:null,o=t.memoizedProps;if(pd())null===n&&(n=o,jn(null!==n,"We should always have pending or current props. This error is likely caused by a bug in React. Please file an issue."));else if(null===n||o===n){if(!N&&S(t.type,o)&&t.pendingWorkPriority!==Sd){for(var a=t.progressedChild;null!==a;)a.pendingWorkPriority=Sd,a=a.sibling;return null}return C(e,t)}var i=n.children;if(x(n)?i=null:r&&x(r)&&(t.effectTag|=Od),c(e,t),!N&&S(t.type,n)&&t.pendingWorkPriority!==Sd){if(t.progressedPriority===Sd&&(t.child=t.progressedChild),u(e,t,i,Sd),P(t,n),t.child=null!==e?e.child:null,null===e)for(var s=t.progressedChild;null!==s;)s.effectTag=_d,s=s.sibling;return null}return l(e,t,i),P(t,n),t.child}function g(e,t){var n=t.pendingProps;return null===n&&(n=t.memoizedProps),P(t,n),null}function v(e,t,n){jn(null===e,"An indeterminate component should never have mounted. This error is likely caused by a bug in React. Please file an issue.");var r,o=t.type,a=t.pendingProps,i=dd(t),u=cd(t,i);if("object"==typeof(r=o(a,u))&&null!==r&&"function"==typeof r.render){t.tag=yd;var s=fd(t);return A(t,r),F(t,n),f(e,t,!0,s)}return t.tag=vd,l(e,t,r),P(t,a),t.child}function y(e,t){var n=t.pendingProps;pd()?null===n&&(n=e&&e.memoizedProps,jn(null!==n,"We should always have pending or current props. This error is likely caused by a bug in React. Please file an issue.")):null!==n&&t.memoizedProps!==n||(n=t.memoizedProps);var r=n.children,o=t.pendingWorkPriority;return t.memoizedProps=null,null===e?t.stateNode=ad(t,t.stateNode,r,o):e.child===t.child?(a(t),t.stateNode=id(t,t.stateNode,r,o),i(t)):(t.stateNode=ld(t,t.stateNode,r,o),i(t)),P(t,n),t.stateNode}function b(e,t){O(t,t.stateNode.containerInfo);var n=t.pendingWorkPriority,r=t.pendingProps;if(pd())null===r&&(r=e&&e.memoizedProps,jn(null!=r,"We should always have pending or current props. This error is likely caused by a bug in React. Please file an issue."));else if(null===r||t.memoizedProps===r)return C(e,t);return null===e?(t.child=ld(t,t.child,r,n),P(t,r),o(e,t,n)):(l(e,t,r),P(t,r)),t.child}function C(e,t){var n=t.pendingWorkPriority;return e&&t.child===e.child&&a(t),ud(e,t),o(e,t,n),t.child}function k(e,t){switch(t.tag){case yd:fd(t);break;case Pd:O(t,t.stateNode.containerInfo)}return null}function P(e,t){e.memoizedProps=t,e.pendingProps=null}function E(e,t){e.memoizedState=t}function T(e,t,n){if(t.pendingWorkPriority===Nd||t.pendingWorkPriority>n)return k(e,t);switch(t.firstEffect=null,t.lastEffect=null,t.progressedPriority===n&&(t.child=t.progressedChild),t.tag){case gd:return v(e,t,n);case vd:return d(e,t);case yd:return p(e,t,n);case bd:return m(e,t,n);case Cd:return h(e,t);case kd:return g(e,t);case Td:t.tag=Ed;case Ed:return y(e,t);case wd:return null;case Pd:return b(e,t);case xd:return s(e,t);default:jn(!1,"Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.")}}function w(e,t,n){if(jn(t.tag===yd||t.tag===bd,"Invalid type of work. This error is likely caused by a bug in React. Please file an issue."),t.effectTag|=Rd,t.pendingWorkPriority===Nd||t.pendingWorkPriority>n)return k(e,t);t.firstEffect=null,t.lastEffect=null;if(l(e,t,null),t.tag===yd){var r=t.stateNode;t.memoizedProps=r.props,t.memoizedState=r.state,t.pendingProps=null}return t.child}var x=e.shouldSetTextContent,N=e.useSyncScheduling,S=e.shouldDeprioritizeSubtree,_=t.pushHostContext,O=t.pushHostContainer,R=od(n,r,P,E),A=R.adoptClassInstance,M=R.constructClassInstance,F=R.mountClassInstance,D=R.resumeMountClassInstance,I=R.updateClassInstance;return{beginWork:T,beginFailedWork:w}},Dd=zc.reconcileChildFibers,Id=gs.popContextProvider,Ud=Hr.IndeterminateComponent,Ld=Hr.FunctionalComponent,Hd=Hr.ClassComponent,jd=Hr.HostRoot,Wd=Hr.HostComponent,Vd=Hr.HostText,Bd=Hr.HostPortal,zd=Hr.CoroutineComponent,Kd=Hr.CoroutineHandlerPhase,Yd=Hr.YieldComponent,qd=Hr.Fragment,Qd=ou.Ref,$d=ou.Update,Xd=function(e,t){function n(e,t,n){t.progressedChild=t.child,t.progressedPriority=n,null!==e&&(e.progressedChild=t.progressedChild,e.progressedPriority=t.progressedPriority)}function r(e){e.effectTag|=$d}function o(e){e.effectTag|=Qd}function a(e,t){var n=t.stateNode;for(n&&(n.return=t);null!==n;){if(n.tag===Wd||n.tag===Vd||n.tag===Bd)jn(!1,"A coroutine cannot have host component children.");else if(n.tag===Yd)e.push(n.type);else if(null!==n.child){n.child.return=n,n=n.child;continue}for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}}function i(e,t){var r=t.memoizedProps;jn(r,"Should be resolved by now. This error is likely caused by a bug in React. Please file an issue."),t.tag=Kd;var o=[];a(o,t);var i=r.handler,l=r.props,u=i(l,o),s=null!==e?e.child:null,c=t.pendingWorkPriority;return t.child=Dd(t,s,u,c),n(e,t,c),t.child}function l(e,t){for(var n=t.child;null!==n;){if(n.tag===Wd||n.tag===Vd)d(e,n.stateNode);else if(n.tag===Bd);else if(null!==n.child){n=n.child;continue}if(n===t)return;for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return}n=n.sibling}}function u(e,t){switch(t.tag){case Ld:return null;case Hd:return Id(t),null;case jd:var n=t.stateNode;return n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),null;case Wd:h(t);var a=m(),u=t.type,d=t.memoizedProps;if(null!==e&&null!=t.stateNode){var y=e.memoizedProps,b=t.stateNode,C=g(),k=f(b,u,y,d,a,C);t.updateQueue=k,k&&r(t),e.ref!==t.ref&&o(t)}else{if(!d)return jn(null!==t.stateNode,"We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."),null;var P=g(),E=s(u,d,a,P,t);l(E,t),p(E,u,d,a)&&r(t),t.stateNode=E,null!==t.ref&&o(t)}return null;case Vd:var T=t.memoizedProps;if(e&&null!=t.stateNode){e.memoizedProps!==T&&r(t)}else{if("string"!=typeof T)return jn(null!==t.stateNode,"We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."),null;var w=m(),x=g(),N=c(T,w,x,t);t.stateNode=N}return null;case zd:return i(e,t);case Kd:return t.tag=zd,null;case Yd:case qd:return null;case Bd:return r(t),v(t),null;case Ud:jn(!1,"An indeterminate component should have become determinate before completing. This error is likely caused by a bug in React. Please file an issue.");default:jn(!1,"Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.")}}var s=e.createInstance,c=e.createTextInstance,d=e.appendInitialChild,p=e.finalizeInitialChildren,f=e.prepareUpdate,m=t.getRootHostContainer,h=t.popHostContext,g=t.getHostContext,v=t.popHostContainer;return{completeWork:u}},Gd=null,Zd=null,Jd=null,ep=null;if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&__REACT_DEVTOOLS_GLOBAL_HOOK__.supportsFiber){var tp=__REACT_DEVTOOLS_GLOBAL_HOOK__.inject,np=__REACT_DEVTOOLS_GLOBAL_HOOK__.onCommitFiberRoot,rp=__REACT_DEVTOOLS_GLOBAL_HOOK__.onCommitFiberUnmount;Zd=function(e){Gd=tp(e)},Jd=function(e){if(null!=Gd)try{np(Gd,e)}catch(e){}},ep=function(e){if(null!=Gd)try{rp(Gd,e)}catch(e){}}}var op=Zd,ap=Jd,ip=ep,lp={injectInternals:op,onCommitRoot:ap,onCommitUnmount:ip},up=Hr.ClassComponent,sp=Hr.HostRoot,cp=Hr.HostComponent,dp=Hr.HostText,pp=Hr.HostPortal,fp=Hr.CoroutineComponent,mp=yu.commitCallbacks,hp=lp.onCommitUnmount,gp=ou.Placement,vp=ou.Update,yp=ou.Callback,bp=ou.ContentReset,Cp=function(e,t){function n(e,n){try{n.componentWillUnmount()}catch(n){t(e,n)}}function r(e){var n=e.ref;if(null!==n){try{n(null)}catch(n){t(e,n)}}}function o(e){for(var t=e.return;null!==t;){switch(t.tag){case cp:return t.stateNode;case sp:case pp:return t.stateNode.containerInfo}t=t.return}jn(!1,"Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.")}function a(e){for(var t=e.return;null!==t;){if(i(t))return t;t=t.return}jn(!1,"Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.")}function i(e){return e.tag===cp||e.tag===sp||e.tag===pp}function l(e){var t=e;e:for(;;){for(;null===t.sibling;){if(null===t.return||i(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==cp&&t.tag!==dp;){if(t.effectTag&gp)continue e;if(null===t.child||t.tag===pp)continue e;t.child.return=t,t=t.child}if(!(t.effectTag&gp))return t.stateNode}}function u(e){var t=a(e),n=void 0;switch(t.tag){case cp:n=t.stateNode;break;case sp:case pp:n=t.stateNode.containerInfo;break;default:jn(!1,"Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.")}t.effectTag&bp&&(b(n),t.effectTag&=~bp);for(var r=l(e),o=e;;){if(o.tag===cp||o.tag===dp)r?P(n,o.stateNode,r):k(n,o.stateNode);else if(o.tag===pp);else if(null!==o.child){o.child.return=o,o=o.child;continue}if(o===e)return;for(;null===o.sibling;){if(null===o.return||o.return===e)return;o=o.return}o.sibling.return=o.return,o=o.sibling}}function s(e){for(var t=e;;)if(p(t),null===t.child||t.tag===pp){if(t===e)return;for(;null===t.sibling;){if(null===t.return||t.return===e)return;t=t.return}t.sibling.return=t.return,t=t.sibling}else t.child.return=t,t=t.child}function c(e,t){for(var n=t;;){if(n.tag===cp||n.tag===dp)s(n),E(e,n.stateNode);else if(n.tag===pp){if(e=n.stateNode.containerInfo,null!==n.child){n.child.return=n,n=n.child;continue}}else if(p(n),null!==n.child){n.child.return=n,n=n.child;continue}if(n===t)return;for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return,n.tag===pp&&(e=o(n))}n.sibling.return=n.return,n=n.sibling}}function d(e){c(o(e),e),e.return=null,e.child=null,e.alternate&&(e.alternate.child=null,e.alternate.return=null)}function p(e){switch("function"==typeof hp&&hp(e),e.tag){case up:r(e);var t=e.stateNode;return void("function"==typeof t.componentWillUnmount&&n(e,t));case cp:return void r(e);case fp:return void s(e.stateNode);case pp:return void c(o(e),e)}}function f(e,t){switch(t.tag){case up:return;case cp:var n=t.stateNode;if(null!=n&&null!==e){var r=t.memoizedProps,o=e.memoizedProps,a=t.type,i=t.updateQueue;t.updateQueue=null,null!==i&&y(n,i,a,o,r,t)}return;case dp:jn(null!==t.stateNode&&null!==e,"This should only be done during updates. This error is likely caused by a bug in React. Please file an issue.");var l=t.stateNode,u=t.memoizedProps,s=e.memoizedProps;return void C(l,s,u);case sp:case pp:return;default:jn(!1,"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.")}}function m(e,t){switch(t.tag){case up:var n=t.stateNode;if(t.effectTag&vp)if(null===e)n.componentDidMount();else{var r=e.memoizedProps,o=e.memoizedState;n.componentDidUpdate(r,o)}return void(t.effectTag&yp&&null!==t.updateQueue&&mp(t,t.updateQueue,n));case sp:var a=t.updateQueue;if(null!==a){var i=t.child&&t.child.stateNode;mp(t,a,i)}return;case cp:var l=t.stateNode;if(null===e&&t.effectTag&vp){var u=t.type,s=t.memoizedProps;v(l,u,s,t)}return;case dp:case pp:return;default:jn(!1,"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.")}}function h(e){var t=e.ref;if(null!==t){t(T(e.stateNode))}}function g(e){var t=e.ref;null!==t&&t(null)}var v=e.commitMount,y=e.commitUpdate,b=e.resetTextContent,C=e.commitTextUpdate,k=e.appendChild,P=e.insertBefore,E=e.removeChild,T=e.getPublicInstance;return{commitPlacement:u,commitDeletion:d,commitWork:f,commitLifeCycles:m,commitAttachRef:h,commitDetachRef:g}},kp=Yu.createCursor,Pp=Yu.pop,Ep=Yu.push,Tp={},wp=function(e){function t(e){return jn(e!==Tp,"Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."),e}function n(){return t(f.current)}function r(e,t){Ep(f,t,e);var n=c(t);Ep(p,e,e),Ep(d,n,e)}function o(e){Pp(d,e),Pp(p,e),Pp(f,e)}function a(){return t(d.current)}function i(e){var n=t(f.current),r=t(d.current),o=s(r,e.type,n);r!==o&&(Ep(p,e,e),Ep(d,o,e))}function l(e){p.current===e&&(Pp(d,e),Pp(p,e))}function u(){d.current=Tp,f.current=Tp}var s=e.getChildHostContext,c=e.getRootHostContext,d=kp(Tp),p=kp(Tp),f=kp(Tp);return{getHostContext:a,getRootHostContainer:n,popHostContainer:o,popHostContext:l,pushHostContainer:r,pushHostContext:i,resetHostContainer:u}},xp=gs.popContextProvider,Np=Yu.reset,Sp=Xs.getStackAddendumByWorkInProgressFiber,_p=tc.logCapturedError,Op=wu.ReactCurrentOwner,Rp=Vs.cloneFiber,Ap=lp.onCommitRoot,Mp=au.NoWork,Fp=au.SynchronousPriority,Dp=au.TaskPriority,Ip=au.AnimationPriority,Up=au.HighPriority,Lp=au.LowPriority,Hp=au.OffscreenPriority,jp=vs.AsyncUpdates,Wp=ou.NoEffect,Vp=ou.Placement,Bp=ou.Update,zp=ou.PlacementAndUpdate,Kp=ou.Deletion,Yp=ou.ContentReset,qp=ou.Callback,Qp=ou.Err,$p=ou.Ref,Xp=Hr.HostRoot,Gp=Hr.HostComponent,Zp=Hr.HostPortal,Jp=Hr.ClassComponent,ef=yu.getPendingPriority,tf=gs,nf=tf.resetContext,rf=1,of=function(e){function t(e){se||(se=!0,q(e))}function n(e){ce||(ce=!0,Q(e))}function r(){Np(),nf(),F()}function o(){for(;null!==le&&le.current.pendingWorkPriority===Mp;){le.isScheduled=!1;var e=le.nextScheduledRoot;if(le.nextScheduledRoot=null,le===ue)return le=null,ue=null,oe=Mp,null;le=e}for(var t=le,n=null,o=Mp;null!==t;)t.current.pendingWorkPriority!==Mp&&(o===Mp||o>t.current.pendingWorkPriority)&&(o=t.current.pendingWorkPriority,n=t),t=t.nextScheduledRoot;return null!==n?(oe=o,Z=oe,r(),Rp(n.current,o)):(oe=Mp,null)}function a(){for(;null!==ae;){var t=ae.effectTag;if(t&Yp&&e.resetTextContent(ae.stateNode),t&$p){var n=ae.alternate;null!==n&&Y(n)}switch(t&~(qp|Qp|Yp|$p)){case Vp:W(ae),ae.effectTag&=~Vp;break;case zp:W(ae),ae.effectTag&=~Vp;var r=ae.alternate;B(r,ae);break;case Bp:var o=ae.alternate;B(o,ae);break;case Kp:ve=!0,V(ae),ve=!1}ae=ae.nextEffect}}function i(){for(;null!==ae;){var e=ae.effectTag;if(e&(Bp|qp)){var t=ae.alternate;z(t,ae)}e&$p&&K(ae),e&Qp&&C(ae);var n=ae.nextEffect;ae.nextEffect=null,ae=n}}function l(e){ge=!0,ie=null;var t=e.stateNode;jn(t.current!==e,"Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue."),Op.current=null;var n=Z;Z=Dp;var r=void 0;e.effectTag!==Wp?null!==e.lastEffect?(e.lastEffect.nextEffect=e,r=e.firstEffect):r=e:r=e.firstEffect;var o=X();for(ae=r;null!==ae;){var l=null;try{a(e)}catch(e){l=e}null!==l&&(jn(null!==ae,"Should have next effect. This error is likely caused by a bug in React. Please file an issue."),v(ae,l),null!==ae&&(ae=ae.nextEffect))}for(G(o),t.current=e,ae=r;null!==ae;){var u=null;try{i(e)}catch(e){u=e}null!==u&&(jn(null!==ae,"Should have next effect. This error is likely caused by a bug in React. Please file an issue."),v(ae,u),null!==ae&&(ae=ae.nextEffect))}ge=!1,"function"==typeof Ap&&Ap(e.stateNode),fe&&(fe.forEach(w),fe=null),Z=n}function u(e){var t=Mp,n=e.updateQueue,r=e.tag;null===n||r!==Jp&&r!==Xp||(t=ef(n));for(var o=e.progressedChild;null!==o;)o.pendingWorkPriority!==Mp&&(t===Mp||t>o.pendingWorkPriority)&&(t=o.pendingWorkPriority),o=o.sibling;e.pendingWorkPriority=t}function s(e){for(;;){var t=e.alternate,n=H(t,e),r=e.return,o=e.sibling;if(u(e),null!==n)return n;if(null!==r&&(null===r.firstEffect&&(r.firstEffect=e.firstEffect),null!==e.lastEffect&&(null!==r.lastEffect&&(r.lastEffect.nextEffect=e.firstEffect),r.lastEffect=e.lastEffect),e.effectTag!==Wp&&(null!==r.lastEffect?r.lastEffect.nextEffect=e:r.firstEffect=e,r.lastEffect=e)),null!==o)return o;if(null===r)return oe<Up?l(e):ie=e,null;e=r}return null}function c(e){var t=e.alternate,n=I(t,e,oe);return null===n&&(n=s(e)),Op.current=null,n}function d(e){var t=e.alternate,n=U(t,e,oe);return null===n&&(n=s(e)),Op.current=null,n}function p(e){ce=!1,g(Hp,e)}function f(){se=!1,g(Ip,null)}function m(){for(null===re&&(re=o());null!==de&&de.size&&null!==re&&oe!==Mp&&oe<=Dp;)null===(re=y(re)?d(re):c(re))&&(re=o())}function h(e,t){m(),null===re&&(re=o());var n=void 0;if(eo.logTopLevelRenders&&null!==re&&re.tag===Xp&&null!==re.child){n="React update: "+(co(re.child)||""),console.time(n)}if(null!==t&&e>Dp)for(;null!==re&&!te;)t.timeRemaining()>rf?null===(re=c(re))&&null!==ie&&(t.timeRemaining()>rf?(l(ie),re=o(),m()):te=!0):te=!0;else for(;null!==re&&oe!==Mp&&oe<=e;)null===(re=c(re))&&(re=o(),m());n&&console.timeEnd(n)}function g(e,r){jn(!ee,"performWork was called recursively. This error is likely caused by a bug in React. Please file an issue."),ee=!0;for(var o=!!r;e!==Mp&&!he;){jn(null!==r||e<Up,"Cannot perform deferred work without a deadline. This error is likely caused by a bug in React. Please file an issue."),null===ie||te||l(ie),J=Z;var a=null;try{h(e,r)}catch(e){a=e}if(Z=J,null!==a){var i=re;if(null!==i){var u=v(i,a);if(null!==u){var c=u;U(c.alternate,c,e),k(i,c),re=s(c)}continue}null===he&&(he=a)}if(e=Mp,oe===Mp||!o||te)switch(oe){case Fp:case Dp:e=oe;break;case Ip:t(f),n(p);break;case Up:case Lp:case Hp:n(p)}else e=oe}var d=he||me;if(ee=!1,te=!1,he=null,me=null,de=null,pe=null,null!==d)throw d}function v(e,t){Op.current=null,re=null;var n=null,r=!1,o=!1,a=null;if(e.tag===Xp)n=e,b(e)&&(he=t);else for(var i=e.return;null!==i&&null===n;){if(i.tag===Jp){var l=i.stateNode;"function"==typeof l.unstable_handleError&&(r=!0,a=co(i),n=i,o=!0)}else i.tag===Xp&&(n=i);if(b(i)){if(ve)return null;if(null!==fe&&(fe.has(i)||null!==i.alternate&&fe.has(i.alternate)))return null;n=null,o=!1}i=i.return}if(null!==n){null===pe&&(pe=new Set),pe.add(n);var u=Sp(e),s=co(e);return null===de&&(de=new Map),de.set(n,{componentName:s,componentStack:u,error:t,errorBoundary:r?n.stateNode:null,errorBoundaryFound:r,errorBoundaryName:a,willRetry:o}),ge?(null===fe&&(fe=new Set),fe.add(n)):w(n),n}return null===me&&(me=t),null}function y(e){return null!==de&&(de.has(e)||null!==e.alternate&&de.has(e.alternate))}function b(e){return null!==pe&&(pe.has(e)||null!==e.alternate&&pe.has(e.alternate))}function C(e){var t=void 0;null!==de&&(t=de.get(e),de.delete(e),null==t&&null!==e.alternate&&(e=e.alternate,t=de.get(e),de.delete(e))),jn(null!=t,"No error for given unit of work. This error is likely caused by a bug in React. Please file an issue.");var n=t.error;try{_p(t)}catch(e){console.error(e)}switch(e.tag){case Jp:var r=e.stateNode,o={componentStack:t.componentStack};return void r.unstable_handleError(n,o);case Xp:return void(null===me&&(me=n));default:jn(!1,"Invalid type of work. This error is likely caused by a bug in React. Please file an issue.")}}function k(e,t){for(var n=e;null!==n&&n!==t&&n.alternate!==t;){switch(n.tag){case Jp:xp(n);break;case Gp:M(n);break;case Xp:case Zp:A(n)}n=n.return}}function P(e,t){t!==Mp&&(e.isScheduled||(e.isScheduled=!0,ue?(ue.nextScheduledRoot=e,ue=e):(le=e,ue=e)))}function E(e,r){r<=oe&&(re=null);for(var o=e,a=!0;null!==o&&a;){if(a=!1,(o.pendingWorkPriority===Mp||o.pendingWorkPriority>r)&&(a=!0,o.pendingWorkPriority=r),null!==o.alternate&&(o.alternate.pendingWorkPriority===Mp||o.alternate.pendingWorkPriority>r)&&(a=!0,o.alternate.pendingWorkPriority=r),null===o.return){if(o.tag!==Xp)return;switch(P(o.stateNode,r),r){case Fp:return void g(Fp,null);case Dp:return;case Ip:return void t(f);case Up:case Lp:case Hp:return void n(p)}}o=o.return}}function T(e,t){var n=Z;return n===Mp&&(n=!$||e.internalContextTag&jp||t?Lp:Fp),n===Fp&&(ee||ne)?Dp:n}function w(e){E(e,Dp)}function x(e,t){var n=Z;Z=e;try{t()}finally{Z=n}}function N(e,t){var n=ne;ne=!0;try{return e(t)}finally{ne=n,ee||ne||g(Dp,null)}}function S(e){var t=ne;ne=!1;try{return e()}finally{ne=t}}function _(e){var t=Z;Z=Fp;try{return e()}finally{Z=t}}function O(e){var t=Z;Z=Lp;try{return e()}finally{Z=t}}var R=wp(e),A=R.popHostContainer,M=R.popHostContext,F=R.resetHostContainer,D=Fd(e,R,E,T),I=D.beginWork,U=D.beginFailedWork,L=Xd(e,R),H=L.completeWork,j=Cp(e,v),W=j.commitPlacement,V=j.commitDeletion,B=j.commitWork,z=j.commitLifeCycles,K=j.commitAttachRef,Y=j.commitDetachRef,q=e.scheduleAnimationCallback,Q=e.scheduleDeferredCallback,$=e.useSyncScheduling,X=e.prepareForCommit,G=e.resetAfterCommit,Z=Mp,J=Mp,ee=!1,te=!1,ne=!1,re=null,oe=Mp,ae=null,ie=null,le=null,ue=null,se=!1,ce=!1,de=null,pe=null,fe=null,me=null,he=null,ge=!1,ve=!1;return{scheduleUpdate:E,getPriorityContext:T,performWithPriority:x,batchedUpdates:N,unbatchedUpdates:S,syncUpdates:_,deferredUpdates:O}},af=function(e){jn(!1,"Missing injection for fiber getContextForSubtree")};Sn._injectFiber=function(e){af=e};var lf=Sn,uf=yu.addTopLevelUpdate,sf=gs.findCurrentUnmaskedContext,cf=gs.isContextProvider,df=gs.processChildContext,pf=Ks.createFiberRoot,ff=Lu.findCurrentHostFiber;lf._injectFiber(function(e){var t=sf(e);return cf(e)?df(e,t,!1):t});var mf=Wr.ELEMENT_NODE,hf=function(e){jn(!1,"Missing injection for fiber findDOMNode")},gf=function(e){jn(!1,"Missing injection for stack findDOMNode")},vf=function(e){if(null==e)return null;if(e.nodeType===mf)return e;var t=Pu.get(e);if(t)return"number"==typeof t.tag?hf(t):gf(t);"function"==typeof e.render?jn(!1,"Unable to find node on an unmounted component."):jn(!1,"Element appears to be neither ReactComponent nor DOMNode. Keys: %s",Object.keys(e))};vf._injectFiber=function(e){hf=e},vf._injectStack=function(e){gf=e};var yf=vf,bf=e.isValidElement,Cf=lp.injectInternals,kf=Wr.ELEMENT_NODE,Pf=Wr.DOCUMENT_NODE,Ef=Wr.DOCUMENT_FRAGMENT_NODE,Tf=ma.createElement,wf=ma.getChildNamespace,xf=ma.setInitialProperties,Nf=ma.diffProperties,Sf=ma.updateProperties,_f=Zr.precacheFiberNode,Of=Zr.updateFiberProps;ru.inject(),Ar.injection.injectFiberControlledHostComponent(ma),yf._injectFiber(function(e){return Mf.findHostInstance(e)});var Rf=null,Af=null,Mf=function(e){function t(e,t,n){var a=eo.enableAsyncSubtreeAPI&&null!=t&&null!=t.type&&!0===t.type.unstable_asyncUpdates,i=o(e,a),l={element:t};n=void 0===n?null:n,uf(e,l,n,i),r(e,i)}var n=of(e),r=n.scheduleUpdate,o=n.getPriorityContext,a=n.performWithPriority,i=n.batchedUpdates,l=n.unbatchedUpdates,u=n.syncUpdates,s=n.deferredUpdates;return{createContainer:function(e){return pf(e)},updateContainer:function(e,n,r,o){var a=n.current,i=lf(r);null===n.context?n.context=i:n.pendingContext=i,t(a,e,o)},performWithPriority:a,batchedUpdates:i,unbatchedUpdates:l,syncUpdates:u,deferredUpdates:s,getPublicRootInstance:function(e){var t=e.current;return t.child?t.child.stateNode:null},findHostInstance:function(e){var t=ff(e);return null===t?null:t.stateNode}}}({getRootHostContext:function(e){var t=e.namespaceURI||null,n=e.tagName;return wf(t,n)},getChildHostContext:function(e,t){return wf(e,t)},getPublicInstance:function(e){return e},prepareForCommit:function(){Rf=xr.isEnabled(),Af=vl.getSelectionInformation(),xr.setEnabled(!1)},resetAfterCommit:function(){vl.restoreSelection(Af),Af=null,xr.setEnabled(Rf),Rf=null},createInstance:function(e,t,n,r,o){var a=void 0;a=r;var i=Tf(e,t,n,a);return _f(o,i),Of(i,t),i},appendInitialChild:function(e,t){e.appendChild(t)},finalizeInitialChildren:function(e,t,n,r){return xf(e,t,n,r),Rn(t,n)},prepareUpdate:function(e,t,n,r,o,a){return Nf(e,t,n,r,o)},commitMount:function(e,t,n,r){e.focus()},commitUpdate:function(e,t,n,r,o,a){Of(e,o),Sf(e,t,n,r,o)},shouldSetTextContent:function(e){return"string"==typeof e.children||"number"==typeof e.children||"object"==typeof e.dangerouslySetInnerHTML&&null!==e.dangerouslySetInnerHTML&&"string"==typeof e.dangerouslySetInnerHTML.__html},resetTextContent:function(e){e.textContent=""},shouldDeprioritizeSubtree:function(e,t){return!!t.hidden},createTextInstance:function(e,t,n,r){var o=document.createTextNode(e);return _f(r,o),o},commitTextUpdate:function(e,t,n){e.nodeValue=n},appendChild:function(e,t){e.appendChild(t)},insertBefore:function(e,t,n){e.insertBefore(t,n)},removeChild:function(e,t){e.removeChild(t)},scheduleAnimationCallback:Oa.rAF,scheduleDeferredCallback:Oa.rIC,useSyncScheduling:!no.fiberAsyncScheduling});ki.injection.injectFiberBatchedUpdates(Mf.batchedUpdates);var Ff=!1,Df={render:function(e,t,n){return On(t),eo.disableNewFiberFeatures&&(bf(e)||("string"==typeof e?jn(!1,"ReactDOM.render(): Invalid component element. Instead of passing a string like 'div', pass React.createElement('div') or <div />."):"function"==typeof e?jn(!1,"ReactDOM.render(): Invalid component element. Instead of passing a class like Foo, pass React.createElement(Foo) or <Foo />."):null!=e&&void 0!==e.props?jn(!1,"ReactDOM.render(): Invalid component element. This may be caused by unintentionally loading two independent copies of React."):jn(!1,"ReactDOM.render(): Invalid component element."))),Mn(null,e,t,n)},unstable_renderSubtreeIntoContainer:function(e,t,n,r){return null!=e&&Pu.has(e)||Fn("38"),Mn(e,t,n,r)},unmountComponentAtNode:function(e){if(_n(e)||Fn("40"),An(),e._reactRootContainer)return Mf.unbatchedUpdates(function(){return Mn(null,null,e,function(){e._reactRootContainer=null})})},findDOMNode:yf,unstable_createPortal:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return hc.createPortal(e,t,null,n)},unstable_batchedUpdates:ki.batchedUpdates,unstable_deferredUpdates:Mf.deferredUpdates,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{EventPluginHub:sr,EventPluginRegistry:zn,EventPropagators:Ua,ReactControlledComponent:Ar,ReactDOMComponentTree:Zr,ReactBrowserEventEmitter:xr}};return"function"==typeof Cf&&Cf({findFiberByHostInstance:Zr.getClosestInstanceFromNode,findHostInstanceByFiber:Mf.findHostInstance}),Df});
packages/material-ui-icons/src/Colorize.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Colorize = props => <SvgIcon {...props}> <path d="M20.71 5.63l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-3.12 3.12-1.93-1.91-1.41 1.41 1.42 1.42L3 16.25V21h4.75l8.92-8.92 1.42 1.42 1.41-1.41-1.92-1.92 3.12-3.12c.4-.4.4-1.03.01-1.42zM6.92 19L5 17.08l8.06-8.06 1.92 1.92L6.92 19z" /> </SvgIcon>; Colorize = pure(Colorize); Colorize.muiName = 'SvgIcon'; export default Colorize;
SprinterV1/scripts/jquery-1.11.0.min.js
jasimmahamoodkm/NexGen
/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f }}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={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:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b) },a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.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(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,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":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
modules/components/topic.js
yuanziyuer/yuanzi-share
/** * Created by natefang on 1/14/16. */ import React, { Component } from 'react'; import { Link } from 'react-router'; import fetch from 'isomorphic-fetch'; import moment from 'moment'; import './style/topic.css'; import $ from 'jquery' class Topic extends Component { constructor(props) { super(props); this.state = { topic: { strategies:[], owner:{ nickname :'' }, cover: '', score: 0, tryCount :0, description:'' } }; } componentDidMount() { $.get('http://www.iyuanzi.net/topics/'+ this.props.params.id + '?version=v2', function(result) { this.setState({ topic: result }); var title = result.title || '元子育儿'; var image = result.cover || 'http://share.iyuanzi.net/favicon.ico'; var description = title; const oMeta = document.createElement('meta'); oMeta.setAttribute('property', 'og:title'); oMeta.setAttribute('content', title); document.getElementsByTagName('head')[0].appendChild(oMeta); const oMetaimage = document.createElement('meta'); oMetaimage.setAttribute('property', 'og:image'); oMetaimage.setAttribute('content', image); document.getElementsByTagName('head')[0].appendChild(oMetaimage); const oMetadesc = document.createElement('meta'); oMetadesc.setAttribute('property', 'og:description'); oMetadesc.setAttribute('content', description); document.getElementsByTagName('head')[0].appendChild(oMetadesc); }.bind(this)); } render() { return ( <div className="content"> { <Topics topic = {this.state.topic}/> } </div> ); } } class Topics extends Component { render () { return ( <div className="topics"><img className="coverImg" src={this.props.topic.cover}/> <div className="topicTitle">{this.props.topic.title}</div> <div className="authorWrap"><span> 来自: </span><span className="author">{this.props.topic.owner.nickname}</span></div> <div className="descrption">{this.props.topic.subTitle}</div> <StrategiesCollections strategies={this.props.topic.strategies}/> </div> ); } } class StrategiesCollections extends Component { render () { return ( <div> { this.props.strategies.length ? <div> <div className="sectionTitle"> <span className="sectionName">妙招 </span> <span>({this.props.strategies.length})</span> </div> <ul className="strategyiesCollection"> { this.props.strategies.map(function(item) { return (<StrategyItem key={item.strategyId} {...item}/>); }) } </ul> </div> : null } </div> ); } } class StrategyItem extends Component { render () { return ( <Link to={'/strategies/'+this.props.strategyId+'/view'} > <li className="strategyItem"> <div className="strategyItemWrap"><img src={this.props.cover} alt="" className="strategyCover"/> <div className="title">{this.props.title}</div> <div className="authorWrap"><span>by </span><span className="author">{this.props.owner.nickname}</span></div> <div className="separator"></div> <div className="score">{ this.props.tryCount+'人参与 / ' + this.props.score+'分' } </div> </div></li> </Link> ); }; } export default Topic;
app/javascript/mastodon/features/compose/components/search.js
tri-star/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { searchEnabled } from '../../../initial_state'; import Icon from 'mastodon/components/icon'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class SearchPopout extends React.PureComponent { static propTypes = { style: PropTypes.object, }; render () { const { style } = this.props; const extraInformation = searchEnabled ? <FormattedMessage id='search_popout.tips.full_text' defaultMessage='Simple text returns statuses you have written, favourited, boosted, or have been mentioned in, as well as matching usernames, display names, and hashtags.' /> : <FormattedMessage id='search_popout.tips.text' defaultMessage='Simple text returns matching display names, usernames and hashtags' />; return ( <div style={{ ...style, position: 'absolute', width: 285, zIndex: 2 }}> <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( <div className='search-popout' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}> <h4><FormattedMessage id='search_popout.search_format' defaultMessage='Advanced search format' /></h4> <ul> <li><em>#example</em> <FormattedMessage id='search_popout.tips.hashtag' defaultMessage='hashtag' /></li> <li><em>@username@domain</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li> <li><em>URL</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li> <li><em>URL</em> <FormattedMessage id='search_popout.tips.status' defaultMessage='status' /></li> </ul> {extraInformation} </div> )} </Motion> </div> ); } } export default @injectIntl class Search extends React.PureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { value: PropTypes.string.isRequired, submitted: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, onShow: PropTypes.func.isRequired, openInRoute: PropTypes.bool, intl: PropTypes.object.isRequired, singleColumn: PropTypes.bool, }; state = { expanded: false, }; setRef = c => { this.searchForm = c; } handleChange = (e) => { this.props.onChange(e.target.value); } handleClear = (e) => { e.preventDefault(); if (this.props.value.length > 0 || this.props.submitted) { this.props.onClear(); } } handleKeyUp = (e) => { if (e.key === 'Enter') { e.preventDefault(); this.props.onSubmit(); if (this.props.openInRoute) { this.context.router.history.push('/search'); } } else if (e.key === 'Escape') { document.querySelector('.ui').parentElement.focus(); } } handleFocus = () => { this.setState({ expanded: true }); this.props.onShow(); if (this.searchForm && !this.props.singleColumn) { const { left, right } = this.searchForm.getBoundingClientRect(); if (left < 0 || right > (window.innerWidth || document.documentElement.clientWidth)) { this.searchForm.scrollIntoView(); } } } handleBlur = () => { this.setState({ expanded: false }); } render () { const { intl, value, submitted } = this.props; const { expanded } = this.state; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.placeholder)}</span> <input ref={this.setRef} className='search__input' type='text' placeholder={intl.formatMessage(messages.placeholder)} value={value} onChange={this.handleChange} onKeyUp={this.handleKeyUp} onFocus={this.handleFocus} onBlur={this.handleBlur} /> </label> <div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}> <Icon id='search' className={hasValue ? '' : 'active'} /> <Icon id='times-circle' className={hasValue ? 'active' : ''} aria-label={intl.formatMessage(messages.placeholder)} /> </div> <Overlay show={expanded && !hasValue} placement='bottom' target={this}> <SearchPopout /> </Overlay> </div> ); } }
src/index.js
renaudtertrais/resume
import React from 'react'; import ReactDOM from 'react-dom'; import './style/index.scss'; import 'font-awesome/css/font-awesome.css'; import * as serviceWorker from './serviceWorker'; import data from './data'; import Resume from './components/Resume'; console.log(data); ReactDOM.render(<Resume {...data} />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
ajax/libs/ember-data.js/1.0.0-beta.9/ember-data.js
jdanyow/cdnjs
(function(global){ var define, requireModule, require, requirejs; (function() { var registry = {}, seen = {}, state = {}; var FAILED = false; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; function reify(deps, name, seen) { var length = deps.length; var reified = new Array(length); var dep; var exports; for (var i = 0, l = length; i < l; i++) { dep = deps[i]; if (dep === 'exports') { exports = reified[i] = seen; } else { reified[i] = require(resolve(dep, name)); } } return { deps: reified, exports: exports }; } requirejs = require = requireModule = function(name) { if (state[name] !== FAILED && seen.hasOwnProperty(name)) { return seen[name]; } if (!registry[name]) { throw new Error('Could not find module ' + name); } var mod = registry[name]; var reified; var module; var loaded = false; seen[name] = { }; // placeholder for run-time cycles try { reified = reify(mod.deps, name, seen[name]); module = mod.callback.apply(this, reified.deps); loaded = true; } finally { if (!loaded) { state[name] = FAILED; } } return reified.exports ? seen[name] : (seen[name] = module); }; function resolve(child, name) { if (child.charAt(0) !== '.') { return child; } var parts = child.split('/'); var nameParts = name.split('/'); var parentBase; if (nameParts.length === 1) { parentBase = nameParts; } else { parentBase = nameParts.slice(0, -1); } for (var i = 0, l = parts.length; i < l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join('/'); } requirejs.entries = requirejs._eak_seen = registry; requirejs.clear = function(){ requirejs.entries = requirejs._eak_seen = registry = {}; seen = state = {}; }; })(); define("activemodel-adapter", ["activemodel-adapter/system","exports"], function(__dependency1__, __exports__) { "use strict"; var ActiveModelAdapter = __dependency1__.ActiveModelAdapter; var ActiveModelSerializer = __dependency1__.ActiveModelSerializer; __exports__.ActiveModelAdapter = ActiveModelAdapter; __exports__.ActiveModelSerializer = ActiveModelSerializer; }); define("activemodel-adapter/setup-container", ["ember-data/system/container_proxy","activemodel-adapter/system/active_model_serializer","activemodel-adapter/system/active_model_adapter","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var ContainerProxy = __dependency1__["default"]; var ActiveModelSerializer = __dependency2__["default"]; var ActiveModelAdapter = __dependency3__["default"]; __exports__["default"] = function setupActiveModelAdapter(container, application){ var proxy = new ContainerProxy(container); proxy.registerDeprecations([ { deprecated: 'serializer:_ams', valid: 'serializer:-active-model' }, { deprecated: 'adapter:_ams', valid: 'adapter:-active-model' } ]); container.register('serializer:-active-model', ActiveModelSerializer); container.register('adapter:-active-model', ActiveModelAdapter); }; }); define("activemodel-adapter/system", ["activemodel-adapter/system/active_model_adapter","activemodel-adapter/system/active_model_serializer","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var ActiveModelAdapter = __dependency1__["default"]; var ActiveModelSerializer = __dependency2__["default"]; __exports__.ActiveModelAdapter = ActiveModelAdapter; __exports__.ActiveModelSerializer = ActiveModelSerializer; }); define("activemodel-adapter/system/active_model_adapter", ["ember-data/adapters","ember-data/system/adapter","ember-inflector","activemodel-adapter/system/active_model_serializer","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; var RESTAdapter = __dependency1__.RESTAdapter; var InvalidError = __dependency2__.InvalidError; var pluralize = __dependency3__.pluralize; var ActiveModelSerializer = __dependency4__["default"]; /** @module ember-data */ var forEach = Ember.EnumerableUtils.forEach; var decamelize = Ember.String.decamelize, underscore = Ember.String.underscore; /** The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers, `embed :ids, include: true` which sideloads the records. This adapter extends the DS.RESTAdapter by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelAdapter expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. Unlike the DS.RESTAdapter, async relationship keys must be the singular form of the relationship name, followed by "_id" for DS.belongsTo relationships, or "_ids" for DS.hasMany relationships. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` Let's imagine that `Occupation` is just another model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.belongsTo('occupation') }); App.Occupation = DS.Model.extend({ name: DS.attr('string'), salary: DS.attr('number'), people: DS.hasMany('person') }); ``` The JSON needed to avoid extra server calls, should look like this: ```js { "people": [{ "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation_id": 1 }], "occupations": [{ "id": 1, "name": "President", "salary": 100000, "person_ids": [1] }] } ``` @class ActiveModelAdapter @constructor @namespace DS @extends DS.RESTAdapter **/ var ActiveModelAdapter = RESTAdapter.extend({ defaultSerializer: '-active-model', /** The ActiveModelAdapter overrides the `pathForType` method to build underscored URLs by decamelizing and pluralizing the object type name. ```js this.pathForType("famousPerson"); //=> "famous_people" ``` @method pathForType @param {String} type @return String */ pathForType: function(type) { var decamelized = decamelize(type); var underscored = underscore(decamelized); return pluralize(underscored); }, /** The ActiveModelAdapter overrides the `ajaxError` method to return a DS.InvalidError for all 422 Unprocessable Entity responses. A 422 HTTP response from the server generally implies that the request was well formed but the API was unable to process it because the content was not semantically correct or meaningful per the API. For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918 https://tools.ietf.org/html/rfc4918#section-11.2 @method ajaxError @param jqXHR @return error */ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var response = Ember.$.parseJSON(jqXHR.responseText), errors = {}; if (response.errors !== undefined) { var jsonErrors = response.errors; forEach(Ember.keys(jsonErrors), function(key) { errors[Ember.String.camelize(key)] = jsonErrors[key]; }); } return new InvalidError(errors); } else { return error; } } }); __exports__["default"] = ActiveModelAdapter; }); define("activemodel-adapter/system/active_model_serializer", ["ember-inflector","ember-data/serializers/rest_serializer","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var singularize = __dependency1__.singularize; var RESTSerializer = __dependency2__["default"]; /** @module ember-data */ var get = Ember.get, forEach = Ember.EnumerableUtils.forEach, camelize = Ember.String.camelize, capitalize = Ember.String.capitalize, decamelize = Ember.String.decamelize, underscore = Ember.String.underscore; /** The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate with a JSON API that uses an underscored naming convention instead of camelCasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers, `embed :ids, include: true` which sideloads the records. This serializer extends the DS.RESTSerializer by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelSerializer expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` Let's imagine that `Occupation` is just another model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.belongsTo('occupation') }); App.Occupation = DS.Model.extend({ name: DS.attr('string'), salary: DS.attr('number'), people: DS.hasMany('person') }); ``` The JSON needed to avoid extra server calls, should look like this: ```js { "people": [{ "id": 1, "first_name": "Barack", "last_name": "Obama", "occupation_id": 1 }], "occupations": [{ "id": 1, "name": "President", "salary": 100000, "person_ids": [1] }] } ``` @class ActiveModelSerializer @namespace DS @extends DS.RESTSerializer */ var ActiveModelSerializer = RESTSerializer.extend({ // SERIALIZE /** Converts camelCased attributes to underscored when serializing. @method keyForAttribute @param {String} attribute @return String */ keyForAttribute: function(attr) { return decamelize(attr); }, /** Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} key @param {String} kind @return String */ keyForRelationship: function(rawKey, kind) { var key = decamelize(rawKey); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return singularize(key) + "_ids"; } else { return key; } }, /* Does not serialize hasMany relationships by default. */ serializeHasMany: Ember.K, /** Underscores the JSON root keys when serializing. @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(data, type, record, options) { var root = underscore(decamelize(type.typeKey)); data[root] = this.serialize(record, options); }, /** Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); var jsonKey = underscore(key + "_type"); if (Ember.isNone(belongsTo)) { json[jsonKey] = null; } else { json[jsonKey] = capitalize(camelize(belongsTo.constructor.typeKey)); } }, // EXTRACT /** Add extra step to `DS.RESTSerializer.normalize` so links are normalized. If your payload looks like: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flagged_comments": "api/comments/flagged" } } } ``` The normalized version would look like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flaggedComments": "api/comments/flagged" } } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @return Object */ normalize: function(type, hash, prop) { this.normalizeLinks(hash); return this._super(type, hash, prop); }, /** Convert `snake_cased` links to `camelCase` @method normalizeLinks @param {Object} data */ normalizeLinks: function(data){ if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }, /** Normalize the polymorphic type from the JSON. Normalize: ```js { id: "1" minion: { type: "evil_minion", id: "12"} } ``` To: ```js { id: "1" minion: { type: "evilMinion", id: "12"} } ``` @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { var payloadKey, payload; if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key); payload = hash[payloadKey]; if (payload && payload.type) { payload.type = this.typeForRoot(payload.type); } else if (payload && relationship.kind === "hasMany") { var self = this; forEach(payload, function(single) { single.type = self.typeForRoot(single.type); }); } } else { payloadKey = this.keyForRelationship(key, relationship.kind); if (!hash.hasOwnProperty(payloadKey)) { return; } payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } } }); __exports__["default"] = ActiveModelSerializer; }); define("ember-data", ["ember-data/core","ember-data/ext/date","ember-data/system/store","ember-data/system/model","ember-data/system/changes","ember-data/system/adapter","ember-data/system/debug","ember-data/system/record_arrays","ember-data/system/record_array_manager","ember-data/adapters","ember-data/serializers/json_serializer","ember-data/serializers/rest_serializer","ember-inflector","ember-data/serializers/embedded_records_mixin","activemodel-adapter","ember-data/transforms","ember-data/system/relationships","ember-data/ember-initializer","ember-data/setup-container","ember-data/system/container_proxy","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __dependency16__, __dependency17__, __dependency18__, __dependency19__, __dependency20__, __exports__) { "use strict"; /** Ember Data @module ember-data @main ember-data */ // support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve; var DS = __dependency1__["default"]; var Store = __dependency3__.Store; var PromiseArray = __dependency3__.PromiseArray; var PromiseObject = __dependency3__.PromiseObject; var Model = __dependency4__.Model; var Errors = __dependency4__.Errors; var RootState = __dependency4__.RootState; var attr = __dependency4__.attr; var AttributeChange = __dependency5__.AttributeChange; var RelationshipChange = __dependency5__.RelationshipChange; var RelationshipChangeAdd = __dependency5__.RelationshipChangeAdd; var RelationshipChangeRemove = __dependency5__.RelationshipChangeRemove; var OneToManyChange = __dependency5__.OneToManyChange; var ManyToNoneChange = __dependency5__.ManyToNoneChange; var OneToOneChange = __dependency5__.OneToOneChange; var ManyToManyChange = __dependency5__.ManyToManyChange; var InvalidError = __dependency6__.InvalidError; var Adapter = __dependency6__.Adapter; var DebugAdapter = __dependency7__["default"]; var RecordArray = __dependency8__.RecordArray; var FilteredRecordArray = __dependency8__.FilteredRecordArray; var AdapterPopulatedRecordArray = __dependency8__.AdapterPopulatedRecordArray; var ManyArray = __dependency8__.ManyArray; var RecordArrayManager = __dependency9__["default"]; var RESTAdapter = __dependency10__.RESTAdapter; var FixtureAdapter = __dependency10__.FixtureAdapter; var JSONSerializer = __dependency11__["default"]; var RESTSerializer = __dependency12__["default"]; var EmbeddedRecordsMixin = __dependency14__["default"]; var ActiveModelAdapter = __dependency15__.ActiveModelAdapter; var ActiveModelSerializer = __dependency15__.ActiveModelSerializer; var Transform = __dependency16__.Transform; var DateTransform = __dependency16__.DateTransform; var NumberTransform = __dependency16__.NumberTransform; var StringTransform = __dependency16__.StringTransform; var BooleanTransform = __dependency16__.BooleanTransform; var hasMany = __dependency17__.hasMany; var belongsTo = __dependency17__.belongsTo; var setupContainer = __dependency19__["default"]; var ContainerProxy = __dependency20__["default"]; DS.Store = Store; DS.PromiseArray = PromiseArray; DS.PromiseObject = PromiseObject; DS.Model = Model; DS.RootState = RootState; DS.attr = attr; DS.Errors = Errors; DS.AttributeChange = AttributeChange; DS.RelationshipChange = RelationshipChange; DS.RelationshipChangeAdd = RelationshipChangeAdd; DS.OneToManyChange = OneToManyChange; DS.ManyToNoneChange = OneToManyChange; DS.OneToOneChange = OneToOneChange; DS.ManyToManyChange = ManyToManyChange; DS.Adapter = Adapter; DS.InvalidError = InvalidError; DS.DebugAdapter = DebugAdapter; DS.RecordArray = RecordArray; DS.FilteredRecordArray = FilteredRecordArray; DS.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray; DS.ManyArray = ManyArray; DS.RecordArrayManager = RecordArrayManager; DS.RESTAdapter = RESTAdapter; DS.FixtureAdapter = FixtureAdapter; DS.RESTSerializer = RESTSerializer; DS.JSONSerializer = JSONSerializer; DS.Transform = Transform; DS.DateTransform = DateTransform; DS.StringTransform = StringTransform; DS.NumberTransform = NumberTransform; DS.BooleanTransform = BooleanTransform; DS.ActiveModelAdapter = ActiveModelAdapter; DS.ActiveModelSerializer = ActiveModelSerializer; DS.EmbeddedRecordsMixin = EmbeddedRecordsMixin; DS.belongsTo = belongsTo; DS.hasMany = hasMany; DS.ContainerProxy = ContainerProxy; DS._setupContainer = setupContainer; Ember.lookup.DS = DS; __exports__["default"] = DS; }); define("ember-data/adapters", ["ember-data/adapters/fixture_adapter","ember-data/adapters/rest_adapter","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var FixtureAdapter = __dependency1__["default"]; var RESTAdapter = __dependency2__["default"]; __exports__.RESTAdapter = RESTAdapter; __exports__.FixtureAdapter = FixtureAdapter; }); define("ember-data/adapters/fixture_adapter", ["ember-data/system/adapter","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var get = Ember.get; var fmt = Ember.String.fmt; var indexOf = Ember.EnumerableUtils.indexOf; var counter = 0; var Adapter = __dependency1__["default"]; /** `DS.FixtureAdapter` is an adapter that loads records from memory. It's primarily used for development and testing. You can also use `DS.FixtureAdapter` while working on the API but is not ready to integrate yet. It is a fully functioning adapter. All CRUD methods are implemented. You can also implement query logic that a remote system would do. It's possible to develop your entire application with `DS.FixtureAdapter`. For information on how to use the `FixtureAdapter` in your application please see the [FixtureAdapter guide](/guides/models/the-fixture-adapter/). @class FixtureAdapter @namespace DS @extends DS.Adapter */ __exports__["default"] = Adapter.extend({ // by default, fixtures are already in normalized form serializer: null, /** If `simulateRemoteResponse` is `true` the `FixtureAdapter` will wait a number of milliseconds before resolving promises with the fixture values. The wait time can be configured via the `latency` property. @property simulateRemoteResponse @type {Boolean} @default true */ simulateRemoteResponse: true, /** By default the `FixtureAdapter` will simulate a wait of the `latency` milliseconds before resolving promises with the fixture values. This behavior can be turned off via the `simulateRemoteResponse` property. @property latency @type {Number} @default 50 */ latency: 50, /** Implement this method in order to provide data associated with a type @method fixturesForType @param {Subclass of DS.Model} type @return {Array} */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture){ var fixtureIdType = typeof fixture.id; if(fixtureIdType !== "number" && fixtureIdType !== "string"){ throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /** Implement this method in order to query fixtures data @method queryFixtures @param {Array} fixture @param {Object} query @param {Subclass of DS.Model} type @return {Promise|Array} */ queryFixtures: function(fixtures, query, type) { Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.'); }, /** @method updateFixtures @param {Subclass of DS.Model} type @param {Array} fixture */ updateFixtures: function(type, fixture) { if(!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /** Implement this method in order to provide json for CRUD methods @method mockJSON @param {Subclass of DS.Model} type @param {DS.Model} record */ mockJSON: function(store, type, record) { return store.serializerFor(type).serialize(record, { includeId: true }); }, /** @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String} id */ generateIdForRecord: function(store) { return "fixture-" + counter++; }, /** @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: function(store, type, id) { var fixtures = this.fixturesForType(type); var fixture; Ember.assert("Unable to find fixtures for model type "+type.toString() +". If you're defining your fixtures using `Model.FIXTURES = ...`, please change it to `Model.reopenClass({ FIXTURES: ... })`.", fixtures); if (fixtures) { fixture = Ember.A(fixtures).findBy('id', id); } if (fixture) { return this.simulateRemoteCall(function() { return fixture; }, this); } }, /** @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); if (fixtures) { fixtures = fixtures.filter(function(item) { return indexOf(ids, item.id) !== -1; }); } if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); return this.simulateRemoteCall(function() { return fixtures; }, this); }, /** @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type " + type.toString(), fixtures); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ createRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ updateRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ deleteRecord: function(store, type, record) { this.deleteLoadedFixture(type, record); return this.simulateRemoteCall(function() { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param type @param record */ deleteLoadedFixture: function(type, record) { var existingFixture = this.findExistingFixture(type, record); if (existingFixture) { var index = indexOf(type.FIXTURES, existingFixture); type.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param type @param record */ findExistingFixture: function(type, record) { var fixtures = this.fixturesForType(type); var id = get(record, 'id'); return this.findFixtureById(fixtures, id); }, /* @method findFixtureById @private @param fixtures @param id */ findFixtureById: function(fixtures, id) { return Ember.A(fixtures).find(function(r) { if (''+get(r, 'id') === ''+id) { return true; } else { return false; } }); }, /* @method simulateRemoteCall @private @param callback @param context */ simulateRemoteCall: function(callback, context) { var adapter = this; return new Ember.RSVP.Promise(function(resolve) { if (get(adapter, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(function() { resolve(callback.call(context)); }, get(adapter, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.schedule('actions', null, function() { resolve(callback.call(context)); }); } }, "DS: FixtureAdapter#simulateRemoteCall"); } }); }); define("ember-data/adapters/rest_adapter", ["ember-data/system/adapter","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var Adapter = __dependency1__["default"]; var get = Ember.get; var forEach = Ember.ArrayPolyfills.forEach; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` Similarly, in response to a `GET` request for `/posts`, the JSON should look like this: ```js { "posts": [ { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" }, { "id": 2, "title": "Rails is omakase", "author": "D2H" } ] } ``` ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "id": 5, "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```js DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Person` would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```js DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` `headers` can also be used as a computed property to support dynamic headers. In the example below, the `session` object has been injected into an adapter by Ember's container. ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: function() { return { "API_KEY": this.get("session.authToken"), "ANOTHER_HEADER": "Some header value" }; }.property("session.authToken") }); ``` In some cases, your dynamic headers may require data from some object outside of Ember's observer system (for example `document.cookie`). You can use the [volatile](/api/classes/Ember.ComputedProperty.html#method_volatile) function to set the property into a non-cached mode causing the headers to be recomputed with every request. ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: function() { return { "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), "ANOTHER_HEADER": "Some header value" }; }.property().volatile() }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter */ __exports__["default"] = Adapter.extend({ defaultSerializer: '-rest', /** By default the RESTAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of ```javascript post: { id:1, comments: [1,2] } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?ids[]=1&ids[]=2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.find('comment', 1); store.find('comment', 2); ``` will also send a request to: `GET /comments?ids[]=1&ids[]=2` @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```javascript DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Post` would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```javascript DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` Requests for `App.Post` would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. For dynamic headers see [headers customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the query string. @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @param {DS.Model} record @return {Promise} promise */ find: function(store, type, id, record) { return this.ajax(this.buildURL(type.typeKey, id, record), 'GET'); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type, sinceToken) { var query; if (sinceToken) { query = { since: sinceToken }; } return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @return {Promise} promise */ findQuery: function(store, type, query) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch several records together if `coalesceFindRequests` is true For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @param {Array} records @return {Promise} promise */ findMany: function(store, type, ids, records) { return this.ajax(this.buildURL(type.typeKey, ids, records), 'GET', { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. If the URL is host-relative (starting with a single slash), the request will use the host specified on the adapter (if any). @method findHasMany @param {DS.Store} store @param {DS.Model} record @param {String} url @return {Promise} promise */ findHasMany: function(store, record, url) { var host = get(this, 'host'); var id = get(record, 'id'); var type = record.constructor.typeKey; if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') { url = host + url; } return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. @method findBelongsTo @param {DS.Store} store @param {DS.Model} record @param {String} url @return {Promise} promise */ findBelongsTo: function(store, record, url) { var id = get(record, 'id'); var type = record.constructor.typeKey; return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ createRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record, { includeId: true }); return this.ajax(this.buildURL(type.typeKey, null, record), "POST", { data: data }); }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ updateRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record); var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id, record), "PUT", { data: data }); }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ deleteRecord: function(store, type, record) { var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id, record), "DELETE"); }, /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. @method buildURL @param {String} type @param {String} id @param {DS.Model} record @return {String} url */ buildURL: function(type, id, record) { var url = [], host = get(this, 'host'), prefix = this.urlPrefix(); if (type) { url.push(this.pathForType(type)); } //We might get passed in an array of ids from findMany //in which case we don't want to modify the url, as the //ids will be passed in through a query param if (id && !Ember.isArray(id)) { url.push(id); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url) { url = '/' + url; } return url; }, /** @method urlPrefix @private @param {String} path @param {String} parentUrl @return {String} urlPrefix */ urlPrefix: function(path, parentURL) { var host = get(this, 'host'); var namespace = get(this, 'namespace'); var url = []; if (path) { // Absolute path if (path.charAt(0) === '/') { if (host) { path = path.slice(1); url.push(host); } // Relative path } else if (!/^http(s)?:\/\//.test(path)) { url.push(parentURL); } } else { if (host) { url.push(host); } if (namespace) { url.push(namespace); } } if (path) { url.push(path); } return url.join('/'); }, _stripIDFromURL: function(store, record) { var type = store.modelFor(record); var url = this.buildURL(type.typeKey, record.get('id'), record); var expandedURL = url.split('/'); //Case when the url is of the format ...something/:id var lastSegment = expandedURL[ expandedURL.length - 1 ]; var id = record.get('id'); if (lastSegment === id) { expandedURL[expandedURL.length - 1] = ""; } else if(endsWith(lastSegment, '?id=' + id)) { //Case when the url is of the format ...something?id=:id expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); } return expandedURL.join('/'); }, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. This implementation groups together records that have the same base URL but differing ids. For example `/comments/1` and `/comments/2` will be grouped together because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2` It also supports urls where ids are passed as a query param, such as `/comments?id=1` but not those where there is more than 1 query param such as `/comments?id=2&name=David` Currently only the query param of `id` is supported. If you need to support others, please override this or the `_stripIDFromURL` method. It does not group records that have differing base urls, such as for example: `/posts/1/comments/2` and `/posts/2/comments/3` @method groupRecordsForFindMany @param {Array} records @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, records) { var groups = Ember.MapWithDefault.create({defaultValue: function(){return [];}}); var adapter = this; forEach.call(records, function(record){ var baseUrl = adapter._stripIDFromURL(store, record); groups.get(baseUrl).push(record); }); function splitGroupToFitInUrl(group, maxUrlLength) { var baseUrl = adapter._stripIDFromURL(store, group[0]); var idsSize = 0; var splitGroups = [[]]; forEach.call(group, function(record) { var additionalLength = '&ids[]='.length + record.get('id.length'); if (baseUrl.length + idsSize + additionalLength >= maxUrlLength) { idsSize = 0; splitGroups.push([]); } idsSize += additionalLength; var lastGroupIndex = splitGroups.length - 1; splitGroups[lastGroupIndex].push(record); }); return splitGroups; } var groupsArray = []; groups.forEach(function(key, group){ // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers var maxUrlLength = 2048; var splitGroups = splitGroupToFitInUrl(group, maxUrlLength); forEach.call(splitGroups, function(splitGroup) { groupsArray.push(splitGroup); }); }); return groupsArray; }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```js App.ApplicationAdapter = DS.RESTAdapter.extend({ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} type @return {String} path **/ pathForType: function(type) { var camelized = Ember.String.camelize(type); return Ember.String.pluralize(camelized); }, /** Takes an ajax response, and returns a relevant error. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` Note: As a correctness optimization, the default implementation of the `ajaxError` method strips out the `then` method from jquery's ajax response (jqXHR). This is important because the jqXHR's `then` method fulfills the promise with itself resulting in a circular "thenable" chain which may cause problems for some promise libraries. @method ajaxError @param {Object} jqXHR @return {Object} jqXHR */ ajaxError: function(jqXHR) { if (jqXHR && typeof jqXHR === 'object') { jqXHR.then = null; } return jqXHR; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} hash @return {Promise} promise */ ajax: function(url, type, options) { var adapter = this; return new Ember.RSVP.Promise(function(resolve, reject) { var hash = adapter.ajaxOptions(url, type, options); hash.success = function(json) { Ember.run(null, resolve, json); }; hash.error = function(jqXHR, textStatus, errorThrown) { Ember.run(null, reject, adapter.ajaxError(jqXHR)); }; Ember.$.ajax(hash); }, "DS: RESTAdapter#ajax " + type + " to " + url); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} hash @return {Object} hash */ ajaxOptions: function(url, type, options) { var hash = options || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } var headers = get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function (xhr) { forEach.call(Ember.keys(headers), function(key) { xhr.setRequestHeader(key, headers[key]); }); }; } return hash; } }); //From http://stackoverflow.com/questions/280634/endswith-in-javascript function endsWith(string, suffix){ if (typeof String.prototype.endsWith !== 'function') { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } } }); define("ember-data/core", ["exports"], function(__exports__) { "use strict"; /** @module ember-data */ /** All Ember Data methods and functions are defined inside of this namespace. @class DS @static */ var DS; if ('undefined' === typeof DS) { /** @property VERSION @type String @default '1.0.0-beta.9' @static */ DS = Ember.Namespace.create({ VERSION: '1.0.0-beta.9' }); if (Ember.libraries) { Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } } __exports__["default"] = DS; }); define("ember-data/ember-initializer", ["ember-data/setup-container"], function(__dependency1__) { "use strict"; var setupContainer = __dependency1__["default"]; var K = Ember.K; /** @module ember-data */ /* This code initializes Ember-Data onto an Ember application. If an Ember.js developer defines a subclass of DS.Store on their application, as `App.ApplicationStore` (or via a module system that resolves to `store:application`) this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.ApplicationStore = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.ApplicationStore` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "ember-data", initialize: setupContainer }); // Deprecated initializers to satisfy old code that depended on them Application.initializer({ name: "store", after: "ember-data", initialize: K }); Application.initializer({ name: "activeModelAdapter", before: "store", initialize: K }); Application.initializer({ name: "transforms", before: "store", initialize: K }); Application.initializer({ name: "data-adapter", before: "store", initialize: K }); Application.initializer({ name: "injectStore", before: "store", initialize: K }); }); }); define("ember-data/ext/date", [], function() { "use strict"; /** @module ember-data */ /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static */ Ember.Date = Ember.Date || {}; var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; /** @method parse @param date */ Ember.Date.parse = function (date) { var timestamp, struct, minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } }); define("ember-data/initializers/data_adapter", ["ember-data/system/debug/debug_adapter","exports"], function(__dependency1__, __exports__) { "use strict"; var DebugAdapter = __dependency1__["default"]; /** Configures a container with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Container} container */ __exports__["default"] = function initializeDebugAdapter(container){ container.register('data-adapter:main', DebugAdapter); }; }); define("ember-data/initializers/store", ["ember-data/serializers","ember-data/adapters","ember-data/system/container_proxy","ember-data/system/store","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; var JSONSerializer = __dependency1__.JSONSerializer; var RESTSerializer = __dependency1__.RESTSerializer; var RESTAdapter = __dependency2__.RESTAdapter; var ContainerProxy = __dependency3__["default"]; var Store = __dependency4__["default"]; /** Configures a container for use with an Ember-Data store. Accepts an optional namespace argument. @method initializeStore @param {Ember.Container} container @param {Object} [application] an application namespace */ __exports__["default"] = function initializeStore(container, application){ Ember.deprecate('Specifying a custom Store for Ember Data on your global namespace as `App.Store` ' + 'has been deprecated. Please use `App.ApplicationStore` instead.', !(application && application.Store)); container.register('store:main', container.lookupFactory('store:application') || (application && application.Store) || Store); // allow older names to be looked up var proxy = new ContainerProxy(container); proxy.registerDeprecations([ { deprecated: 'serializer:_default', valid: 'serializer:-default' }, { deprecated: 'serializer:_rest', valid: 'serializer:-rest' }, { deprecated: 'adapter:_rest', valid: 'adapter:-rest' } ]); // new go forward paths container.register('serializer:-default', JSONSerializer); container.register('serializer:-rest', RESTSerializer); container.register('adapter:-rest', RESTAdapter); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook container.lookup('store:main'); }; }); define("ember-data/initializers/store_injections", ["exports"], function(__exports__) { "use strict"; /** Configures a container with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Container} container */ __exports__["default"] = function initializeStoreInjections(container){ container.injection('controller', 'store', 'store:main'); container.injection('route', 'store', 'store:main'); container.injection('serializer', 'store', 'store:main'); container.injection('data-adapter', 'store', 'store:main'); }; }); define("ember-data/initializers/transforms", ["ember-data/transforms","exports"], function(__dependency1__, __exports__) { "use strict"; var BooleanTransform = __dependency1__.BooleanTransform; var DateTransform = __dependency1__.DateTransform; var StringTransform = __dependency1__.StringTransform; var NumberTransform = __dependency1__.NumberTransform; /** Configures a container for use with Ember-Data transforms. @method initializeTransforms @param {Ember.Container} container */ __exports__["default"] = function initializeTransforms(container){ container.register('transform:boolean', BooleanTransform); container.register('transform:date', DateTransform); container.register('transform:number', NumberTransform); container.register('transform:string', StringTransform); }; }); define("ember-data/serializers", ["ember-data/serializers/json_serializer","ember-data/serializers/rest_serializer","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var JSONSerializer = __dependency1__["default"]; var RESTSerializer = __dependency2__["default"]; __exports__.JSONSerializer = JSONSerializer; __exports__.RESTSerializer = RESTSerializer; }); define("ember-data/serializers/embedded_records_mixin", ["ember-inflector","exports"], function(__dependency1__, __exports__) { "use strict"; var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; var camelize = Ember.String.camelize; var pluralize = __dependency1__.pluralize; /** ## Using Embedded Records `DS.EmbeddedRecordsMixin` supports serializing embedded records. To set up embedded records, include the mixin when extending a serializer then define and configure embedded (model) relationships. Below is an example of a per-type serializer ('post' type). ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: {embedded: 'always'}, comments: {serialize: 'ids'} } }) ``` The `attrs` option for a resource `{embedded: 'always'}` is shorthand for: ```js {serialize: 'records', deserialize: 'records'} ``` ### Configuring Attrs A resource's `attrs` option may be set to use `ids`, `records` or false for the `serialize` and `deserialize` settings. The `attrs` property can be set on the ApplicationSerializer or a per-type serializer. In the case where embedded JSON is expected while extracting a payload (reading) the setting is `deserialize: 'records'`, there is no need to use `ids` when extracting as that is the default behavior without this mixin if you are using the vanilla EmbeddedRecordsMixin. Likewise, to embed JSON in the payload while serializing `serialize: 'records'` is the setting to use. There is an option of not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you do not want the relationship sent at all, you can use `serialize: false`. ### EmbeddedRecordsMixin defaults If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin` will behave in the following way: BelongsTo: `{serialize:'id', deserialize:'id'}` HasMany: `{serialize:false, deserialize:'ids'}` ### Model Relationships Embedded records must have a model defined to be extracted and serialized. To successfully extract and serialize embedded records the model relationships must be setup correcty See the [defining relationships](/guides/models/defining-models/#toc_defining-relationships) section of the **Defining Models** guide page. Records without an `id` property are not considered embedded records, model instances must have an `id` property to be used with Ember Data. ### Example JSON payloads, Models and Serializers **When customizing a serializer it is imporant to grok what the cusomizations are, please read the docs for the methods this mixin provides, in case you need to modify to fit your specific needs.** For example review the docs for each method of this mixin: * [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize) * [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo) * [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany) @class EmbeddedRecordsMixin @namespace DS */ var EmbeddedRecordsMixin = Ember.Mixin.create({ /** Normalize the record and recursively normalize/extract all the embedded records while pushing them into the store as they are encountered A payload with an attr configured for embedded records needs to be extracted: ```js { "post": { "id": "1" "title": "Rails is omakase", "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash to be normalized @param {String} key the hash has been referenced by @return {Object} the normalized hash **/ normalize: function(type, hash, prop) { var normalizedHash = this._super(type, hash, prop); return extractEmbeddedRecords(this, this.store, type, normalizedHash); }, keyForRelationship: function(key, type){ if (this.hasDeserializeRecordsOption(key)) { return this.keyForAttribute(key); } else { return this._super(key, type) || key; } }, /** Serialize `belongsTo` relationship when it is configured as an embedded object. This example of an author model belongs to a post model: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), author: DS.belongsTo('author') }); Author = DS.Model.extend({ name: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded author ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: {embedded: 'always'} } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "author": { "id": "2" "name": "dhh" } } } ``` @method serializeBelongsTo @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(record, json, relationship) { var attr = relationship.key; var attrs = this.get('attrs'); if (this.noSerializeOptionSpecified(attr)) { this._super(record, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var embeddedRecord = record.get(attr); var key; if (includeIds) { key = this.keyForRelationship(attr, relationship.kind); if (!embeddedRecord) { json[key] = null; } else { json[key] = get(embeddedRecord, 'id'); } } else if (includeRecords) { key = this.keyForAttribute(attr); if (!embeddedRecord) { json[key] = null; } else { json[key] = embeddedRecord.serialize({includeId: true}); this.removeEmbeddedForeignKey(record, embeddedRecord, relationship, json[key]); } } }, /** Serialize `hasMany` relationship when it is configured as embedded objects. This example of a post model has many comments: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), comments: DS.hasMany('comment') }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded comments ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {embedded: 'always'} } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` The attrs options object can use more specific instruction for extracting and serializing. When serializing, an option to embed `ids` or `records` can be set. When extracting the only option is `records`. So `{embedded: 'always'}` is shorthand for: `{serialize: 'records', deserialize: 'records'}` To embed the `ids` for a related object (using a hasMany relationship): ```js App.PostSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {serialize: 'ids', deserialize: 'records'} } }) ``` ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": ["1", "2"] } } ``` @method serializeHasMany @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeHasMany: function(record, json, relationship) { var attr = relationship.key; var attrs = this.get('attrs'); if (this.noSerializeOptionSpecified(attr)) { this._super(record, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var key; if (includeIds) { key = this.keyForRelationship(attr, relationship.kind); json[key] = get(record, attr).mapBy('id'); } else if (includeRecords) { key = this.keyForAttribute(attr); json[key] = get(record, attr).map(function(embeddedRecord) { var serializedEmbeddedRecord = embeddedRecord.serialize({includeId: true}); this.removeEmbeddedForeignKey(record, embeddedRecord, relationship, serializedEmbeddedRecord); return serializedEmbeddedRecord; }, this); } }, /** When serializing an embedded record, modify the property (in the json payload) that refers to the parent record (foreign key for relationship). Serializing a `belongsTo` relationship removes the property that refers to the parent record Serializing a `hasMany` relationship does not remove the property that refers to the parent record. @method removeEmbeddedForeignKey @param {DS.Model} record @param {DS.Model} embeddedRecord @param {Object} relationship @param {Object} json */ removeEmbeddedForeignKey: function (record, embeddedRecord, relationship, json) { if (relationship.kind === 'hasMany') { return; } else if (relationship.kind === 'belongsTo') { var parentRecord = record.constructor.inverseFor(relationship.key); if (parentRecord) { var name = parentRecord.name; var embeddedSerializer = this.store.serializerFor(embeddedRecord.constructor); var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind); if (parentKey) { delete json[parentKey]; } } } }, // checks config for attrs option to embedded (always) - serialize and deserialize hasEmbeddedAlwaysOption: function (attr) { var option = this.attrsOption(attr); return option && option.embedded === 'always'; }, // checks config for attrs option to serialize ids hasSerializeRecordsOption: function(attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || (option && (option.serialize === 'records')); }, // checks config for attrs option to serialize records hasSerializeIdsOption: function(attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids' || option.serialize === 'id'); }, // checks config for attrs option to serialize records noSerializeOptionSpecified: function(attr) { var option = this.attrsOption(attr); var serializeRecords = this.hasSerializeRecordsOption(attr); var serializeIds = this.hasSerializeIdsOption(attr); return !(option && (option.serialize || option.embedded)); }, // checks config for attrs option to deserialize records // a defined option object for a resource is treated the same as // `deserialize: 'records'` hasDeserializeRecordsOption: function(attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || (option && option.deserialize === 'records'); }, attrsOption: function(attr) { var attrs = this.get('attrs'); return attrs && (attrs[camelize(attr)] || attrs[attr]); } }); // chooses a relationship kind to branch which function is used to update payload // does not change payload if attr is not embedded function extractEmbeddedRecords(serializer, store, type, partial) { type.eachRelationship(function(key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { var embeddedType = store.modelFor(relationship.type.typeKey); if (relationship.kind === "hasMany") { extractEmbeddedHasMany(store, key, embeddedType, partial); } if (relationship.kind === "belongsTo") { extractEmbeddedBelongsTo(store, key, embeddedType, partial); } } }); return partial; } // handles embedding for `hasMany` relationship function extractEmbeddedHasMany(store, key, embeddedType, hash) { if (!hash[key]) { return hash; } var ids = []; var embeddedSerializer = store.serializerFor(embeddedType.typeKey); forEach(hash[key], function(data) { var embeddedRecord = embeddedSerializer.normalize(embeddedType, data, null); store.push(embeddedType, embeddedRecord); ids.push(embeddedRecord.id); }); hash[key] = ids; return hash; } function extractEmbeddedBelongsTo(store, key, embeddedType, hash) { if (!hash[key]) { return hash; } var embeddedSerializer = store.serializerFor(embeddedType.typeKey); var embeddedRecord = embeddedSerializer.normalize(embeddedType, hash[key], null); store.push(embeddedType, embeddedRecord); hash[key] = embeddedRecord.id; //TODO Need to add a reference to the parent later so relationship works between both `belongsTo` records return hash; } __exports__["default"] = EmbeddedRecordsMixin; }); define("ember-data/serializers/json_serializer", ["ember-data/system/changes","exports"], function(__dependency1__, __exports__) { "use strict"; var RelationshipChange = __dependency1__.RelationshipChange; var get = Ember.get; var set = Ember.set; var isNone = Ember.isNone; var map = Ember.ArrayPolyfills.map; var merge = Ember.merge; /** In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. For maximum performance Ember Data recommends you use the [RESTSerializer](DS.RESTSerializer.html) or one of its subclasses. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. @class JSONSerializer @namespace DS */ __exports__["default"] = Ember.Object.extend({ /** The primaryKey is used when serializing and deserializing data. Ember Data always uses the `id` property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override the primaryKey property to match the primaryKey of your external store. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** The `attrs` object can be used to declare a simple mapping between property names on `DS.Model` records and payload keys in the serialized JSON object representing the record. An object with the property `key` can also be used to designate the attribute's key on the response payload. Example ```javascript App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string'), admin: DS.attr('boolean') }); App.PersonSerializer = DS.JSONSerializer.extend({ attrs: { admin: 'is_admin', occupation: {key: 'career'} } }); ``` You can also remove attributes by setting the `serialize` key to false in your mapping object. Example ```javascript App.PersonSerializer = DS.JSONSerializer.extend({ attrs: { admin: {serialize: false}, occupation: {key: 'career'} } }); ``` When serialized: ```javascript { "career": "magician" } ``` Note that the `admin` is now not included in the payload. @property attrs @type {Object} */ /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {subclass of DS.Model} type @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function(type, data) { type.eachTransformedAttribute(function(key, type) { if (!data.hasOwnProperty(key)) { return; } var transform = this.transformFor(type); data[key] = transform.deserialize(data[key]); }, this); return data; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ normalize: function(type, hash) { var fields = Ember.get(type, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @return {Object} */ normalize: function(type, hash) { if (!hash) { return hash; } this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); this.applyTransforms(type, hash); return hash; }, /** You can use this method to normalize all payloads, regardless of whether they represent single records or an array. For example, you might want to remove some extraneous data from the payload: ```js App.ApplicationSerializer = DS.JSONSerializer.extend({ normalizePayload: function(payload) { delete payload.version; delete payload.status; return payload; } }); ``` @method normalizePayload @param {Object} payload @return {Object} the normalized payload */ normalizePayload: function(payload) { return payload; }, /** @method normalizeAttributes @private */ normalizeAttributes: function(type, hash) { var payloadKey, key; if (this.keyForAttribute) { type.eachAttribute(function(key) { payloadKey = this.keyForAttribute(key); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, key; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function(type, hash) { var attrs = get(this, 'attrs'), payloadKey, key; if (attrs) { for (key in attrs) { payloadKey = this._getMappedKey(key); if (!hash.hasOwnProperty(payloadKey)) { continue; } if (payloadKey !== key) { hash[key] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** @method normalizeId @private */ normalizeId: function(hash) { var primaryKey = get(this, 'primaryKey'); if (primaryKey === 'id') { return; } hash.id = hash[primaryKey]; delete hash[primaryKey]; }, /** Looks up the property key that was set by the custom `attr` mapping passed to the serializer. @method _getMappedKey @private @param {String} key @return {String} key */ _getMappedKey: function(key) { var attrs = get(this, 'attrs'); var mappedKey; if (attrs && attrs[key]) { mappedKey = attrs[key]; //We need to account for both the {title: 'post_title'} and //{title: {key: 'post_title'}} forms if (mappedKey.key){ mappedKey = mappedKey.key; } if (typeof mappedKey === 'string'){ key = mappedKey; } } return key; }, /** Check attrs.key.serialize property to inform if the `key` can be serialized @method _canSerialize @private @param {String} key @return {boolean} true if the key can be serialized */ _canSerialize: function(key) { var attrs = get(this, 'attrs'); return !attrs || !attrs[key] || attrs[key].serialize !== false; }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```javascript App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapBy('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {subclass of DS.Model} record @param {Object} options @return {Object} json */ serialize: function(record, options) { var json = {}; if (options && options.includeId) { var id = get(record, 'id'); if (id) { json[get(this, 'primaryKey')] = id; } } record.eachAttribute(function(key, attribute) { this.serializeAttribute(record, json, key, attribute); }, this); record.eachRelationship(function(key, relationship) { if (relationship.kind === 'belongsTo') { this.serializeBelongsTo(record, json, relationship); } else if (relationship.kind === 'hasMany') { this.serializeHasMany(record, json, relationship); } }, this); return json; }, /** You can use this method to customize how a serialized record is added to the complete JSON hash to be sent to the server. By default the JSON Serializer does not namespace the payload and just sends the raw serialized JSON object. If your server expects namespaced keys, you should consider using the RESTSerializer. Otherwise you can override this method to customize how the record is added to the hash. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(hash, type, record, options) { merge(hash, this.serialize(record, options)); }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all your attributes were always serialized as properties on an `attributes` object you could write: ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serializeAttribute: function(record, json, key, attributes) { json.attributes = json.attributes || {}; this._super(record, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Model} record @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function(record, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { var value = get(record, key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value); } // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForAttribute) { payloadKey = this.keyForAttribute(key); } json[payloadKey] = value; } }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsTo = get(record, key); // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "belongsTo"); } if (isNone(belongsTo)) { json[payloadKey] = belongsTo; } else { json[payloadKey] = get(belongsTo, 'id'); } if (relationship.options.polymorphic) { this.serializePolymorphicType(record, json, relationship); } } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeHasMany: function(record, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeHasMany: function(record, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var payloadKey; // if provided, use the mapping provided by `attrs` in // the serializer payloadKey = this._getMappedKey(key); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "hasMany"); } var relationshipType = RelationshipChange.determineRelationshipType(record.constructor, relationship); if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') { json[payloadKey] = get(record, key).mapBy('id'); // TODO support for polymorphic manyToNone and manyToMany relationships } } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{polymorphic: true}` is pass as the second argument to the `DS.belongsTo` function. Example ```javascript App.CommentSerializer = DS.JSONSerializer.extend({ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; if (Ember.isNone(belongsTo)) { json[key + "_type"] = null; } else { json[key + "_type"] = belongsTo.constructor.typeKey; } } }); ``` @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: Ember.K, // EXTRACT /** The `extract` method is used to deserialize payload data from the server. By default the `JSONSerializer` does not push the records into the store. However records that subclass `JSONSerializer` such as the `RESTSerializer` may push records into the store as part of the extract call. This method delegates to a more specific extract method based on the `requestType`. Example ```javascript var get = Ember.get; socket.on('message', function(message) { var modelName = message.model; var data = message.data; var type = store.modelFor(modelName); var serializer = store.serializerFor(type.typeKey); var record = serializer.extract(store, type, data, get(data, 'id'), 'single'); store.push(modelName, record); }); ``` @method extract @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extract: function(store, type, payload, id, requestType) { this.extractMeta(store, type, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, type, payload, id, requestType); }, /** `extractFindAll` is a hook into the extract method used when a call is made to `DS.Store#findAll`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindAll @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindAll: function(store, type, payload, id, requestType){ return this.extractArray(store, type, payload, id, requestType); }, /** `extractFindQuery` is a hook into the extract method used when a call is made to `DS.Store#findQuery`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindQuery: function(store, type, payload, id, requestType){ return this.extractArray(store, type, payload, id, requestType); }, /** `extractFindMany` is a hook into the extract method used when a call is made to `DS.Store#findMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindMany: function(store, type, payload, id, requestType){ return this.extractArray(store, type, payload, id, requestType); }, /** `extractFindHasMany` is a hook into the extract method used when a call is made to `DS.Store#findHasMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindHasMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindHasMany: function(store, type, payload, id, requestType){ return this.extractArray(store, type, payload, id, requestType); }, /** `extractCreateRecord` is a hook into the extract method used when a call is made to `DS.Store#createRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractCreateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractCreateRecord: function(store, type, payload, id, requestType) { return this.extractSave(store, type, payload, id, requestType); }, /** `extractUpdateRecord` is a hook into the extract method used when a call is made to `DS.Store#update`. By default this method is alias for [extractSave](#method_extractSave). @method extractUpdateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractUpdateRecord: function(store, type, payload, id, requestType) { return this.extractSave(store, type, payload, id, requestType); }, /** `extractDeleteRecord` is a hook into the extract method used when a call is made to `DS.Store#deleteRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractDeleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractDeleteRecord: function(store, type, payload, id, requestType) { return this.extractSave(store, type, payload, id, requestType); }, /** `extractFind` is a hook into the extract method used when a call is made to `DS.Store#find`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFind @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractFind: function(store, type, payload, id, requestType) { return this.extractSingle(store, type, payload, id, requestType); }, /** `extractFindBelongsTo` is a hook into the extract method used when a call is made to `DS.Store#findBelongsTo`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFindBelongsTo @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractFindBelongsTo: function(store, type, payload, id, requestType) { return this.extractSingle(store, type, payload, id, requestType); }, /** `extractSave` is a hook into the extract method used when a call is made to `DS.Model#save`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractSave @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractSave: function(store, type, payload, id, requestType) { return this.extractSingle(store, type, payload, id, requestType); }, /** `extractSingle` is used to deserialize a single record returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractSingle: function(store, type, payload) { payload.comments = payload._embedded.comment; delete payload._embedded; return this._super(store, type, payload); }, }); ``` @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractSingle: function(store, type, payload, id, requestType) { payload = this.normalizePayload(payload); return this.normalize(type, payload); }, /** `extractArray` is used to deserialize an array of records returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractArray: function(store, type, payload) { return payload.map(function(json) { return this.extractSingle(store, type, json); }, this); } }); ``` @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractArray: function(store, type, arrayPayload, id, requestType) { var normalizedPayload = this.normalizePayload(arrayPayload); var serializer = this; return map.call(normalizedPayload, function(singlePayload) { return serializer.normalize(type, singlePayload); }); }, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractMeta: function(store, type, payload) { if (payload && payload._pagination) { store.metaForType(type, payload._pagination); delete payload._pagination; } } }); ``` @method extractMeta @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload */ extractMeta: function(store, type, payload) { if (payload && payload.meta) { store.metaForType(type, payload.meta); delete payload.meta; } }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```javascript App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @return {String} normalized key */ keyForAttribute: function(key){ return key; }, /** `keyForRelationship` can be used to define a custom key when serializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} relationship type @return {String} normalized key */ keyForRelationship: function(key, type){ return key; }, // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function(attributeType, skipAssertion) { var transform = this.container.lookup('transform:' + attributeType); Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform); return transform; } }); }); define("ember-data/serializers/rest_serializer", ["ember-data/serializers/json_serializer","ember-inflector/system/string","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var JSONSerializer = __dependency1__["default"]; var get = Ember.get; var set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; var map = Ember.ArrayPolyfills.map; var camelize = Ember.String.camelize; var singularize = __dependency2__.singularize; function coerceId(id) { return id == null ? null : id + ''; } /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method and individual normalizations under `normalizeHash`. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to define across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Parse, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, and the kind of relationship (`hasMany` or `belongsTo`) as the second parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ __exports__["default"] = JSONSerializer.extend({ /** If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, given the following json where the the `IDs` under `"comments"` are provided as `_id` instead of `id`. ```javascript { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "_id": 1, "body": "FIRST" }, { "_id": 2, "body": "Rails is unagi" }] } ``` You use `normalizeHash` to normalize just the comments: ```javascript App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is usually just the original key that was in the original payload. However, key names will be impacted by any modifications done in the `normalizePayload` method. The `DS.RESTSerializer`'s default implementation makes no changes to the payload keys. @property normalizeHash @type {Object} @default undefined */ /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```js App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is just the original key that was in the original payload. @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @return {Object} */ normalize: function(type, hash, prop) { this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); if (this.normalizeHash && this.normalizeHash[prop]) { this.normalizeHash[prop](hash); } this.applyTransforms(type, hash); return hash; }, /** Called when the server has returned a payload representing a single record, such as in response to a `find` or `save`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for post 1: ```js { "id": 1, "title": "Rails is omakase", "_embedded": { "comment": [{ "_id": 1, "comment_title": "FIRST" }, { "_id": 2, "comment_title": "Rails is unagi" }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type extractSingle: function(store, type, payload, id) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, type, payload, id); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractSingle`, the built-in implementation will find the primary record in your normalized payload and push the remaining records into the store. The primary record is the single hash found under `post` or the first element of the `posts` array. The primary record has special meaning when the record is being created for the first time or updated (`createRecord` or `updateRecord`). In particular, it will update the properties of the record that was saved. @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @param {String} recordId @return {Object} the primary response to the original request */ extractSingle: function(store, primaryType, rawPayload, recordId) { var payload = this.normalizePayload(rawPayload); var primaryTypeName = primaryType.typeKey; var primaryRecord; for (var prop in payload) { var typeName = this.typeForRoot(prop); var type = store.modelFor(typeName); var isPrimary = type.typeKey === primaryTypeName; var value = payload[prop]; // legacy support for singular resources if (isPrimary && Ember.typeOf(value) !== "array" ) { primaryRecord = this.normalize(primaryType, value, prop); continue; } /*jshint loopfunc:true*/ forEach.call(value, function(hash) { var typeName = this.typeForRoot(prop); var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); hash = typeSerializer.normalize(type, hash, prop); var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord; var isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first // record in the Array if (isFirstCreatedRecord || isUpdatedRecord) { primaryRecord = hash; } else { store.push(typeName, hash); } }, this); } return primaryRecord; }, /** Called when the server has returned a payload representing multiple records, such as in response to a `findAll` or `findQuery`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for all posts: ```js { "_embedded": { "post": [{ "id": 1, "title": "Rails is omakase" }, { "id": 2, "title": "The Parley Letter" }], "comment": [{ "_id": 1, "comment_title": "Rails is unagi" "post_id": 1 }, { "_id": 2, "comment_title": "Don't tread on me", "post_id": 2 }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type // and the comments are listed under a post's `comments` key. extractArray: function(store, type, payload) { var posts = payload._embedded.post; var comments = []; var postCache = {}; posts.forEach(function(post) { post.comments = []; postCache[post.id] = post; }); payload._embedded.comment.forEach(function(comment) { comments.push(comment); postCache[comment.post_id].comments.push(comment); delete comment.post_id; }); payload = { comments: comments, posts: payload }; return this._super(store, type, payload); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractArray`, the built-in implementation will find the primary array in your normalized payload and push the remaining records into the store. The primary array is the array found under `posts`. The primary record has special meaning when responding to `findQuery` or `findHasMany`. In particular, the primary array will become the list of records in the record array that kicked off the request. If your primary array contains secondary (embedded) records of the same type, you cannot place these into the primary array `posts`. Instead, place the secondary items into an underscore prefixed property `_posts`, which will push these items into the store and will not affect the resulting query. @method extractArray @param {DS.Store} store @param {subclass of DS.Model} primaryType @param {Object} payload @return {Array} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryType, rawPayload) { var payload = this.normalizePayload(rawPayload); var primaryTypeName = primaryType.typeKey; var primaryArray; for (var prop in payload) { var typeKey = prop; var forcedSecondary = false; if (prop.charAt(0) === '_') { forcedSecondary = true; typeKey = prop.substr(1); } var typeName = this.typeForRoot(typeKey); var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); var isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeName)); /*jshint loopfunc:true*/ var normalizedArray = map.call(payload[prop], function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); if (isPrimary) { primaryArray = normalizedArray; } else { store.pushMany(typeName, normalizedArray); } } return primaryArray; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function(store, rawPayload) { var payload = this.normalizePayload(rawPayload); for (var prop in payload) { var typeName = this.typeForRoot(prop); var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); /*jshint loopfunc:true*/ var normalizedArray = map.call(Ember.makeArray(payload[prop]), function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); store.pushMany(typeName, normalizedArray); } }, /** This method is used to convert each JSON root key in the payload into a typeKey that it can use to look up the appropriate model for that part of the payload. By default the typeKey for a model is its name in camelCase, so if your JSON root key is 'fast-car' you would use typeForRoot to convert it to 'fastCar' so that Ember Data finds the `FastCar` model. If you diverge from this norm you should also consider changes to store._normalizeTypeKey as well. For example, your server may return prefixed root keys like so: ```js { "response-fast-car": { "id": "1", "name": "corvette" } } ``` In order for Ember Data to know that the model corresponding to the 'response-fast-car' hash is `FastCar` (typeKey: 'fastCar'), you can override typeForRoot to convert 'response-fast-car' to 'fastCar' like so: ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ typeForRoot: function(root) { // 'response-fast-car' should become 'fast-car' var subRoot = root.substring(9); // _super normalizes 'fast-car' to 'fastCar' return this._super(subRoot); } }); ``` @method typeForRoot @param {String} key @return {String} the model's typeKey */ typeForRoot: function(key) { return camelize(singularize(key)); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```js App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapBy('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = this._super(record, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param record @param options */ serialize: function(record, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. By default the REST Serializer sends the typeKey of a model, whih is a camelized version of the name. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(hash, type, record, options) { hash[type.typeKey] = this.serialize(record, options); }, /** You can use this method to customize how polymorphic objects are serialized. By default the JSON Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; if (Ember.isNone(belongsTo)) { json[key + "Type"] = null; } else { json[key + "Type"] = Ember.String.camelize(belongsTo.constructor.typeKey); } } }); }); define("ember-data/setup-container", ["ember-data/initializers/store","ember-data/initializers/transforms","ember-data/initializers/store_injections","ember-data/initializers/data_adapter","activemodel-adapter/setup-container","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; var initializeStore = __dependency1__["default"]; var initializeTransforms = __dependency2__["default"]; var initializeStoreInjections = __dependency3__["default"]; var initializeDataAdapter = __dependency4__["default"]; var setupActiveModelContainer = __dependency5__["default"]; __exports__["default"] = function setupContainer(container, application){ // application is not a required argument. This ensures // testing setups can setup a container without booting an // entire ember application. initializeDataAdapter(container, application); initializeTransforms(container, application); initializeStoreInjections(container, application); initializeStore(container, application); setupActiveModelContainer(container, application); }; }); define("ember-data/system/adapter", ["exports"], function(__exports__) { "use strict"; /** @module ember-data */ var get = Ember.get; var set = Ember.set; var map = Ember.ArrayPolyfills.map; var errorProps = [ 'description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack' ]; /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. Example ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` The `DS.InvalidError` must be constructed with a single object whose keys are the invalid model properties, and whose values are the corresponding error messages. For example: ```javascript return new DS.InvalidError({ length: 'Must be less than 15', name: 'Must not be blank }); ``` @class InvalidError @namespace DS */ function InvalidError(errors) { var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors)); this.errors = errors; for (var i=0, l=errorProps.length; i<l; i++) { this[errorProps[i]] = tmp[errorProps[i]]; } } InvalidError.prototype = Ember.create(Error.prototype); /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter Create a new subclass of `DS.Adapter`, then assign it to the `ApplicationAdapter` property of the application. ```javascript var MyAdapter = DS.Adapter.extend({ // ...your code here }); App.ApplicationAdapter = MyAdapter; ``` Model-specific adapters can be created by assigning your adapter class to the `ModelName` + `Adapter` property of the application. ```javascript var MyPostAdapter = DS.Adapter.extend({ // ...Post-specific adapter code goes here }); App.PostAdapter = MyPostAdapter; ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `findQuery()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ var Adapter = Ember.Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority than a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```javascript var DjangoAdapter = DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `find` implementation: ```javascript App.ApplicationAdapter = DS.Adapter.extend({ find: function(store, type, id) { var url = [type.typeKey, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: Ember.required(Function), /** The `findAll()` method is called when you call `find` on the store without an ID (i.e. `store.find('post')`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var url = type; var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: null, /** This method is called when you call `find` on the store with a query object as the second parameter (i.e. `store.find('person', { page: 1 })`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findQuery: function(store, type, query) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript generateIdForRecord: function(store, record) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String|Number} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; // ... } }); ``` @method serialize @param {DS.Model} record @param {Object} options @return {Object} serialized record */ serialize: function(record, options) { return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'POST', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ createRecord: Ember.required(Function), /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ updateRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'PUT', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ updateRecord: Ember.required(Function), /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ deleteRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'DELETE', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ deleteRecord: Ember.required(Function), /** By default the store will try to coalesce all `fetchRecord` calls within the same runloop into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. You can opt out of this behaviour by either not implementing the findMany hook or by setting coalesceFindRequests to false @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: true, /** Find multiple records at once if coalesceFindRequests is true @method findMany @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the records @param {Array} ids @param {Array} records @return {Promise} promise */ /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. For example, if your api has nested URLs that depend on the parent, you will want to group records by their parent. The default implementation returns the records as a single group. @method groupRecordsForFindMany @param {Array} records @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, records) { return [records]; } }); __exports__.InvalidError = InvalidError; __exports__.Adapter = Adapter; __exports__["default"] = Adapter; }); define("ember-data/system/changes", ["ember-data/system/changes/relationship_change","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var RelationshipChange = __dependency1__.RelationshipChange; var RelationshipChangeAdd = __dependency1__.RelationshipChangeAdd; var RelationshipChangeRemove = __dependency1__.RelationshipChangeRemove; var OneToManyChange = __dependency1__.OneToManyChange; var ManyToNoneChange = __dependency1__.ManyToNoneChange; var OneToOneChange = __dependency1__.OneToOneChange; var ManyToManyChange = __dependency1__.ManyToManyChange; __exports__.RelationshipChange = RelationshipChange; __exports__.RelationshipChangeAdd = RelationshipChangeAdd; __exports__.RelationshipChangeRemove = RelationshipChangeRemove; __exports__.OneToManyChange = OneToManyChange; __exports__.ManyToNoneChange = ManyToNoneChange; __exports__.OneToOneChange = OneToOneChange; __exports__.ManyToManyChange = ManyToManyChange; }); define("ember-data/system/changes/relationship_change", ["ember-data/system/model/model","ember-data/system/relationship-meta","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var Model = __dependency1__["default"]; var isSyncRelationship = __dependency2__.isSyncRelationship; var get = Ember.get; var set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; /** @class RelationshipChange @namespace DS @private @constructor */ var RelationshipChange = function(options) { this.parentRecord = options.parentRecord; this.childRecord = options.childRecord; this.firstRecord = options.firstRecord; this.firstRecordKind = options.firstRecordKind; this.firstRecordName = options.firstRecordName; this.secondRecord = options.secondRecord; this.secondRecordKind = options.secondRecordKind; this.secondRecordName = options.secondRecordName; this.changeType = options.changeType; this.store = options.store; this.committed = {}; }; /** @class RelationshipChangeAdd @namespace DS @private @constructor */ function RelationshipChangeAdd(options){ RelationshipChange.call(this, options); } /** @class RelationshipChangeRemove @namespace DS @private @constructor */ function RelationshipChangeRemove(options){ RelationshipChange.call(this, options); } RelationshipChange.create = function(options) { return new RelationshipChange(options); }; RelationshipChangeAdd.create = function(options) { return new RelationshipChangeAdd(options); }; RelationshipChangeRemove.create = function(options) { return new RelationshipChangeRemove(options); }; var OneToManyChange = {}; var OneToNoneChange = {}; var ManyToNoneChange = {}; var OneToOneChange = {}; var ManyToManyChange = {}; RelationshipChange._createChange = function(options){ if (options.changeType === 'add') { return RelationshipChangeAdd.create(options); } if (options.changeType === 'remove') { return RelationshipChangeRemove.create(options); } }; RelationshipChange.determineRelationshipType = function(recordType, knownSide){ var knownKey = knownSide.key, key, otherKind; var knownKind = knownSide.kind; var inverse = recordType.inverseFor(knownKey); if (inverse) { key = inverse.name; otherKind = inverse.kind; } if (!inverse) { return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone'; } else { if (otherKind === 'belongsTo') { return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne'; } else { return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany'; } } }; RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){ // Get the type of the child based on the child's client ID var firstRecordType = firstRecord.constructor, changeType; changeType = RelationshipChange.determineRelationshipType(firstRecordType, options); if (changeType === 'oneToMany') { return OneToManyChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === 'manyToOne') { return OneToManyChange.createChange(secondRecord, firstRecord, store, options); } else if (changeType === 'oneToNone') { return OneToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === 'manyToNone') { return ManyToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === 'oneToOne') { return OneToOneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === 'manyToMany') { return ManyToManyChange.createChange(firstRecord, secondRecord, store, options); } }; OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, store: store, changeType: options.changeType, firstRecordName: key, firstRecordKind: 'belongsTo' }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = RelationshipChange._createChange({ parentRecord: childRecord, childRecord: parentRecord, secondRecord: childRecord, store: store, changeType: options.changeType, secondRecordName: options.key, secondRecordKind: 'hasMany' }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) { // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. var key = options.key; var change = RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: 'hasMany', secondRecordKind: 'hasMany', store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; OneToOneChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; } else if (options.key) { key = options.key; } else { Ember.assert('You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent', false); } var change = RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: 'belongsTo', secondRecordKind: 'belongsTo', store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; OneToOneChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === 'add' && store.recordIsMaterialized(childRecord)) { var oldParent = get(childRecord, key); if (oldParent) { var correspondingChange = OneToOneChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: 'remove', key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange); correspondingChange.sync(); } } }; OneToManyChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; OneToManyChange.maintainInvariant( options, store, childRecord, key ); } else if (options.key) { key = options.key; } else { Ember.assert('You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent', false); } var change = RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: 'belongsTo', secondRecordKind: 'hasMany', store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change); return change; }; OneToManyChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === 'add' && childRecord) { var oldParent = get(childRecord, key); if (oldParent) { var correspondingChange = OneToManyChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: 'remove', key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange); correspondingChange.sync(); } } }; /** @class RelationshipChange @namespace DS */ RelationshipChange.prototype = { getSecondRecordName: function() { var name = this.secondRecordName, parent; if (!name) { parent = this.secondRecord; if (!parent) { return; } var childType = this.firstRecord.constructor; var inverse = childType.inverseFor(this.firstRecordName); this.secondRecordName = inverse.name; } return this.secondRecordName; }, /** Get the name of the relationship on the belongsTo side. @method getFirstRecordName @return {String} */ getFirstRecordName: function() { return this.firstRecordName; }, /** @method destroy @private */ destroy: function() { var childRecord = this.childRecord; var belongsToName = this.getFirstRecordName(); var hasManyName = this.getSecondRecordName(); var store = this.store; store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType); }, getSecondRecord: function(){ return this.secondRecord; }, /** @method getFirstRecord @private */ getFirstRecord: function() { return this.firstRecord; }, coalesce: function(){ var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord); forEach(relationshipPairs, function(pair) { var addedChange = pair['add']; var removedChange = pair['remove']; if (addedChange && removedChange) { addedChange.destroy(); removedChange.destroy(); } }); } }; RelationshipChangeAdd.prototype = Ember.create(RelationshipChange.create({})); RelationshipChangeRemove.prototype = Ember.create(RelationshipChange.create({})); RelationshipChangeAdd.prototype.changeType = 'add'; RelationshipChangeAdd.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(); var firstRecordName = this.getFirstRecordName(); var firstRecord = this.getFirstRecord(); var secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof Model && firstRecord instanceof Model) { if (this.secondRecordKind === 'belongsTo') { secondRecord.suspendRelationshipObservers(function() { set(secondRecord, secondRecordName, firstRecord); }); } else if (this.secondRecordKind === 'hasMany' && isSyncRelationship(secondRecord, secondRecordName)) { secondRecord.suspendRelationshipObservers(function() { var relationship = get(secondRecord, secondRecordName); relationship.addObject(firstRecord); }); } } if (firstRecord instanceof Model && secondRecord instanceof Model && get(firstRecord, firstRecordName) !== secondRecord) { if (this.firstRecordKind === 'belongsTo') { firstRecord.suspendRelationshipObservers(function() { set(firstRecord, firstRecordName, secondRecord); }); } else if (this.firstRecordKind === 'hasMany' && isSyncRelationship(secondRecord, secondRecordName)) { firstRecord.suspendRelationshipObservers(function() { var relationship = get(firstRecord, firstRecordName); relationship.addObject(secondRecord); }); } } this.coalesce(); }; RelationshipChangeRemove.prototype.changeType = 'remove'; RelationshipChangeRemove.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(); var firstRecordName = this.getFirstRecordName(); var firstRecord = this.getFirstRecord(); var secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof Model && firstRecord instanceof Model) { if (this.secondRecordKind === 'belongsTo') { secondRecord.suspendRelationshipObservers(function() { set(secondRecord, secondRecordName, null); }); } else if (this.secondRecordKind === 'hasMany' && isSyncRelationship(secondRecord, secondRecordName)) { secondRecord.suspendRelationshipObservers(function() { var relationship = get(secondRecord, secondRecordName); relationship.removeObject(firstRecord); }); } } if (firstRecord instanceof Model && get(firstRecord, firstRecordName)) { if (this.firstRecordKind === 'belongsTo') { firstRecord.suspendRelationshipObservers(function() { set(firstRecord, firstRecordName, null); }); } else if (this.firstRecordKind === 'hasMany' && isSyncRelationship(firstRecord, firstRecordName)) { firstRecord.suspendRelationshipObservers(function() { var relationship = get(firstRecord, firstRecordName); relationship.removeObject(secondRecord); }); } } this.coalesce(); }; __exports__.RelationshipChange = RelationshipChange; __exports__.RelationshipChangeAdd = RelationshipChangeAdd; __exports__.RelationshipChangeRemove = RelationshipChangeRemove; __exports__.OneToManyChange = OneToManyChange; __exports__.ManyToNoneChange = ManyToNoneChange; __exports__.OneToOneChange = OneToOneChange; __exports__.ManyToManyChange = ManyToManyChange; }); define("ember-data/system/container_proxy", ["exports"], function(__exports__) { "use strict"; /** This is used internally to enable deprecation of container paths and provide a decent message to the user indicating how to fix the issue. @class ContainerProxy @namespace DS @private */ function ContainerProxy(container){ this.container = container; } ContainerProxy.prototype.aliasedFactory = function(path, preLookup) { var _this = this; return {create: function(){ if (preLookup) { preLookup(); } return _this.container.lookup(path); }}; }; ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) { var factory = this.aliasedFactory(dest, preLookup); return this.container.register(source, factory); }; ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) { var preLookupCallback = function(){ Ember.deprecate("You tried to look up '" + deprecated + "', " + "but this has been deprecated in favor of '" + valid + "'.", false); }; return this.registerAlias(deprecated, valid, preLookupCallback); }; ContainerProxy.prototype.registerDeprecations = function(proxyPairs) { var i, proxyPair, deprecated, valid, proxy; for (i = proxyPairs.length; i > 0; i--) { proxyPair = proxyPairs[i - 1]; deprecated = proxyPair['deprecated']; valid = proxyPair['valid']; this.registerDeprecation(deprecated, valid); } }; __exports__["default"] = ContainerProxy; }); define("ember-data/system/debug", ["ember-data/system/debug/debug_info","ember-data/system/debug/debug_adapter","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var DebugAdapter = __dependency2__["default"]; __exports__["default"] = DebugAdapter; }); define("ember-data/system/debug/debug_adapter", ["ember-data/system/model","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var Model = __dependency1__.Model; var get = Ember.get; var capitalize = Ember.String.capitalize; var underscore = Ember.String.underscore; /** Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ __exports__["default"] = Ember.DataAdapter.extend({ getFilters: function() { return [ { name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' } ]; }, detect: function(klass) { return klass !== Model && Model.detect(klass); }, columnsForType: function(type) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; get(type, 'attributes').forEach(function(name, meta) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function(type) { return this.get('store').all(type); }, getRecordColumnValues: function(record) { var self = this, count = 0; var columnValues = { id: get(record, 'id') }; record.eachAttribute(function(key) { if (count++ > self.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function(record) { var keywords = []; var keys = Ember.A(['id']); record.eachAttribute(function(key) { keys.push(key); }); keys.forEach(function(key) { keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function(record) { return { isNew: record.get('isNew'), isModified: record.get('isDirty') && !record.get('isNew'), isClean: !record.get('isDirty') }; }, getRecordColor: function(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('isDirty')) { color = 'blue'; } return color; }, observeRecord: function(record, recordUpdated) { var releaseMethods = Ember.A(), self = this; var keysToObserve = Ember.A(['id', 'isNew', 'isDirty']); record.eachAttribute(function(key) { keysToObserve.push(key); }); keysToObserve.forEach(function(key) { var handler = function() { recordUpdated(self.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function() { Ember.removeObserver(record, key, handler); }); }); var release = function() { releaseMethods.forEach(function(fn) { fn(); } ); }; return release; } }); }); define("ember-data/system/debug/debug_info", ["ember-data/system/model","exports"], function(__dependency1__, __exports__) { "use strict"; var Model = __dependency1__.Model; Model.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function() { var attributes = ['id'], relationships = { belongsTo: [], hasMany: [] }, expensiveProperties = []; this.eachAttribute(function(name, meta) { attributes.push(name); }, this); this.eachRelationship(function(name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [ { name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] } ]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); __exports__["default"] = Model; }); define("ember-data/system/model", ["ember-data/system/model/model","ember-data/system/model/attributes","ember-data/system/model/states","ember-data/system/model/errors","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; /** @module ember-data */ var Model = __dependency1__["default"]; var attr = __dependency2__["default"]; var RootState = __dependency3__["default"]; var Errors = __dependency4__["default"]; __exports__.Model = Model; __exports__.RootState = RootState; __exports__.attr = attr; __exports__.Errors = Errors; }); define("ember-data/system/model/attributes", ["ember-data/system/model/model","exports"], function(__dependency1__, __exports__) { "use strict"; var Model = __dependency1__["default"]; /** @module ember-data */ var get = Ember.get; /** @class Model @namespace DS */ Model.reopenClass({ /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); var attributes = Ember.get(App.Person, 'attributes') attributes.forEach(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id'); meta.name = name; map.set(name, meta); } }); return map; }).readOnly(), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); var transformedAttributes = Ember.get(App.Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachAttribute(function(key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }).readOnly(), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); App.Person.eachAttribute(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachAttribute: function(callback, binding) { get(this, 'attributes').forEach(function(name, meta) { callback.call(binding, name, meta); }, binding); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a string containing the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); App.Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachTransformedAttribute: function(callback, binding) { get(this, 'transformedAttributes').forEach(function(name, type) { callback.call(binding, name, type); }); } }); Model.reopen({ eachAttribute: function(callback, binding) { this.constructor.eachAttribute(callback, binding); } }); function getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue.apply(null, arguments); } else { return options.defaultValue; } } function hasValue(record, key) { return record._attributes.hasOwnProperty(key) || record._inFlightAttributes.hasOwnProperty(key) || record._data.hasOwnProperty(key); } function getValue(record, key) { if (record._attributes.hasOwnProperty(key)) { return record._attributes[key]; } else if (record._inFlightAttributes.hasOwnProperty(key)) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: `string`, `number`, `boolean` and `date`. You can define your own transforms by subclassing [DS.Transform](/api/data/classes/DS.Transform.html). Note that you cannot use `attr` to define an attribute of `id`. `DS.attr` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: Pass a string or a function to be called to set the attribute to a default value if none is supplied. Example ```javascript var attr = DS.attr; App.User = DS.Model.extend({ username: attr('string'), email: attr('string'), verified: attr('boolean', {defaultValue: false}) }); ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ __exports__["default"] = function attr(type, options) { options = options || {}; var meta = { type: type, isAttribute: true, options: options }; return Ember.computed('data', function(key, value) { if (arguments.length > 1) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id'); var oldValue = getValue(this, key); if (value !== oldValue) { // Add the new value to the changed attributes hash; it will get deleted by // the 'didSetProperty' handler if it is no different from the original value this._attributes[key] = value; this.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: this._data[key], value: value }); } return value; } else if (hasValue(this, key)) { return getValue(this, key); } else { return getDefaultValue(this, options, key); } // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).meta(meta); }; }); define("ember-data/system/model/errors", ["exports"], function(__exports__) { "use strict"; var get = Ember.get; var isEmpty = Ember.isEmpty; var map = Ember.EnumerableUtils.map; /** @module ember-data */ /** Holds validation errors for a given record organized by attribute names. Every DS.Model has an `errors` property that is an instance of `DS.Errors`. This can be used to display validation error messages returned from the server when a `record.save()` rejects. This works automatically with `DS.ActiveModelAdapter`, but you can implement [ajaxError](api/data/classes/DS.RESTAdapter.html#method_ajaxError) in other adapters as well. For Example, if you had an `User` model that looked like this: ```javascript App.User = DS.Model.extend({ username: attr('string'), email: attr('string') }); ``` And you attempted to save a record that did not validate on the backend. ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save(); ``` Your backend data store might return a response that looks like this. This response will be used to populate the error object. ```javascript { "errors": { "username": ["This username is already taken!"], "email": ["Doesn't look like a valid email."] } } ``` Errors can be displayed to the user by accessing their property name or using the `messages` property to get an array of all errors. ```handlebars {{#each errors.messages}} <div class="error"> {{message}} </div> {{/each}} <label>Username: {{input value=username}} </label> {{#each errors.username}} <div class="error"> {{message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each errors.email}} <div class="error"> {{message}} </div> {{/each}} ``` @class Errors @namespace DS @extends Ember.Object @uses Ember.Enumerable @uses Ember.Evented */ __exports__["default"] = Ember.Object.extend(Ember.Enumerable, Ember.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid */ registerHandlers: function(target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: Ember.reduceComputed("content", { initialValue: function() { return Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); }, addedItem: function(errors, error) { errors.get(error.attribute).pushObject(error); return errors; }, removedItem: function(errors, error) { errors.get(error.attribute).removeObject(error); return errors; } }), /** Returns errors for a given attribute ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save().catch(function(){ user.get('errors').errorsFor('email'); // ["Doesn't look like a valid email."] }); ``` @method errorsFor @param {String} attribute @return {Array} */ errorsFor: function(attribute) { return get(this, 'errorsByAttributeName').get(attribute); }, /** An array containing all of the error messages for this record. This is useful for displaying all errors to the user. ```handlebars {{#each errors.messages}} <div class="error"> {{message}} </div> {{/each}} ``` @property messages @type {Array} */ messages: Ember.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: Ember.computed(function() { return Ember.A(); }), /** @method unknownProperty @private */ unknownProperty: function(attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** @method nextObject @private */ nextObject: function(index, previousObject, context) { return get(this, 'content').objectAt(index); }, /** Total number of errors. @property length @type {Number} @readOnly */ length: Ember.computed.oneWay('content.length').readOnly(), /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: Ember.computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. Example: ```javascript if (!user.get('username') { user.get('errors').add('username', 'This field is required'); } ``` @method add @param {String} attribute @param {Array|String} messages */ add: function(attribute, messages) { var wasEmpty = get(this, 'isEmpty'); messages = this._findOrCreateMessages(attribute, messages); get(this, 'content').addObjects(messages); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function(attribute, messages) { var errors = this.errorsFor(attribute); return map(Ember.makeArray(messages), function(message) { return errors.findBy('message', message) || { attribute: attribute, message: message }; }); }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. Example: ```javascript App.User = DS.Model.extend({ email: DS.attr('string'), twoFactorAuth: DS.attr('boolean'), phone: DS.attr('string') }); App.UserEditRoute = Ember.Route.extend({ actions: { save: function(user) { if (!user.get('twoFactorAuth')) { user.get('errors').remove('phone'); } user.save(); } } }); ``` @method remove @param {String} attribute */ remove: function(attribute) { if (get(this, 'isEmpty')) { return; } var content = get(this, 'content').rejectBy('attribute', attribute); get(this, 'content').setObjects(content); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages and sends `becameValid` event to the record. Example: ```javascript App.UserEditRoute = Ember.Route.extend({ actions: { retrySave: function(user) { user.get('errors').clear(); user.save(); } } }); ``` @method clear */ clear: function() { if (get(this, 'isEmpty')) { return; } get(this, 'content').clear(); this.enumerableContentDidChange(); this.trigger('becameValid'); }, /** Checks if there is error messages for the given attribute. ```javascript App.UserEditRoute = Ember.Route.extend({ actions: { save: function(user) { if (user.get('errors').has('email')) { return alert('Please update your email before attempting to save.'); } user.save(); } } }); ``` @method has @param {String} attribute @return {Boolean} true if there some errors on given attribute */ has: function(attribute) { return !isEmpty(this.errorsFor(attribute)); } }); }); define("ember-data/system/model/model", ["ember-data/system/model/states","ember-data/system/model/errors","ember-data/system/store","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var RootState = __dependency1__["default"]; var Errors = __dependency2__["default"]; var PromiseObject = __dependency3__.PromiseObject; /** @module ember-data */ var get = Ember.get; var set = Ember.set; var merge = Ember.merge; var Promise = Ember.RSVP.Promise; var forEach = Ember.ArrayPolyfills.forEach; var JSONSerializer; var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) { return get(get(this, 'currentState'), key); }).readOnly(); var _extractPivotNameCache = Object.create(null); var _splitOnDotCache = Object.create(null); function splitOnDot(name) { return _splitOnDotCache[name] || ( _splitOnDotCache[name] = name.split('.') ); } function extractPivotName(name) { return _extractPivotNameCache[name] || ( _extractPivotNameCache[name] = splitOnDot(name)[0] ); } /** The model class that all Ember Data records descend from. @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ var Model = Ember.Object.extend(Ember.Evented, { _recordArrays: undefined, _relationships: undefined, _loadingRecordArrays: undefined, /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord('model'); record.get('isLoaded'); // true store.find('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord('model'); record.get('isDirty'); // true store.find('model', 1).then(function(model) { model.get('isDirty'); // false model.set('foo', 'some value'); model.get('isDirty'); // true }); ``` @property isDirty @type {Boolean} @readOnly */ isDirty: retrieveFromCurrentState, /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord('model'); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `isDirty` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `isDirty` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord('model'); record.get('isDeleted'); // false record.deleteRecord(); // Locally deleted record.get('isDeleted'); // true record.get('isDirty'); // true record.get('isSaving'); // false // Persisting the deletion var promise = record.save(); record.get('isDeleted'); // true record.get('isSaving'); // true // Deletion Persisted promise.then(function() { record.get('isDeleted'); // true record.get('isSaving'); // false record.get('isDirty'); // false }); ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord('model'); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord('model'); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error. Example ```javascript record.get('isError'); // false record.set('foo', 'valid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** The `clientId` property is a transient numerical identifier generated at runtime by the data store. It is important primarily because newly created objects may not yet have an externally generated id. @property clientId @private @type {Number|String} */ clientId: null, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord('model'); record.get('id'); // null store.find('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ currentState: RootState.empty, /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash typically contains keys corresponding to the invalid property names and values which are an array of error messages. ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().then(null, function() { record.get('errors').get('foo'); // ['foo should be a number.'] }); ``` @property errors @type {DS.Errors} */ errors: Ember.computed(function() { var errors = Errors.create(); errors.registerHandlers(this, function() { this.send('becameInvalid'); }, function() { this.send('becameValid'); }); return errors; }).readOnly(), /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function(options) { var store = get(this, 'store'); return store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @return {Object} A JSON representation of the object. */ toJSON: function(options) { if (!JSONSerializer) { JSONSerializer = requireModule("ember-data/serializers/json_serializer")["default"]; } // container is for lazy transform lookups var serializer = JSONSerializer.create({ container: this.container }); return serializer.serialize(this, options); }, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when the record is created. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, /** @property data @private @type {Object} */ data: Ember.computed(function() { this._data = this._data || {}; return this._data; }).readOnly(), _data: null, init: function() { this._super(); this._setup(); }, _setup: function() { this._changesToSync = {}; this._deferredTriggers = []; this._data = {}; this._attributes = {}; this._inFlightAttributes = {}; this._relationships = {}; }, /** @method send @private @param {String} name @param {Object} context */ send: function(name, context) { var currentState = get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct references to state objects var pivotName = extractPivotName(name); var currentState = get(this, 'currentState'); var state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = splitOnDot(name); var setups = [], enters = [], i, l; for (i=0, l=path.length; i<l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i=0, l=enters.length; i<l; i++) { enters[i].enter(this); } set(this, 'currentState', state); for (i=0, l=setups.length; i<l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, withTransaction: function(fn) { var transaction = get(this, 'transaction'); if (transaction) { fn(transaction); } }, /** @method loadingData @private @param {Promise} promise */ loadingData: function(promise) { this.send('loadingData', promise); }, /** @method loadedData @private */ loadedData: function() { this.send('loadedData'); }, /** @method notFound @private */ notFound: function() { this.send('notFound'); }, /** @method pushedData @private */ pushedData: function() { this.send('pushedData'); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollback()` a delete after it was made. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { softDelete: function() { this.controller.get('model').deleteRecord(); }, confirm: function() { this.controller.get('model').save(); }, undo: function() { this.controller.get('model').rollback(); } } }); ``` @method deleteRecord */ deleteRecord: function() { this.send('deleteRecord'); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; controller.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` @method destroyRecord @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function() { this.deleteRecord(); return this.save(); }, /** @method unloadRecord @private */ unloadRecord: function() { if (this.isDestroyed) { return; } this.send('unloadRecord'); }, /** @method clearRelationships @private */ clearRelationships: function() { this.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { set(this, name, null); } else if (relationship.kind === 'hasMany') { var hasMany = this._relationships[name]; if (hasMany) { // relationships are created lazily hasMany.destroy(); } } }, this); }, /** @method updateRecordArrays @private */ updateRecordArrays: function() { this._updatingRecordArraysLater = false; get(this, 'store').dataWasUpdated(this.constructor, this); }, /** When a find request is triggered on the store, the user can optionally passed in attributes and relationships to be preloaded. These are meant to behave as if they came back from the server, expect the user obtained them out of band and is informing the store of their existence. The most common use case is for supporting client side nested URLs, such as `/posts/1/comments/2` so the user can do `store.find('comment', 2, {post:1})` without having to fetch the post. Preloaded data can be attributes and relationships passed in either as IDs or as actual models. @method _preloadData @private @param {Object} preload */ _preloadData: function(preload) { var record = this; //TODO(Igor) consider the polymorphic case forEach.call(Ember.keys(preload), function(key) { var preloadValue = get(preload, key); var relationshipMeta = record.constructor.metaForProperty(key); if (relationshipMeta.isRelationship) { record._preloadRelationship(key, preloadValue); } else { get(record, '_data')[key] = preloadValue; } }); }, _preloadRelationship: function(key, preloadValue) { var relationshipMeta = this.constructor.metaForProperty(key); var type = relationshipMeta.type; if (relationshipMeta.kind === 'hasMany'){ this._preloadHasMany(key, preloadValue, type); } else { this._preloadBelongsTo(key, preloadValue, type); } }, _preloadHasMany: function(key, preloadValue, type) { Ember.assert("You need to pass in an array to set a hasMany property on a record", Ember.isArray(preloadValue)); var record = this; forEach.call(preloadValue, function(recordToPush) { recordToPush = record._convertStringOrNumberIntoRecord(recordToPush, type); get(record, key).pushObject(recordToPush); }); }, _preloadBelongsTo: function(key, preloadValue, type){ var recordToPush = this._convertStringOrNumberIntoRecord(preloadValue, type); set(this, key, recordToPush); }, _convertStringOrNumberIntoRecord: function(value, type) { if (Ember.typeOf(value) === 'string' || Ember.typeOf(value) === 'number'){ return this.store.recordForId(type, value); } return value; }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. Example ```javascript App.Mascot = DS.Model.extend({ name: attr('string') }); var person = store.createRecord('person'); person.changedAttributes(); // {} person.set('name', 'Tomster'); person.changedAttributes(); // {name: [undefined, 'Tomster']} ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var oldData = get(this, '_data'); var newData = get(this, '_attributes'); var diffData = {}; var prop; for (prop in newData) { diffData[prop] = [oldData[prop], newData[prop]]; } return diffData; }, /** @method adapterWillCommit @private */ adapterWillCommit: function() { this.send('willCommit'); }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function(data) { set(this, 'isError', false); if (data) { this._data = data; } else { Ember.mixin(this._data, this._inFlightAttributes); } this._inFlightAttributes = {}; this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, /** @method adapterDidDirty @private */ adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, dataDidChange: Ember.observer(function() { this.reloadHasManys(); }, 'data'), reloadHasManys: function() { var relationships = get(this.constructor, 'relationshipsByName'); this.updateRecordArraysLater(); relationships.forEach(function(name, relationship) { if (this._data.links && this._data.links[name]) { return; } if (relationship.kind === 'hasMany') { this.hasManyDidChange(relationship.key); } }, this); }, hasManyDidChange: function(key) { var hasMany = this._relationships[key]; if (hasMany) { var records = this._data[key] || []; set(hasMany, 'content', Ember.A(records)); set(hasMany, 'isLoaded', true); hasMany.trigger('didLoad'); } }, /** @method updateRecordArraysLater @private */ updateRecordArraysLater: function() { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; Ember.run.schedule('actions', this, this.updateRecordArrays); }, /** @method setupData @private @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ setupData: function(data, partial) { if (partial) { Ember.merge(this._data, data); } else { this._data = data; } var relationships = this._relationships; this.eachRelationship(function(name, rel) { if (data.links && data.links[name]) { return; } if (rel.options.async) { relationships[name] = null; } }); if (data) { this.pushedData(); } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, materializeId: function(id) { set(this, 'id', id); }, materializeAttributes: function(attributes) { Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes); merge(this._data, attributes); }, materializeAttribute: function(name, value) { this._data[name] = value; }, /** @method updateHasMany @private @param {String} name @param {Array} records */ updateHasMany: function(name, records) { this._data[name] = records; this.hasManyDidChange(name); }, /** @method updateBelongsTo @private @param {String} name @param {DS.Model} record */ updateBelongsTo: function(name, record) { this._data[name] = record; }, /** If the model `isDirty` this function will discard any unsaved changes Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollback(); record.get('name'); // 'Untitled Document' ``` @method rollback */ rollback: function() { this._attributes = {}; if (get(this, 'isError')) { this._inFlightAttributes = {}; set(this, 'isError', false); } if (!get(this, 'isValid')) { this._inFlightAttributes = {}; } this.send('rolledBack'); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, toStringExtension: function() { return get(this, 'id'); }, /** The goal of this method is to temporarily disable specific observers that take action in response to application changes. This allows the system to make changes (such as materialization and rollback) that should not trigger secondary behavior (such as setting an inverse relationship or marking records as dirty). The specific implementation will likely change as Ember proper provides better infrastructure for suspending groups of observers, and if Array observation becomes more unified with regular observers. @method suspendRelationshipObservers @private @param callback @param binding */ suspendRelationshipObservers: function(callback, binding) { var observers = get(this.constructor, 'relationshipNames').belongsTo; var self = this; try { this._suspendedRelationships = true; Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() { Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() { callback.call(binding || self); }); }); } finally { this._suspendedRelationships = false; } }, /** Save the record and persist any changes to the record to an extenal source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function(){ // Success callback }, function() { // Error callback }); ``` @method save @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function() { var promiseLabel = "DS: Model#save " + this; var resolver = Ember.RSVP.defer(promiseLabel); this.get('store').scheduleSave(this, resolver); this._inFlightAttributes = this._attributes; this._attributes = {}; return PromiseObject.create({ promise: resolver.promise }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). Example ```javascript App.ModelViewRoute = Ember.Route.extend({ actions: { reload: function() { this.controller.get('model').reload(); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function() { set(this, 'isReloading', true); var record = this; var promiseLabel = "DS: Model#reload of " + this; var promise = new Promise(function(resolve){ record.send('reloadRecord', resolve); }, promiseLabel).then(function() { record.set('isReloading', false); record.set('isError', false); return record; }, function(reason) { record.set('isError', true); throw reason; }, "DS: Model#reload complete, update flags"); return PromiseObject.create({ promise: promise }); }, // FOR USE DURING COMMIT PROCESS adapterDidUpdateAttribute: function(attributeName, value) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if (value !== undefined) { this._data[attributeName] = value; this.notifyPropertyChange(attributeName); } else { this._data[attributeName] = this._inFlightAttributes[attributeName]; } this.updateRecordArraysLater(); }, /** @method adapterDidInvalidate @private */ adapterDidInvalidate: function(errors) { var recordErrors = get(this, 'errors'); function addError(name) { if (errors[name]) { recordErrors.add(name, errors[name]); } } this.eachAttribute(addError); this.eachRelationship(addError); }, /** @method adapterDidError @private */ adapterDidError: function() { this.send('becameError'); set(this, 'isError', true); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param name */ trigger: function(name) { Ember.tryInvoke(this, name, [].slice.call(arguments, 1)); this._super.apply(this, arguments); }, triggerLater: function() { if (this._deferredTriggers.push(arguments) !== 1) { return; } Ember.run.schedule('actions', this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function() { for (var i=0, l= this._deferredTriggers.length; i<l; i++) { this.trigger.apply(this, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; }, willDestroy: function() { this._super(); this.clearRelationships(); }, // This is a temporary solution until we refactor DS.Model to not // rely on the data property. willMergeMixin: function(props) { Ember.assert('`data` is a reserved property name on DS.Model objects. Please choose a different property name for ' + this.constructor.toString(), !props.data); } }); Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); } }); __exports__["default"] = Model; }); define("ember-data/system/model/states", ["exports"], function(__exports__) { "use strict"; /** @module ember-data */ var get = Ember.get; var set = Ember.set; /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (This state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What that means is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [isDirty](DS.Model.html#property_isDirty) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ function hasDefinedProperties(object) { // Ignore internal property defined by simulated `Ember.create`. var names = Ember.keys(object); var i, l, name; for (i = 0, l = names.length; i < l; i++ ) { name = names[i]; if (object.hasOwnProperty(name) && object[name]) { return true; } } return false; } function didSetProperty(record, context) { if (context.value === context.originalValue) { delete record._attributes[context.name]; record.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { record.send('becomeDirty'); } record.updateRecordArraysLater(); } // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: The adapter did not report any server-side validation // failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: didSetProperty, //TODO(Igor) reloading now triggers a //loadingData event, though it seems fine? loadingData: Ember.K, propertyWasReset: function(record, name) { var stillDirty = false; for (var prop in record._attributes) { stillDirty = true; break; } if (!stillDirty) { record.send('rolledBack'); } }, pushedData: Ember.K, becomeDirty: Ember.K, willCommit: function(record) { record.transitionTo('inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, rolledBack: function(record) { record.transitionTo('loaded.saved'); }, becameInvalid: function(record) { record.transitionTo('invalid'); }, rollback: function(record) { record.rollback(); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: didSetProperty, becomeDirty: Ember.K, pushedData: Ember.K, unloadRecord: function(record) { Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + " `", false); }, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { var dirtyType = get(this, 'dirtyType'); record.transitionTo('saved'); record.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function(record) { record.transitionTo('invalid'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // A record is in the `invalid` if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, didSetProperty: function(record, context) { get(record, 'errors').remove(context.name); didSetProperty(record, context); }, becomeDirty: Ember.K, willCommit: function(record) { get(record, 'errors').clear(); record.transitionTo('inFlight'); }, rolledBack: function(record) { get(record, 'errors').clear(); }, becameValid: function(record) { record.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('becameInvalid', record); }, exit: function(record) { record._inFlightAttributes = {}; } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}, value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.uncommitted.rolledBack = function(record) { record.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); createdState.uncommitted.deleteRecord = function(record) { record.clearRelationships(); record.transitionTo('deleted.saved'); }; createdState.uncommitted.rollback = function(record) { DirtyState.uncommitted.rollback.apply(this, arguments); record.transitionTo('deleted.saved'); }; createdState.uncommitted.propertyWasReset = Ember.K; function assertAgainstUnloadRecord(record) { Ember.assert("You can only unload a record which is not inFlight. `" + Ember.inspect(record) + "`", false); } updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord; updatedState.uncommitted.deleteRecord = function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: Ember.K, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, propertyWasReset: Ember.K, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function(record, promise) { record._loadingPromise = promise; record.transitionTo('loading'); }, loadedData: function(record) { record.transitionTo('loaded.created.uncommitted'); record.suspendRelationshipObservers(function() { record.notifyPropertyChange('data'); }); }, pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); } }, // A record enters this state when the store asks // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function(record) { record._loadingPromise = null; }, // EVENTS pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); set(record, 'isError', false); }, becameError: function(record) { record.triggerLater('becameError', record); }, notFound: function(record) { record.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, //TODO(Igor) Reloading now triggers a loadingData event, //but it should be ok? loadingData: Ember.K, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function(record) { var attrs = record._attributes; var isDirty = false; for (var prop in attrs) { if (attrs.hasOwnProperty(prop)) { isDirty = true; break; } } if (isDirty) { record.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: Ember.K, becomeDirty: function(record) { record.transitionTo('updated.uncommitted'); }, willCommit: function(record) { record.transitionTo('updated.inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, didCommit: function(record) { record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: Ember.K }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(record) { record.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function(record) { record.transitionTo('inFlight'); }, rollback: function(record) { record.rollback(); }, becomeDirty: Ember.K, deleteRecord: Ember.K, rolledBack: function(record) { record.transitionTo('loaded.saved'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS unloadRecord: assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { record.transitionTo('saved'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function(record) { var store = get(record, 'store'); store.dematerializeRecord(record); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('didDelete', record); record.triggerLater('didCommit', record); }, willCommit: Ember.K, didCommit: Ember.K } }, invokeLifecycleCallbacks: function(record, dirtyType) { if (dirtyType === 'created') { record.triggerLater('didCreate', record); } else { record.triggerLater('didUpdate', record); } record.triggerLater('didCommit', record); } }; function wireState(object, parent, name) { /*jshint proto:true*/ // TODO: Use Object.create and copy instead object = mixin(parent ? Ember.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + "." + prop); } } return object; } RootState = wireState(RootState, null, "root"); __exports__["default"] = RootState; }); define("ember-data/system/record_array_manager", ["ember-data/system/record_arrays","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var RecordArray = __dependency1__.RecordArray; var FilteredRecordArray = __dependency1__.FilteredRecordArray; var AdapterPopulatedRecordArray = __dependency1__.AdapterPopulatedRecordArray; var ManyArray = __dependency1__.ManyArray; var get = Ember.get; var set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ __exports__["default"] = Ember.Object.extend({ init: function() { this.filteredRecordArrays = Ember.MapWithDefault.create({ defaultValue: function() { return []; } }); this.changedRecords = []; this._adapterPopulatedRecordArrays = []; }, recordDidChange: function(record) { if (this.changedRecords.push(record) !== 1) { return; } Ember.run.schedule('actions', this, this.updateRecordArrays); }, recordArraysForRecord: function(record) { record._recordArrays = record._recordArrays || Ember.OrderedSet.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function() { forEach(this.changedRecords, function(record) { if (get(record, 'isDeleted')) { this._recordWasDeleted(record); } else { this._recordWasChanged(record); } }, this); this.changedRecords.length = 0; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } forEach(recordArrays, function(array) { array.removeRecord(record); }); }, _recordWasChanged: function (record) { var type = record.constructor; var recordArrays = this.filteredRecordArrays.get(type); var filter; forEach(recordArrays, function(array) { filter = get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, record); }, this); // loop through all manyArrays containing an unloaded copy of this // clientId and notify them that the record was loaded. var manyArrays = record._loadingRecordArrays; if (manyArrays) { for (var i=0, l=manyArrays.length; i<l; i++) { manyArrays[i].loadedRecord(); } record._loadingRecordArrays = []; } }, /** Update an individual filter. @method updateRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, record) { var shouldBeInArray; if (!filter) { shouldBeInArray = true; } else { shouldBeInArray = filter(record); } var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { if (!recordArrays.has(array)) { array.pushRecord(record); recordArrays.add(array); } } else if (!shouldBeInArray) { recordArrays.remove(array); array.removeRecord(record); } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param array @param type @param filter */ updateFilter: function(array, type, filter) { var typeMap = this.store.typeMapFor(type); var records = typeMap.records, record; for (var i=0, l=records.length; i<l; i++) { record = records[i]; if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) { this.updateRecordArray(array, filter, type, record); } } }, /** Create a `DS.ManyArray` for a type and list of record references, and index the `ManyArray` under each reference. This allows us to efficiently remove records from `ManyArray`s when they are deleted. @method createManyArray @param {Class} type @param {Array} references @return {DS.ManyArray} */ createManyArray: function(type, records) { var manyArray = ManyArray.create({ type: type, content: records, store: this.store }); forEach(records, function(record) { var arrays = this.recordArraysForRecord(record); arrays.add(manyArray); }, this); return manyArray; }, /** Create a `DS.RecordArray` for a type and register it for updates. @method createRecordArray @param {Class} type @return {DS.RecordArray} */ createRecordArray: function(type) { var array = RecordArray.create({ type: type, content: Ember.A(), store: this.store, isLoaded: true }); this.registerFilteredRecordArray(array, type); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {Class} type @param {Function} filter @param {Object} query (optional @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function(type, filter, query) { var array = FilteredRecordArray.create({ query: query, type: type, content: Ember.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, type, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {Class} type @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function(type, query) { var array = AdapterPopulatedRecordArray.create({ type: type, query: query, content: Ember.A(), store: this.store, manager: this }); this._adapterPopulatedRecordArrays.push(array); return array; }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerFilteredRecordArray: function(array, type, filter) { var recordArrays = this.filteredRecordArrays.get(type); recordArrays.push(array); this.updateFilter(array, type, filter); }, // Internally, we maintain a map of all unloaded IDs requested by // a ManyArray. As the adapter loads data into the store, the // store notifies any interested ManyArrays. When the ManyArray's // total number of loading records drops to zero, it becomes // `isLoaded` and fires a `didLoad` event. registerWaitingRecordArray: function(record, array) { var loadingRecordArrays = record._loadingRecordArrays || []; loadingRecordArrays.push(array); record._loadingRecordArrays = loadingRecordArrays; }, willDestroy: function(){ this._super(); forEach(flatten(values(this.filteredRecordArrays.values)), destroy); forEach(this._adapterPopulatedRecordArrays, destroy); } }); function values(obj) { var result = []; var keys = Ember.keys(obj); for (var i = 0; i < keys.length; i++) { result.push(obj[keys[i]]); } return result; } function destroy(entry) { entry.destroy(); } function flatten(list) { var length = list.length; var result = Ember.A(); for (var i = 0; i < length; i++) { result = result.concat(list[i]); } return result; } }); define("ember-data/system/record_arrays", ["ember-data/system/record_arrays/record_array","ember-data/system/record_arrays/filtered_record_array","ember-data/system/record_arrays/adapter_populated_record_array","ember-data/system/record_arrays/many_array","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; /** @module ember-data */ var RecordArray = __dependency1__["default"]; var FilteredRecordArray = __dependency2__["default"]; var AdapterPopulatedRecordArray = __dependency3__["default"]; var ManyArray = __dependency4__["default"]; __exports__.RecordArray = RecordArray; __exports__.FilteredRecordArray = FilteredRecordArray; __exports__.AdapterPopulatedRecordArray = AdapterPopulatedRecordArray; __exports__.ManyArray = ManyArray; }); define("ember-data/system/record_arrays/adapter_populated_record_array", ["ember-data/system/record_arrays/record_array","exports"], function(__dependency1__, __exports__) { "use strict"; var RecordArray = __dependency1__["default"]; /** @module ember-data */ var get = Ember.get; var set = Ember.set; function cloneNull(source) { var clone = Object.create(null); for (var key in source) { clone[key] = source[key]; } return clone; } /** Represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the `AdapterPopulatedRecordArray`. @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray */ __exports__["default"] = RecordArray.extend({ query: null, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, /** @method load @private @param {Array} data */ load: function(data) { var store = get(this, 'store'); var type = get(this, 'type'); var records = store.pushMany(type, data); var meta = store.metadataFor(type); this.setProperties({ content: Ember.A(records), isLoaded: true, meta: cloneNull(meta) }); records.forEach(function(record) { this.manager.recordArraysForRecord(record).add(this); }, this); // TODO: should triggering didLoad event be the last action of the runLoop? Ember.run.once(this, 'trigger', 'didLoad'); } }); }); define("ember-data/system/record_arrays/filtered_record_array", ["ember-data/system/record_arrays/record_array","exports"], function(__dependency1__, __exports__) { "use strict"; var RecordArray = __dependency1__["default"]; /** @module ember-data */ var get = Ember.get; /** Represents a list of records whose membership is determined by the store. As records are created, loaded, or modified, the store evaluates them to determine if they should be part of the record array. @class FilteredRecordArray @namespace DS @extends DS.RecordArray */ __exports__["default"] = RecordArray.extend({ /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.all('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ filterFunction: null, isLoaded: true, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, /** @method updateFilter @private */ _updateFilter: function() { var manager = get(this, 'manager'); manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, updateFilter: Ember.observer(function() { Ember.run.once(this, this._updateFilter); }, 'filterFunction') }); }); define("ember-data/system/record_arrays/many_array", ["ember-data/system/record_arrays/record_array","ember-data/system/changes","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var RecordArray = __dependency1__["default"]; var RelationshipChange = __dependency2__.RelationshipChange; /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.EnumerableUtils.map; function sync(change) { change.sync(); } /** A `ManyArray` is a `RecordArray` that represents the contents of a has-many relationship. The `ManyArray` is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends DS.RecordArray */ __exports__["default"] = RecordArray.extend({ init: function() { this._super.apply(this, arguments); this._changesToSync = Ember.OrderedSet.create(); }, /** The property name of the relationship @property {String} name @private */ name: null, /** The record to which this relationship belongs. @property {DS.Model} owner @private */ owner: null, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, // LOADING STATE isLoaded: false, /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ promise: null, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, /** @method fetch @private */ fetch: function() { var records = get(this, 'content'); var store = get(this, 'store'); var owner = get(this, 'owner'); var unloadedRecords = records.filterBy('isEmpty', true); store.scheduleFetchMany(unloadedRecords, owner); }, // Overrides Ember.Array's replace method to implement replaceContent: function(index, removed, added) { // Map the array of record objects into an array of client ids. added = map(added, function(record) { Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to this relationship (only '" + this.type.typeKey + "' allowed)", !this.type || record instanceof this.type); return record; }, this); this._super(index, removed, added); }, arrangedContentDidChange: function() { Ember.run.once(this, 'fetch'); }, arrayContentWillChange: function(index, removed, added) { var owner = get(this, 'owner'); var name = get(this, 'name'); if (!owner._suspendedRelationships) { // This code is the first half of code that continues inside // of arrayContentDidChange. It gets or creates a change from // the child object, adds the current owner as the old // parent if this is the first time the object was removed // from a ManyArray, and sets `newParent` to null. // // Later, if the object is added to another ManyArray, // the `arrayContentDidChange` will set `newParent` on // the change. for (var i=index; i<index+removed; i++) { var record = get(this, 'content').objectAt(i); var change = RelationshipChange.createChange(owner, record, get(this, 'store'), { parentType: owner.constructor, changeType: "remove", kind: "hasMany", key: name }); this._changesToSync.add(change); } } return this._super.apply(this, arguments); }, arrayContentDidChange: function(index, removed, added) { this._super.apply(this, arguments); var owner = get(this, 'owner'); var name = get(this, 'name'); var store = get(this, 'store'); if (!owner._suspendedRelationships) { // This code is the second half of code that started in // `arrayContentWillChange`. It gets or creates a change // from the child object, and adds the current owner as // the new parent. for (var i=index; i<index+added; i++) { var record = get(this, 'content').objectAt(i); var change = RelationshipChange.createChange(owner, record, store, { parentType: owner.constructor, changeType: "add", kind:"hasMany", key: name }); change.hasManyName = name; this._changesToSync.add(change); } // We wait until the array has finished being // mutated before syncing the OneToManyChanges created // in arrayContentWillChange, so that the array // membership test in the sync() logic operates // on the final results. this._changesToSync.forEach(sync); this._changesToSync.clear(); } }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function(hash) { var owner = get(this, 'owner'); var store = get(owner, 'store'); var type = get(this, 'type'); var record; Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic')); record = store.createRecord.call(store, type, hash); this.pushObject(record); return record; } }); }); define("ember-data/system/record_arrays/record_array", ["ember-data/system/store","exports"], function(__dependency1__, __exports__) { "use strict"; /** @module ember-data */ var PromiseArray = __dependency1__.PromiseArray; var get = Ember.get; var set = Ember.set; /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of `DS.RecordArray` or its subclasses will be returned by your application's store in response to queries. @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented */ __exports__["default"] = Ember.ArrayProxy.extend(Ember.Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ content: null, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all('person'); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ isLoaded: false, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ isUpdating: false, /** The store that created this record array. @property store @private @type DS.Store */ store: null, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function(index) { var content = get(this, 'content'); return content.objectAt(index); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.all('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @method update */ update: function() { if (get(this, 'isUpdating')) { return; } var store = get(this, 'store'); var type = get(this, 'type'); return store.fetchAll(type, this); }, /** Adds a record to the `RecordArray` without duplicates @method addRecord @private @param {DS.Model} record */ addRecord: function(record) { get(this, 'content').addObject(record); }, /** Adds a record to the `RecordArray`, but allows duplicates @method pushRecord @private @param {DS.Model} record */ pushRecord: function(record) { get(this, 'content').pushObject(record); }, /** Removes a record to the `RecordArray`. @method removeRecord @private @param {DS.Model} record */ removeRecord: function(record) { get(this, 'content').removeObject(record); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.all('message'); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function() { var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) { return Ember.A(array); }, null, "DS: RecordArray#save apply Ember.NativeArray"); return PromiseArray.create({ promise: promise }); }, _dissociateFromOwnRecords: function() { var array = this; this.forEach(function(record){ var recordArrays = record._recordArrays; if (recordArrays) { recordArrays.remove(array); } }); }, willDestroy: function(){ this._dissociateFromOwnRecords(); this._super(); } }); }); define("ember-data/system/relationship-meta", ["ember-inflector/system","exports"], function(__dependency1__, __exports__) { "use strict"; var singularize = __dependency1__.singularize; function typeForRelationshipMeta(store, meta) { var typeKey, type; typeKey = meta.type || meta.key; if (typeof typeKey === 'string') { if (meta.kind === 'hasMany') { typeKey = singularize(typeKey); } type = store.modelFor(typeKey); } else { type = meta.type; } return type; } __exports__.typeForRelationshipMeta = typeForRelationshipMeta;function relationshipFromMeta(store, meta) { return { key: meta.key, kind: meta.kind, type: typeForRelationshipMeta(store, meta), options: meta.options, parentType: meta.parentType, isRelationship: true }; } __exports__.relationshipFromMeta = relationshipFromMeta;function isSyncRelationship(record, relationshipName) { var meta = Ember.meta(record); var desc = meta.descs[relationshipName]; return desc && !desc._meta.options.async; } __exports__.isSyncRelationship = isSyncRelationship; }); define("ember-data/system/relationships", ["./relationships/belongs_to","./relationships/has_many","ember-data/system/relationships/ext","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; /** @module ember-data */ var belongsTo = __dependency1__["default"]; var hasMany = __dependency2__["default"]; __exports__.belongsTo = belongsTo; __exports__.hasMany = hasMany; }); define("ember-data/system/relationships/belongs_to", ["ember-data/system/model","ember-data/system/store","ember-data/system/changes","ember-data/system/relationship-meta","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; var get = Ember.get; var set = Ember.set; var isNone = Ember.isNone; var Promise = Ember.RSVP.Promise; var Model = __dependency1__.Model; var PromiseObject = __dependency2__.PromiseObject; var RelationshipChange = __dependency3__.RelationshipChange; var relationshipFromMeta = __dependency4__.relationshipFromMeta; var typeForRelationshipMeta = __dependency4__.typeForRelationshipMeta; var isSyncRelationship = __dependency4__.isSyncRelationship; /** @module ember-data */ function asyncBelongsTo(type, options, meta) { return Ember.computed('data', function(key, value) { var data = get(this, 'data'); var store = get(this, 'store'); var promiseLabel = "DS: Async belongsTo " + this + " : " + key; var promise; meta.key = key; if (arguments.length === 2) { Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeForRelationshipMeta(store, meta)); return value === undefined ? null : PromiseObject.create({ promise: Promise.cast(value, promiseLabel) }); } var link = data.links && data.links[key]; var belongsTo = data[key]; if (!isNone(belongsTo)) { var inverse = this.constructor.inverseFor(key); //but for now only in the oneToOne case if (inverse && inverse.kind === 'belongsTo'){ set(belongsTo, inverse.name, this); } //TODO(Igor) after OR doesn't seem that will be called promise = store.findById(belongsTo.constructor, belongsTo.get('id')) || Promise.cast(belongsTo, promiseLabel); return PromiseObject.create({ promise: promise }); } else if (link) { promise = store.findBelongsTo(this, link, relationshipFromMeta(store, meta)); return PromiseObject.create({ promise: promise }); } else { return null; } }).meta(meta); } /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```javascript App.User = DS.Model.extend({ profile: DS.belongsTo('profile') }); App.Profile = DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` @namespace @method belongsTo @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ function belongsTo(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { Ember.assert("The first argument to DS.belongsTo must be a string representing a model type key, e.g. use DS.belongsTo('person') to define a relation to the App.Person model", !!type && (typeof type === 'string' || Model.detect(type))); } options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo', key: null }; if (options.async) { return asyncBelongsTo(type, options, meta); } return Ember.computed('data', function(key, value) { var data = get(this, 'data'); var store = get(this, 'store'); var belongsTo, typeClass; if (typeof type === 'string') { typeClass = store.modelFor(type); } else { typeClass = type; } if (arguments.length === 2) { Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass); return value === undefined ? null : value; } belongsTo = data[key]; if (isNone(belongsTo)) { return null; } store.findById(belongsTo.constructor, belongsTo.get('id')); return belongsTo; }).meta(meta); } /** These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. @class Model @namespace DS */ Model.reopen({ /** @method belongsToWillChange @private @static @param record @param key */ belongsToWillChange: Ember.beforeObserver(function(record, key) { if (get(record, 'isLoaded') && isSyncRelationship(record, key)) { var oldParent = get(record, key); if (oldParent) { var store = get(record, 'store'); var change = RelationshipChange.createChange(record, oldParent, store, { key: key, kind: 'belongsTo', changeType: 'remove' }); change.sync(); this._changesToSync[key] = change; } } }), /** @method belongsToDidChange @private @static @param record @param key */ belongsToDidChange: Ember.immediateObserver(function(record, key) { if (get(record, 'isLoaded')) { var newParent = get(record, key); if (newParent) { var store = get(record, 'store'); var change = RelationshipChange.createChange(record, newParent, store, { key: key, kind: 'belongsTo', changeType: 'add' }); change.sync(); } } delete this._changesToSync[key]; }) }); __exports__["default"] = belongsTo; }); define("ember-data/system/relationships/ext", ["ember-inflector/system","ember-data/system/relationship-meta","ember-data/system/model"], function(__dependency1__, __dependency2__, __dependency3__) { "use strict"; var singularize = __dependency1__.singularize; var typeForRelationshipMeta = __dependency2__.typeForRelationshipMeta; var relationshipFromMeta = __dependency2__.relationshipFromMeta; var Model = __dependency3__.Model; var get = Ember.get; var set = Ember.set; /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ Model.reopen({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param proto @param key @param value */ didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.ComputedProperty) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); if (meta.isRelationship && meta.kind === 'belongsTo') { Ember.addObserver(proto, key, null, 'belongsToDidChange'); Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); } meta.parentType = proto.constructor; } } }); /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ Model.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } var options = this.metaForProperty(name).options; if (options.inverse === null) { return null; } var inverseName, inverseKind, inverse; if (options.inverse) { inverseName = options.inverse; inverse = Ember.get(inverseType, 'relationshipsByName').get(inverseName); Ember.assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.typeKey + "' model. This is most likely due to a missing attribute on your model definition.", !Ember.isNone(inverse)); inverseKind = inverse.kind; } else { var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, possibleRelationships) { possibleRelationships = possibleRelationships || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type)); } if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: Ember.computed(function() { var map = new Ember.MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { meta.key = name; var relationshipsForType = map.get(typeForRelationshipMeta(this.store, meta)); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }).cacheable(false).readOnly(), /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: Ember.computed(function() { var type; var types = Ember.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = typeForRelationshipMeta(this.store, meta); Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type); if (!types.contains(type)) { Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type); types.push(type); } } }); return types; }).cacheable(false).readOnly(), /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; var relationship = relationshipFromMeta(this.store, meta); relationship.type = typeForRelationshipMeta(this.store, meta); map.set(name, relationship); } }); return map; }).cacheable(false).readOnly(), /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(field, kind) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }).readOnly(), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { get(this, 'relationshipsByName').forEach(function(name, relationship) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); } }); Model.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); } }); }); define("ember-data/system/relationships/has_many", ["ember-data/system/store","ember-data/system/relationship-meta","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /** @module ember-data */ var PromiseArray = __dependency1__.PromiseArray; var relationshipFromMeta = __dependency2__.relationshipFromMeta; var typeForRelationshipMeta = __dependency2__.typeForRelationshipMeta; var get = Ember.get; var set = Ember.set; var setProperties = Ember.setProperties; var map = Ember.EnumerableUtils.map; /** Returns a computed property that synchronously returns a ManyArray for this relationship. If not all of the records in this relationship are loaded, it will raise an exception. */ function syncHasMany(type, options, meta) { return Ember.computed('data', function(key) { return buildRelationship(this, key, options, function(store, data) { // Configure the metadata for the computed property to contain // the key. meta.key = key; var records = data[key]; Ember.assert("You looked up the '" + key + "' relationship on '" + this + "' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", Ember.A(records).isEvery('isEmpty', false)); return store.findMany(this, data[key], typeForRelationshipMeta(store, meta)); }); }).meta(meta).readOnly(); } /** Returns a computed property that itself returns a promise that resolves to a ManyArray. */ function asyncHasMany(type, options, meta) { return Ember.computed('data', function(key) { // Configure the metadata for the computed property to contain // the key. meta.key = key; var relationship = buildRelationship(this, key, options, function(store, data) { var link = data.links && data.links[key]; var rel; var promiseLabel = "DS: Async hasMany " + this + " : " + key; var resolver = Ember.RSVP.defer(promiseLabel); if (link) { rel = store.findHasMany(this, link, relationshipFromMeta(store, meta), resolver); } else { //This is a temporary workaround for setting owner on the relationship //until single source of truth lands. It only works for OneToMany atm var records = data[key]; var inverse = this.constructor.inverseFor(key); var owner = this; if (inverse && records) { if (inverse.kind === 'belongsTo'){ map(records, function(record){ set(record, inverse.name, owner); }); } } rel = store.findMany(owner, data[key], typeForRelationshipMeta(store, meta), resolver); } // Cache the promise so we can use it when we come back and don't // need to rebuild the relationship. set(rel, 'promise', resolver.promise); return rel; }); var promise = relationship.get('promise').then(function() { return relationship; }, null, "DS: Async hasMany records received"); return PromiseArray.create({ promise: promise }); }).meta(meta).readOnly(); } /* Builds the ManyArray for a relationship using the provided callback, but only if it had not been created previously. After building, it sets some metadata on the created ManyArray, such as the record which owns it and the name of the relationship. */ function buildRelationship(record, key, options, callback) { var rels = record._relationships; if (rels[key]) { return rels[key]; } var data = get(record, 'data'); var store = get(record, 'store'); var relationship = rels[key] = callback.call(record, store, data); return setProperties(relationship, { owner: record, name: key, isPolymorphic: options.polymorphic }); } /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```javascript App.Post = DS.Model.extend({ tags: DS.hasMany('tag') }); App.Tag = DS.Model.extend({ posts: DS.hasMany('post') }); ``` #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasManys` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```javascript var belongsTo = DS.belongsTo, hasMany = DS.hasMany; App.Comment = DS.Model.extend({ onePost: belongsTo('post'), twoPost: belongsTo('post'), redPost: belongsTo('post'), bluePost: belongsTo('post') }); App.Post = DS.Model.extend({ comments: hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ function hasMany(type, options) { if (typeof type === 'object') { options = type; type = undefined; } options = options || {}; // Metadata about relationships is stored on the meta of // the relationship. This is used for introspection and // serialization. Note that `key` is populated lazily // the first time the CP is called. var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany', key: null }; if (options.async) { return asyncHasMany(type, options, meta); } else { return syncHasMany(type, options, meta); } } __exports__["default"] = hasMany; }); define("ember-data/system/store", ["ember-data/system/adapter","ember-inflector/system/string","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*globals Ember*/ /*jshint eqnull:true*/ /** @module ember-data */ var InvalidError = __dependency1__.InvalidError; var Adapter = __dependency1__.Adapter; var singularize = __dependency2__.singularize; var get = Ember.get; var set = Ember.set; var once = Ember.run.once; var isNone = Ember.isNone; var forEach = Ember.EnumerableUtils.forEach; var indexOf = Ember.EnumerableUtils.indexOf; var map = Ember.EnumerableUtils.map; var Promise = Ember.RSVP.Promise; var copy = Ember.copy; var Store, PromiseObject, PromiseArray, RecordArrayManager, Model; var camelize = Ember.String.camelize; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +reference+ means a record reference object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. function coerceId(id) { return id == null ? null : id+''; } /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```javascript MyApp.Store = DS.Store.extend(); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `find()` method: ```javascript store.find('person', 123).then(function (person) { }); ``` If your application has multiple `DS.Store` instances (an unusual case), you can specify which store should be used: ```javascript store.find('person', 123).then(function (person) { }); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```javascript MyApp.ApplicationAdapter = MyApp.CustomAdapter ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. ### Store createRecord() vs. push() vs. pushPayload() vs. update() The store provides multiple ways to create new record objects. They have some subtle differences in their use which are detailed below: [createRecord](#method_createRecord) is used for creating new records on the client side. This will return a new record in the `created.uncommitted` state. In order to persist this record to the backend you will need to call `record.save()`. [push](#method_push) is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the `loaded.saved` state. The primary use-case for `store#push` is to notify Ember Data about record updates that happen outside of the normal adapter methods (for example [SSE](http://dev.w3.org/html5/eventsource/) or [Web Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). [pushPayload](#method_pushPayload) is a convenience wrapper for `store#push` that will deserialize payloads if the Serializer implements a `pushPayload` method. [update](#method_update) works like `push`, except it can handle partial attributes without overwriting the existing record properties. Note: When creating a new record using any of the above methods Ember Data will update `DS.RecordArray`s such as those returned by `store#all()`, `store#findAll()` or `store#filter()`. This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values. @class Store @namespace DS @extends Ember.Object */ Store = Ember.Object.extend({ /** @method init @private */ init: function() { // internal bookkeeping; not observable if (!RecordArrayManager) { RecordArrayManager = requireModule("ember-data/system/record_array_manager")["default"]; } this.typeMaps = {}; this.recordArrayManager = RecordArrayManager.create({ store: this }); this._relationshipChanges = {}; this._pendingSave = []; //Used to keep track of all the find requests that need to be coalesced this._pendingFetch = Ember.Map.create(); }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `App.CustomAdapter` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.RESTAdapter @type {DS.Adapter|String} */ adapter: '-rest', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { return this.serializerFor(record.constructor.typeKey).serialize(record, options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @return DS.Adapter */ defaultAdapter: Ember.computed('adapter', function() { var adapter = get(this, 'adapter'); Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof Adapter)); if (typeof adapter === 'string') { adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:-rest'); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create({ container: this.container }); } return adapter; }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of `App.Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` @method createRecord @param {String} type @param {Object} properties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function(typeName, inputProperties) { var type = this.modelFor(typeName); var properties = copy(inputProperties) || {}; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(type); } // Coerce ID to a string properties.id = coerceId(properties.id); var record = this.buildRecord(type, properties.id); // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); // Set the properties specified on the record. record.setProperties(properties); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} type @return {String} if the adapter can generate one, an ID */ _generateId: function(type) { var adapter = this.adapterFor(type); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript var post = store.createRecord('post', { title: "Rails is omakase" }); store.deleteRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.find('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is the model's name as a string. --- To find a record by ID, pass the `id` as the second parameter: ```javascript store.find('person', 1); ``` The `find` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `find` method will always resolve its promise with the same object for a given type and `id`. --- You can optionally preload specific attributes and relationships that you know of by passing them as the third argument to find. For example, if your Ember route looks like `/posts/1/comments/2` and you API route for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment without fetching the post you can pass in the post to the `find` call: ```javascript store.find('comment', 2, {post: 1}); ``` If you have access to the post model you can also pass the model itself: ```javascript store.find('post', 1).then(function (myPostModel) { store.find('comment', 2, {post: myPostModel}); }); ``` This way, your adapter's `find` or `buildURL` method will be able to look up the relationship on the record and construct the nested URL without having to first fetch the post. --- To find all records for a type, call `find` with no additional parameters: ```javascript store.find('person'); ``` This will ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. --- To find a record by a query, call `find` with a hash as the second parameter: ```javascript store.find('person', { page: 1 }); ``` This will ask the adapter's `findQuery` method to find the records for the query, and return a promise that will be resolved once the server responds. @method find @param {String or subclass of DS.Model} type @param {Object|String|Integer|null} id @return {Promise} promise */ find: function(type, id, preload) { Ember.assert("You need to pass a type to the store's find method", arguments.length >= 1); Ember.assert("You may not pass `" + id + "` as id to the store's find method", arguments.length === 1 || !Ember.isNone(id)); if (arguments.length === 1) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, coerceId(id), preload); }, /** This method returns a record for a given type and id combination. @method findById @private @param {String or subclass of DS.Model} type @param {String|Integer} id @return {Promise} promise */ findById: function(typeName, id, preload) { var fetchedRecord; var type = this.modelFor(typeName); var record = this.recordForId(type, id); if (preload) { record._preloadData(preload); } if (get(record, 'isEmpty')) { fetchedRecord = this.scheduleFetch(record); //TODO double check about reloading } else if (get(record, 'isLoading')){ fetchedRecord = record._loadingPromise; } return promiseObject(fetchedRecord || record, "DS: Store#findById " + type + " with id: " + id); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} type @param {Array} ids @return {Promise} promise */ findByIds: function(type, ids) { var store = this; var promiseLabel = "DS: Store#findByIds " + type; return promiseArray(Ember.RSVP.all(map(ids, function(id) { return store.findById(type, id); })).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete")); }, /** This method is called by `findById` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {DS.Model} record @return {Promise} promise */ fetchRecord: function(record) { var type = record.constructor; var id = get(record, 'id'); var adapter = this.adapterFor(type); Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", adapter.find); var promise = _find(adapter, this, type, id, record); return promise; }, scheduleFetchMany: function(records) { return Ember.RSVP.all(map(records, this.scheduleFetch, this)); }, scheduleFetch: function(record) { var type = record.constructor; if (isNone(record)) { return null; } if (record._loadingPromise) { return record._loadingPromise; } var resolver = Ember.RSVP.defer('Fetching ' + type + 'with id: ' + record.get('id')); var recordResolverPair = { record: record, resolver: resolver }; var promise = resolver.promise; record.loadingData(promise); if (!this._pendingFetch.get(type)){ this._pendingFetch.set(type, [recordResolverPair]); } else { this._pendingFetch.get(type).push(recordResolverPair); } Ember.run.scheduleOnce('afterRender', this, this.flushAllPendingFetches); return promise; }, flushAllPendingFetches: function(){ if (this.isDestroyed || this.isDestroying) { return; } this._pendingFetch.forEach(this._flushPendingFetchForType, this); this._pendingFetch = Ember.Map.create(); }, _flushPendingFetchForType: function (type, recordResolverPairs) { var store = this; var adapter = store.adapterFor(type); var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; var records = Ember.A(recordResolverPairs).mapBy('record'); var resolvers = Ember.A(recordResolverPairs).mapBy('resolver'); function _fetchRecord(recordResolverPair) { recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record)); } function resolveFoundRecords(records) { forEach(records, function(record){ var pair = Ember.A(recordResolverPairs).findBy('record', record); if (pair){ var resolver = pair.resolver; resolver.resolve(record); } }); } function makeMissingRecordsRejector(requestedRecords) { return function rejectMissingRecords(resolvedRecords) { var missingRecords = requestedRecords.without(resolvedRecords); rejectRecords(missingRecords); }; } function makeRecordsRejector(records) { return function (error) { rejectRecords(records, error); }; } function rejectRecords(records, error) { forEach(records, function(record){ var pair = Ember.A(recordResolverPairs).findBy('record', record); if (pair){ var resolver = pair.resolver; resolver.reject(error); } }); } if (recordResolverPairs.length === 1) { _fetchRecord(recordResolverPairs[0]); } else if (shouldCoalesce) { var groups = adapter.groupRecordsForFindMany(this, records); forEach(groups, function (groupOfRecords) { var requestedRecords = Ember.A(groupOfRecords); var ids = requestedRecords.mapBy('id'); if (ids.length > 1) { _findMany(adapter, store, type, ids, requestedRecords). then(resolveFoundRecords). then(makeMissingRecordsRejector(requestedRecords)). then(null, makeRecordsRejector(requestedRecords)); } else if (ids.length === 1) { var pair = Ember.A(recordResolverPairs).findBy('record', groupOfRecords[0]); _fetchRecord(pair); } else { Ember.assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false); } }); } else { forEach(recordResolverPairs, _fetchRecord); } }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it is available in the store, otherwise it will return `null`. A record is available if it has been fetched earlier, or pushed manually into the store. _Note: This is an synchronous method and does not return a promise._ ```js var post = store.getById('post', 1); post.get('id'); // 1 ``` @method getById @param {String or subclass of DS.Model} type @param {String|Integer} id @return {DS.Model|null} record */ getById: function(type, id) { if (this.hasRecordForId(type, id)) { return this.recordForId(type, id); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} record @return {Promise} promise */ reloadRecord: function(record) { var type = record.constructor; var adapter = this.adapterFor(type); var id = get(record, 'id'); Ember.assert("You cannot reload a record without an ID", id); Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to reload a record but your adapter does not implement `find`", adapter.find); return this.scheduleFetch(record); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {String or subclass of DS.Model} type @param {String|Integer} id @return {Boolean} */ hasRecordForId: function(typeName, inputId) { var type = this.modelFor(typeName); var id = coerceId(inputId); return !!this.typeMapFor(type).idToRecord[id]; }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String or subclass of DS.Model} type @param {String|Integer} id @return {DS.Model} record */ recordForId: function(typeName, inputId) { var type = this.modelFor(typeName); var id = coerceId(inputId); var idToRecord = this.typeMapFor(type).idToRecord; var record = idToRecord[id]; if (!record || !idToRecord[id]) { record = this.buildRecord(type, id); } return record; }, /** @method findMany @private @param {DS.Model} owner @param {Array} records @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} records */ findMany: function(owner, inputRecords, typeName, resolver) { var type = this.modelFor(typeName); var records = Ember.A(inputRecords); var unloadedRecords = records.filterProperty('isEmpty', true); var manyArray = this.recordArrayManager.createManyArray(type, records); manyArray.loadingRecordsCount = unloadedRecords.length; if (unloadedRecords.length) { forEach(unloadedRecords, function(record) { this.recordArrayManager.registerWaitingRecordArray(record, manyArray); }, this); resolver.resolve(this.scheduleFetchMany(unloadedRecords, owner)); } else { if (resolver) { resolver.resolve(); } manyArray.set('isLoaded', true); once(manyArray, 'trigger', 'didLoad'); } return manyArray; }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {String or subclass of DS.Model} type @return {Promise} promise */ findHasMany: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", adapter.findHasMany); var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([])); resolver.resolve(_findHasMany(adapter, this, owner, link, relationship)); return records; }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @return {Promise} promise */ findBelongsTo: function(owner, link, relationship) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", adapter.findBelongsTo); return _findBelongsTo(adapter, this, owner, link, relationship); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. This method returns a promise, which is resolved with a `RecordArray` once the server returns. @method findQuery @private @param {String or subclass of DS.Model} type @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ findQuery: function(typeName, query) { var type = this.modelFor(typeName); var array = this.recordArrayManager .createAdapterPopulatedRecordArray(type, query); var adapter = this.adapterFor(type); Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery); return promiseArray(_findQuery(adapter, this, type, query, array)); }, /** This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @method findAll @private @param {String or subclass of DS.Model} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(typeName) { var type = this.modelFor(typeName); return this.fetchAll(type, this.all(type)); }, /** @method fetchAll @private @param {DS.Model} type @param {DS.RecordArray} array @return {Promise} promise */ fetchAll: function(type, array) { var adapter = this.adapterFor(type); var sinceToken = this.typeMapFor(type).metadata.since; set(array, 'isUpdating', true); Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll); return promiseArray(_findAll(adapter, this, type, sinceToken)); }, /** @method didUpdateAll @param {DS.Model} type */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type. Note that because it's just a filter, it will have any locally created records of the type. Also note that multiple calls to `all` for a given type will always return the same RecordArray. Example ```javascript var localPosts = store.all('post'); ``` @method all @param {String or subclass of DS.Model} type @return {DS.RecordArray} */ all: function(typeName) { var type = this.modelFor(typeName); var typeMap = this.typeMapFor(type); var findAllCache = typeMap.findAllCache; if (findAllCache) { return findAllCache; } var array = this.recordArrayManager.createRecordArray(type); typeMap.findAllCache = array; return array; }, /** This method unloads all of the known records for a given type. ```javascript store.unloadAll('post'); ``` @method unloadAll @param {String or subclass of DS.Model} type */ unloadAll: function(type) { var modelType = this.modelFor(type); var typeMap = this.typeMapFor(modelType); var records = typeMap.records.slice(); var record; for (var i = 0; i < records.length; i++) { record = records[i]; record.unloadRecord(); record.destroy(); // maybe within unloadRecord } typeMap.findAllCache = null; }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query which will be triggered at first. The results returned by the server could then appear in the filter if they match the filter function. Example ```javascript store.filter('post', {unread: true}, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 var unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @param {String or subclass of DS.Model} type @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} */ filter: function(type, query, filter) { var promise; var length = arguments.length; var array; var hasQuery = length === 3; // allow an optional server query if (hasQuery) { promise = this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } type = this.modelFor(type); if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(type, filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(type, filter); } promise = promise || Promise.cast(array); return promiseArray(promise.then(function() { return array; }, null, "DS: Store#filter of " + type)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded('post', 1); // false store.find('post', 1).then(function() { store.recordIsLoaded('post', 1); // true }); ``` @method recordIsLoaded @param {String or subclass of DS.Model} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { if (!this.hasRecordForId(type, id)) { return false; } return !get(this.recordForId(type, id), 'isEmpty'); }, /** This method returns the metadata for a specific type. @method metadataFor @param {String or subclass of DS.Model} type @return {object} */ metadataFor: function(type) { type = this.modelFor(type); return this.typeMapFor(type).metadata; }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {DS.Model} record */ dataWasUpdated: function(type, record) { this.recordArrayManager.recordDidChange(record); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {DS.Model} record @param {Resolver} resolver */ scheduleSave: function(record, resolver) { record.adapterWillCommit(); this._pendingSave.push([record, resolver]); once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function() { var pending = this._pendingSave.slice(); this._pendingSave = []; forEach(pending, function(tuple) { var record = tuple[0], resolver = tuple[1]; var adapter = this.adapterFor(record.constructor); var operation; if (get(record, 'currentState.stateName') === 'root.deleted.saved') { return resolver.resolve(record); } else if (get(record, 'isNew')) { operation = 'createRecord'; } else if (get(record, 'isDeleted')) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, this, operation, record)); }, this); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { if (data) { // normalize relationship IDs into records data = normalizeRelationships(this, record.constructor, data, record); this.updateId(record, data); } record.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var oldId = get(record, 'id'); var id = coerceId(data.id); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); this.typeMapFor(record.constructor).idToRecord[id] = record; set(record, 'id', id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param type @return {Object} typeMap */ typeMapFor: function(type) { var typeMaps = get(this, 'typeMaps'); var guid = Ember.guidFor(type); var typeMap; typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: Object.create(null), records: [], metadata: Object.create(null), type: type }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {String or subclass of DS.Model} type @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ _load: function(type, data, partial) { var id = coerceId(data.id); var record = this.recordForId(type, id); record.setupData(data, partial); this.recordArrayManager.recordDidChange(record); return record; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String or subclass of DS.Model} key @return {subclass of DS.Model} */ modelFor: function(key) { var factory; if (typeof key === 'string') { var normalizedKey = this.container.normalize('model:' + key); factory = this.container.lookupFactory(normalizedKey); if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); } factory.typeKey = this._normalizeTypeKey(normalizedKey.split(':', 2)[1]); } else { // A factory already supplied. Ensure it has a normalized key. factory = key; if (factory.typeKey) { factory.typeKey = this._normalizeTypeKey(factory.typeKey); } } factory.store = this; return factory; }, /** Push some data for a given type into the store. This method expects normalized data: * The ID is a key named `id` (an ID is mandatory) * The names of attributes are the ones you used in your model's `DS.attr`s. * Your relationships must be: * represented as IDs or Arrays of IDs * represented as model instances * represented as URLs, under the `links` key For this model: ```js App.Person = DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } ``` To represent the children relationship as a URL: ```js { id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/people/1/children" } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. This method can be used both to push in brand new records, as well as to update existing records. @method push @param {String or subclass of DS.Model} type @param {Object} data @return {DS.Model} the record that was created or updated. */ push: function(typeName, data, _partial) { // _partial is an internal param used by `update`. // If passed, it means that the data should be // merged into the existing data, not replace it. Ember.assert("You must include an `id` for " + typeName+ " in a hash passed to `push`", data.id != null); var type = this.modelFor(typeName); // normalize relationship IDs into records data = normalizeRelationships(this, type, data); this._load(type, data, _partial); return this.recordForId(type, data.id); }, /** Push some raw data into the store. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; var pushData = { posts: [ {id: 1, post_title: "Great post", comment_ids: [2]} ], comments: [ {id: 2, comment_body: "Insightful comment"} ] } store.pushPayload(pushData); ``` By default, the data will be deserialized using a default serializer (the application serializer if it exists). Alternatively, `pushPayload` will accept a model type which will determine which serializer will process the payload. However, the serializer itself (processing this data via `normalizePayload`) will not know which model it is deserializing. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; App.PostSerializer = DS.JSONSerializer; store.pushPayload('comment', pushData); // Will use the ApplicationSerializer store.pushPayload('post', pushData); // Will use the PostSerializer ``` @method pushPayload @param {String} type Optionally, a model used to determine which serializer will be used @param {Object} payload */ pushPayload: function (type, inputPayload) { var serializer; var payload; if (!inputPayload) { payload = type; serializer = defaultSerializer(this.container); Ember.assert("You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`", serializer.pushPayload); } else { payload = inputPayload; serializer = this.serializerFor(type); } serializer.pushPayload(this, payload); }, /** `normalize` converts a json payload into the normalized form that [push](#method_push) expects. Example ```js socket.on('message', function(message) { var modelName = message.model; var data = message.data; store.push(modelName, store.normalize(modelName, data)); }); ``` @method normalize @param {String} The name of the model type for this payload @param {Object} payload @return {Object} The normalized payload */ normalize: function (type, payload) { var serializer = this.serializerFor(type); var model = this.modelFor(type); return serializer.normalize(model, payload); }, /** Update existing records in the store. Unlike [push](#method_push), update will merge the new data properties with the existing properties. This makes it safe to use with a subset of record attributes. This method expects normalized data. `update` is useful if your app broadcasts partial updates to records. ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string') }); store.get('person', 1).then(function(tom) { tom.get('firstName'); // Tom tom.get('lastName'); // Dale var updateEvent = {id: 1, firstName: "TomHuda"}; store.update('person', updateEvent); tom.get('firstName'); // TomHuda tom.get('lastName'); // Dale }); ``` @method update @param {String} type @param {Object} data @return {DS.Model} the record that was updated. */ update: function(type, data) { Ember.assert("You must include an `id` for " + type + " in a hash passed to `update`", data.id != null); return this.push(type, data, true); }, /** If you have an Array of normalized data to push, you can call `pushMany` with the Array, and it will call `push` repeatedly for you. @method pushMany @param {String or subclass of DS.Model} type @param {Array} datas @return {Array} */ pushMany: function(type, datas) { return map(datas, function(data) { return this.push(type, data); }, this); }, /** If you have some metadata to set for a type you can call `metaForType`. @method metaForType @param {String or subclass of DS.Model} type @param {Object} metadata */ metaForType: function(typeName, metadata) { var type = this.modelFor(typeName); Ember.merge(this.typeMapFor(type).metadata, metadata); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {subclass of DS.Model} type @param {String} id @param {Object} data @return {DS.Model} record */ buildRecord: function(type, id, data) { var typeMap = this.typeMapFor(type); var idToRecord = typeMap.idToRecord; Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]); Ember.assert("`" + Ember.inspect(type)+ "` does not appear to be an ember-data model", (typeof type._create === 'function') ); // lookupFactory should really return an object that creates // instances with the injections applied var record = type._create({ id: id, store: this, container: this.container }); if (data) { record.setupData(data); } // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = record; } typeMap.records.push(record); return record; }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method dematerializeRecord @private @param {DS.Model} record */ dematerializeRecord: function(record) { var type = record.constructor; var typeMap = this.typeMapFor(type); var id = get(record, 'id'); record.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = indexOf(typeMap.records, record); typeMap.records.splice(loc, 1); }, // ........................ // . RELATIONSHIP CHANGES . // ........................ addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) { var clientId = childRecord.clientId; var parentClientId = parentRecord ? parentRecord : parentRecord; var key = childKey + parentKey; var changes = this._relationshipChanges; if (!(clientId in changes)) { changes[clientId] = {}; } if (!(parentClientId in changes[clientId])) { changes[clientId][parentClientId] = {}; } if (!(key in changes[clientId][parentClientId])) { changes[clientId][parentClientId][key] = {}; } changes[clientId][parentClientId][key][change.changeType] = change; }, removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) { var clientId = clientRecord.clientId; var parentClientId = parentRecord ? parentRecord.clientId : parentRecord; var changes = this._relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){ return; } delete changes[clientId][parentClientId][key][type]; }, relationshipChangePairsFor: function(record){ var toReturn = []; if( !record ) { return toReturn; } //TODO(Igor) What about the other side var changesObject = this._relationshipChanges[record.clientId]; for (var objKey in changesObject){ if (changesObject.hasOwnProperty(objKey)){ for (var changeKey in changesObject[objKey]){ if (changesObject[objKey].hasOwnProperty(changeKey)){ toReturn.push(changesObject[objKey][changeKey]); } } } } return toReturn; }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns the adapter for a given type. @method adapterFor @private @param {subclass of DS.Model} type @return DS.Adapter */ adapterFor: function(type) { var container = this.container, adapter; if (container) { adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application'); } return adapter || get(this, 'defaultAdapter'); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). If no `App.ApplicationSerializer` is found, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @private @param {String} type the record to serialize @return {DS.Serializer} */ serializerFor: function(type) { type = this.modelFor(type); var adapter = this.adapterFor(type); return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer); }, willDestroy: function() { var typeMaps = this.typeMaps; var keys = Ember.keys(typeMaps); var store = this; var types = map(keys, byType); this.recordArrayManager.destroy(); forEach(types, this.unloadAll, this); function byType(entry) { return typeMaps[entry]['type']; } }, /** All typeKeys are camelCase internally. Changing this function may require changes to other normalization hooks (such as typeForRoot). @method _normalizeTypeKey @private @param {String} type @return {String} if the adapter can generate one, an ID */ _normalizeTypeKey: function(key) { return camelize(singularize(key)); } }); function normalizeRelationships(store, type, data, record) { type.eachRelationship(function(key, relationship) { // A link (usually a URL) was already provided in // normalized form if (data.links && data.links[key]) { if (record && relationship.options.async) { record._relationships[key] = null; } return; } var kind = relationship.kind; var value = data[key]; if (value == null) { if (kind === 'hasMany' && record) { value = data[key] = record.get(key).toArray(); } return; } if (kind === 'belongsTo') { deserializeRecordId(store, data, key, relationship, value); } else if (kind === 'hasMany') { deserializeRecordIds(store, data, key, relationship, value); addUnsavedRecords(record, key, value); } }); return data; } function deserializeRecordId(store, data, key, relationship, id) { if (!Model) { Model = requireModule("ember-data/system/model")["Model"]; } if (isNone(id) || id instanceof Model) { return; } var type; if (typeof id === 'number' || typeof id === 'string') { type = typeFor(relationship, key, data); data[key] = store.recordForId(type, id); } else if (typeof id === 'object') { // polymorphic data[key] = store.recordForId(id.type, id.id); } } function typeFor(relationship, key, data) { if (relationship.options.polymorphic) { return data[key + "Type"]; } else { return relationship.type; } } function deserializeRecordIds(store, data, key, relationship, ids) { for (var i=0, l=ids.length; i<l; i++) { deserializeRecordId(store, ids, i, relationship, ids[i]); } } // If there are any unsaved records that are in a hasMany they won't be // in the payload, so add them back in manually. function addUnsavedRecords(record, key, data) { if(record) { var unsavedRecords = uniqById(Ember.A(data), record.get(key).filterBy('isNew')); Ember.A(data).pushObjects(unsavedRecords); } } function uniqById(data, records) { var currentIds = data.mapBy("id"); return records.reject(function(record) { return Ember.A(currentIds).contains(record.id); }); } // Delegation to the adapter and promise management /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved, then the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); function promiseObject(promise, label) { return PromiseObject.create({ promise: Promise.cast(promise, label) }); } function promiseArray(promise, label) { return PromiseArray.create({ promise: Promise.cast(promise, label) }); } function isThenable(object) { return object && typeof object.then === 'function'; } function serializerFor(container, type, defaultSerializer) { return container.lookup('serializer:'+type) || container.lookup('serializer:application') || container.lookup('serializer:' + defaultSerializer) || container.lookup('serializer:-default'); } function defaultSerializer(container) { return container.lookup('serializer:application') || container.lookup('serializer:-default'); } function serializerForAdapter(adapter, type) { var serializer = adapter.serializer; var defaultSerializer = adapter.defaultSerializer; var container = adapter.container; if (container && serializer === undefined) { serializer = serializerFor(container, type.typeKey, defaultSerializer); } if (serializer === null || serializer === undefined) { serializer = { extract: function(store, type, payload) { return payload; } }; } return serializer; } function _objectIsAlive(object) { return !(get(object, "isDestroyed") || get(object, "isDestroying")); } function _guard(promise, test) { var guarded = promise['finally'](function() { if (!test()) { guarded._subscribers.length = 0; } }); return guarded; } function _bind(fn) { var args = Array.prototype.slice.call(arguments, 1); return function() { return fn.apply(undefined, args); }; } function _find(adapter, store, type, id, record) { var promise = adapter.find(store, type, id, record); var serializer = serializerForAdapter(adapter, type); var label = "DS: Handle Adapter#find of " + type + " with id: " + id; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); return promise.then(function(adapterPayload) { Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", adapterPayload); var payload = serializer.extract(store, type, adapterPayload, id, 'find'); return store.push(type, payload); }, function(error) { var record = store.getById(type, id); if (record) { record.notFound(); } throw error; }, "DS: Extract payload of '" + type + "'"); } function _findMany(adapter, store, type, ids, records) { var promise = adapter.findMany(store, type, ids, records); var serializer = serializerForAdapter(adapter, type); var label = "DS: Handle Adapter#findMany of " + type; if (promise === undefined) { throw new Error('adapter.findMany returned undefined, this was very likely a mistake'); } var guardedPromise; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, null, 'findMany'); Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); return store.pushMany(type, payload); }, null, "DS: Extract payload of " + type); } function _findHasMany(adapter, store, record, link, relationship) { var promise = adapter.findHasMany(store, record, link, relationship); var serializer = serializerForAdapter(adapter, relationship.type); var label = "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); promise = _guard(promise, _bind(_objectIsAlive, record)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findHasMany'); Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); var records = store.pushMany(relationship.type, payload); record.updateHasMany(relationship.key, records); }, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type); } function _findBelongsTo(adapter, store, record, link, relationship) { var promise = adapter.findBelongsTo(store, record, link, relationship); var serializer = serializerForAdapter(adapter, relationship.type); var label = "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); promise = _guard(promise, _bind(_objectIsAlive, record)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, relationship.type, adapterPayload, null, 'findBelongsTo'); var record = store.push(relationship.type, payload); record.updateBelongsTo(relationship.key, record); return record; }, null, "DS: Extract payload of " + record + " : " + relationship.type); } function _findAll(adapter, store, type, sinceToken) { var promise = adapter.findAll(store, type, sinceToken); var serializer = serializerForAdapter(adapter, type); var label = "DS: Handle Adapter#findAll of " + type; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, null, 'findAll'); Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); store.pushMany(type, payload); store.didUpdateAll(type); return store.all(type); }, null, "DS: Extract payload of findAll " + type); } function _findQuery(adapter, store, type, query, recordArray) { var promise = adapter.findQuery(store, type, query, recordArray); var serializer = serializerForAdapter(adapter, type); var label = "DS: Handle Adapter#findQuery of " + type; promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); return promise.then(function(adapterPayload) { var payload = serializer.extract(store, type, adapterPayload, null, 'findQuery'); Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); recordArray.load(payload); return recordArray; }, null, "DS: Extract payload of findQuery " + type); } function _commit(adapter, store, operation, record) { var type = record.constructor; var promise = adapter[operation](store, type, record); var serializer = serializerForAdapter(adapter, type); var label = "DS: Extract and notify about " + operation + " completion of " + record; Ember.assert("Your adapter's '" + operation + "' method must return a value, but it returned `undefined", promise !==undefined); promise = Promise.cast(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); promise = _guard(promise, _bind(_objectIsAlive, record)); return promise.then(function(adapterPayload) { var payload; if (adapterPayload) { payload = serializer.extract(store, type, adapterPayload, get(record, 'id'), operation); } else { payload = adapterPayload; } store.didSaveRecord(record, payload); return record; }, function(reason) { if (reason instanceof InvalidError) { store.recordWasInvalid(record, reason.errors); } else { store.recordWasError(record, reason); } throw reason; }, label); } __exports__.Store = Store; __exports__.PromiseArray = PromiseArray; __exports__.PromiseObject = PromiseObject; __exports__["default"] = Store; }); define("ember-data/transforms", ["ember-data/transforms/base","ember-data/transforms/number","ember-data/transforms/date","ember-data/transforms/string","ember-data/transforms/boolean","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; var NumberTransform = __dependency2__["default"]; var DateTransform = __dependency3__["default"]; var StringTransform = __dependency4__["default"]; var BooleanTransform = __dependency5__["default"]; __exports__.Transform = Transform; __exports__.NumberTransform = NumberTransform; __exports__.DateTransform = DateTransform; __exports__.StringTransform = StringTransform; __exports__.BooleanTransform = BooleanTransform; }); define("ember-data/transforms/base", ["exports"], function(__exports__) { "use strict"; /** The `DS.Transform` class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. Subclassing `DS.Transform` is useful for creating custom attributes. All subclasses of `DS.Transform` must implement a `serialize` and a `deserialize` method. Example ```javascript // Converts centigrade in the JSON to fahrenheit in the app App.TemperatureTransform = DS.Transform.extend({ deserialize: function(serialized) { return (serialized * 1.8) + 32; }, serialize: function(deserialized) { return (deserialized - 32) / 1.8; } }); ``` Usage ```javascript var attr = DS.attr; App.Requirement = DS.Model.extend({ name: attr('string'), temperature: attr('temperature') }); ``` @class Transform @namespace DS */ __exports__["default"] = Ember.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @return The serialized value */ serialize: Ember.required(), /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @return The deserialized value */ deserialize: Ember.required() }); }); define("ember-data/transforms/boolean", ["ember-data/transforms/base","exports"], function(__dependency1__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; /** The `DS.BooleanTransform` class is used to serialize and deserialize boolean attributes on Ember Data record objects. This transform is used when `boolean` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class BooleanTransform @extends DS.Transform @namespace DS */ __exports__["default"] = Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }); }); define("ember-data/transforms/date", ["ember-data/transforms/base","exports"], function(__dependency1__, __exports__) { "use strict"; /** The `DS.DateTransform` class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used when `date` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ var Transform = __dependency1__["default"]; // Date.prototype.toISOString shim // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString var toISOString = Date.prototype.toISOString || function() { function pad(number) { if ( number < 10 ) { return '0' + number; } return number; } return this.getUTCFullYear() + '-' + pad( this.getUTCMonth() + 1 ) + '-' + pad( this.getUTCDate() ) + 'T' + pad( this.getUTCHours() ) + ':' + pad( this.getUTCMinutes() ) + ':' + pad( this.getUTCSeconds() ) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; }; if (Ember.SHIM_ES5) { if (!Date.prototype.toISOString) { Date.prototype.toISOString = toISOString; } } __exports__["default"] = Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { return toISOString.call(date); } else { return null; } } }); }); define("ember-data/transforms/number", ["ember-data/transforms/base","exports"], function(__dependency1__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; var empty = Ember.isEmpty; /** The `DS.NumberTransform` class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used when `number` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ __exports__["default"] = Transform.extend({ deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); }, serialize: function(deserialized) { return empty(deserialized) ? null : Number(deserialized); } }); }); define("ember-data/transforms/string", ["ember-data/transforms/base","exports"], function(__dependency1__, __exports__) { "use strict"; var Transform = __dependency1__["default"]; var none = Ember.isNone; /** The `DS.StringTransform` class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used when `string` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ __exports__["default"] = Transform.extend({ deserialize: function(serialized) { return none(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return none(deserialized) ? null : String(deserialized); } }); }); define("ember-inflector", ["./system","./helpers","./ext/string","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var Inflector = __dependency1__.Inflector; var defaultRules = __dependency1__.defaultRules; var pluralize = __dependency1__.pluralize; var singularize = __dependency1__.singularize; Inflector.defaultRules = defaultRules; Ember.Inflector = Inflector; Ember.String.pluralize = pluralize; Ember.String.singularize = singularize; __exports__["default"] = Inflector; __exports__.pluralize = pluralize; __exports__.singularize = singularize; }); define("ember-inflector/ext/string", ["../system/string"], function(__dependency1__) { "use strict"; var pluralize = __dependency1__.pluralize; var singularize = __dependency1__.singularize; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function() { return pluralize(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function() { return singularize(this); }; } }); define("ember-inflector/helpers", ["./system/string"], function(__dependency1__) { "use strict"; var singularize = __dependency1__.singularize; var pluralize = __dependency1__.pluralize; /** * * If you have Ember Inflector (such as if Ember Data is present), * singularize a word. For example, turn "oxen" into "ox". * * Example: * * {{singularize myProperty}} * {{singularize "oxen"}} * * @for Ember.Handlebars.helpers * @method singularize * @param {String|Property} word word to singularize */ Ember.Handlebars.helper('singularize', singularize); /** * * If you have Ember Inflector (such as if Ember Data is present), * pluralize a word. For example, turn "ox" into "oxen". * * Example: * * {{pluralize myProperty}} * {{pluralize "oxen"}} * * @for Ember.Handlebars.helpers * @method pluralize * @param {String|Property} word word to pluralize */ Ember.Handlebars.helper('pluralize', pluralize); }); define("ember-inflector/system", ["./system/inflector","./system/string","./system/inflections","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var Inflector = __dependency1__["default"]; var pluralize = __dependency2__.pluralize; var singularize = __dependency2__.singularize; var defaultRules = __dependency3__["default"]; Inflector.inflector = new Inflector(defaultRules); __exports__.Inflector = Inflector; __exports__.singularize = singularize; __exports__.pluralize = pluralize; __exports__.defaultRules = defaultRules; }); define("ember-inflector/system/inflections", ["exports"], function(__exports__) { "use strict"; __exports__["default"] = { plurals: [ [/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes'] ], singular: [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1'] ], irregularPairs: [ ['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies'] ], uncountable: [ 'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police' ] }; }); define("ember-inflector/system/inflector", ["exports"], function(__exports__) { "use strict"; var BLANK_REGEX = /^\s*$/; var LAST_WORD_DASHED_REGEX = /(\w+[_-])([a-z\d]+$)/; var LAST_WORD_CAMELIZED_REGEX = /(\w+)([A-Z][a-z\d]*$)/; var CAMELIZED_REGEX = /[A-Z][a-z\d]*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; //pluralizing rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregular[pair[1].toLowerCase()] = pair[1]; //singularizing rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; rules.irregularInverse[pair[0].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow'); //=> 'kine' inflector.singularize('kine'); //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice'); // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice'); // => 'advice' inflector.pluralize('formula'); // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula'); // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ /$/, 's' ], singular: [ /\s$/, '' ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || makeDictionary(); ruleSet.irregularPairs = ruleSet.irregularPairs || makeDictionary(); var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: makeDictionary(), irregularInverse: makeDictionary(), uncountable: makeDictionary() }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); this.enableCache(); } if (!Object.create && !Object.create(null).hasOwnProperty) { throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); } function makeDictionary() { var cache = Object.create(null); cache['_dict'] = null; delete cache['_dict']; return cache; } Inflector.prototype = { /** @public As inflections can be costly, and commonly the same subset of words are repeatedly inflected an optional cache is provided. @method enableCache */ enableCache: function() { this.purgeCache(); this.singularize = function(word) { this._cacheUsed = true; return this._sCache[word] || (this._sCache[word] = this._singularize(word)); }; this.pluralize = function(word) { this._cacheUsed = true; return this._pCache[word] || (this._pCache[word] = this._pluralize(word)); }; }, /** @public @method purgedCache */ purgeCache: function() { this._cacheUsed = false; this._sCache = makeDictionary(); this._pCache = makeDictionary(); }, /** @public disable caching @method disableCache; */ disableCache: function() { this._sCache = null; this._pCache = null; this.singularize = function(word) { return this._singularize(word); }; this.pluralize = function(word) { return this._pluralize(word); }; }, /** @method plural @param {RegExp} regex @param {String} string */ plural: function(regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function(regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function(string) { if (this._cacheUsed) { this.purgeCache(); } loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { if (this._cacheUsed) { this.purgeCache(); } loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function(word) { return this._pluralize(word); }, _pluralize: function(word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function(word) { return this._singularize(word); }, _singularize: function(word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function(word, typeRules, irregular) { var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, isUncountable, isIrregular, isIrregularInverse, rule; isBlank = BLANK_REGEX.test(word); isCamelized = CAMELIZED_REGEX.test(word); firstPhrase = ""; if (isBlank) { return word; } lowercase = word.toLowerCase(); wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word); if (wordSplit){ firstPhrase = wordSplit[1]; lastWord = wordSplit[2].toLowerCase(); } isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord]; if (isUncountable) { return word; } isIrregular = irregular && (irregular[lowercase] || irregular[lastWord]); if (isIrregular) { if (irregular[lowercase]){ return isIrregular; } else { isIrregular = (isCamelized) ? isIrregular.capitalize() : isIrregular; return firstPhrase + isIrregular; } } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i-1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; __exports__["default"] = Inflector; }); define("ember-inflector/system/string", ["./inflector","exports"], function(__dependency1__, __exports__) { "use strict"; var Inflector = __dependency1__["default"]; function pluralize(word) { return Inflector.inflector.pluralize(word); } function singularize(word) { return Inflector.inflector.singularize(word); } __exports__.pluralize = pluralize; __exports__.singularize = singularize; }); global.DS = requireModule('ember-data')['default']; })(this);
packages/material-ui-icons/src/SmsFailed.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 12h-2v-2h2v2zm0-4h-2V6h2v4z" /></React.Fragment> , 'SmsFailed');
ajax/libs/yui/3.14.0/datatable-core/datatable-core-coverage.js
robfletcher/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/datatable-core/datatable-core.js']) { __coverage__['build/datatable-core/datatable-core.js'] = {"path":"build/datatable-core/datatable-core.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0,0],"15":[0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0,0],"33":[0,0],"34":[0,0],"35":[0,0],"36":[0,0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0],"52":[0,0],"53":[0,0,0],"54":[0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0],"60":[0,0,0],"61":[0,0],"62":[0,0,0],"63":[0,0],"64":[0,0,0],"65":[0,0],"66":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":26},"end":{"line":1,"column":45}}},"2":{"name":"(anonymous_2)","line":38,"loc":{"start":{"line":38,"column":40},"end":{"line":38,"column":52}}},"3":{"name":"(anonymous_3)","line":231,"loc":{"start":{"line":231,"column":15},"end":{"line":231,"column":31}}},"4":{"name":"(anonymous_4)","line":278,"loc":{"start":{"line":278,"column":15},"end":{"line":278,"column":31}}},"5":{"name":"(anonymous_5)","line":344,"loc":{"start":{"line":344,"column":25},"end":{"line":344,"column":38}}},"6":{"name":"(anonymous_6)","line":357,"loc":{"start":{"line":357,"column":22},"end":{"line":357,"column":35}}},"7":{"name":"(anonymous_7)","line":377,"loc":{"start":{"line":377,"column":28},"end":{"line":377,"column":41}}},"8":{"name":"(anonymous_8)","line":406,"loc":{"start":{"line":406,"column":24},"end":{"line":406,"column":41}}},"9":{"name":"(anonymous_9)","line":429,"loc":{"start":{"line":429,"column":16},"end":{"line":429,"column":28}}},"10":{"name":"(anonymous_10)","line":445,"loc":{"start":{"line":445,"column":17},"end":{"line":445,"column":42}}},"11":{"name":"(anonymous_11)","line":468,"loc":{"start":{"line":468,"column":19},"end":{"line":468,"column":38}}},"12":{"name":"(anonymous_12)","line":480,"loc":{"start":{"line":480,"column":20},"end":{"line":480,"column":35}}},"13":{"name":"(anonymous_13)","line":500,"loc":{"start":{"line":500,"column":18},"end":{"line":500,"column":30}}},"14":{"name":"(anonymous_14)","line":526,"loc":{"start":{"line":526,"column":21},"end":{"line":526,"column":33}}},"15":{"name":"(anonymous_15)","line":544,"loc":{"start":{"line":544,"column":15},"end":{"line":544,"column":27}}},"16":{"name":"(anonymous_16)","line":569,"loc":{"start":{"line":569,"column":23},"end":{"line":569,"column":39}}},"17":{"name":"(anonymous_17)","line":607,"loc":{"start":{"line":607,"column":17},"end":{"line":607,"column":35}}},"18":{"name":"(anonymous_18)","line":653,"loc":{"start":{"line":653,"column":19},"end":{"line":653,"column":38}}},"19":{"name":"process","line":656,"loc":{"start":{"line":656,"column":8},"end":{"line":656,"column":31}}},"20":{"name":"(anonymous_20)","line":703,"loc":{"start":{"line":703,"column":17},"end":{"line":703,"column":32}}},"21":{"name":"copyObj","line":709,"loc":{"start":{"line":709,"column":8},"end":{"line":709,"column":28}}},"22":{"name":"genId","line":735,"loc":{"start":{"line":735,"column":8},"end":{"line":735,"column":29}}},"23":{"name":"process","line":749,"loc":{"start":{"line":749,"column":8},"end":{"line":749,"column":39}}},"24":{"name":"(anonymous_24)","line":805,"loc":{"start":{"line":805,"column":19},"end":{"line":805,"column":34}}},"25":{"name":"(anonymous_25)","line":828,"loc":{"start":{"line":828,"column":14},"end":{"line":828,"column":29}}},"26":{"name":"(anonymous_26)","line":866,"loc":{"start":{"line":866,"column":19},"end":{"line":866,"column":34}}},"27":{"name":"(anonymous_27)","line":871,"loc":{"start":{"line":871,"column":21},"end":{"line":871,"column":39}}},"28":{"name":"(anonymous_28)","line":898,"loc":{"start":{"line":898,"column":20},"end":{"line":898,"column":35}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":1319,"column":79}},"2":{"start":{"line":11,"column":0},"end":{"line":24,"column":10}},"3":{"start":{"line":38,"column":0},"end":{"line":38,"column":55}},"4":{"start":{"line":40,"column":0},"end":{"line":199,"column":2}},"5":{"start":{"line":201,"column":0},"end":{"line":911,"column":3}},"6":{"start":{"line":232,"column":8},"end":{"line":232,"column":39}},"7":{"start":{"line":234,"column":8},"end":{"line":242,"column":9}},"8":{"start":{"line":235,"column":12},"end":{"line":239,"column":13}},"9":{"start":{"line":236,"column":16},"end":{"line":236,"column":48}},"10":{"start":{"line":238,"column":16},"end":{"line":238,"column":27}},"11":{"start":{"line":241,"column":12},"end":{"line":241,"column":46}},"12":{"start":{"line":244,"column":8},"end":{"line":246,"column":9}},"13":{"start":{"line":245,"column":12},"end":{"line":245,"column":23}},"14":{"start":{"line":248,"column":8},"end":{"line":248,"column":38}},"15":{"start":{"line":250,"column":8},"end":{"line":259,"column":9}},"16":{"start":{"line":251,"column":12},"end":{"line":251,"column":33}},"17":{"start":{"line":252,"column":12},"end":{"line":252,"column":27}},"18":{"start":{"line":254,"column":12},"end":{"line":256,"column":13}},"19":{"start":{"line":255,"column":16},"end":{"line":255,"column":63}},"20":{"start":{"line":258,"column":12},"end":{"line":258,"column":51}},"21":{"start":{"line":261,"column":8},"end":{"line":261,"column":20}},"22":{"start":{"line":279,"column":8},"end":{"line":279,"column":78}},"23":{"start":{"line":281,"column":8},"end":{"line":290,"column":9}},"24":{"start":{"line":282,"column":12},"end":{"line":284,"column":13}},"25":{"start":{"line":283,"column":16},"end":{"line":283,"column":46}},"26":{"start":{"line":287,"column":12},"end":{"line":289,"column":13}},"27":{"start":{"line":288,"column":16},"end":{"line":288,"column":73}},"28":{"start":{"line":292,"column":8},"end":{"line":292,"column":30}},"29":{"start":{"line":345,"column":8},"end":{"line":345,"column":37}},"30":{"start":{"line":358,"column":8},"end":{"line":358,"column":33}},"31":{"start":{"line":360,"column":8},"end":{"line":360,"column":29}},"32":{"start":{"line":362,"column":8},"end":{"line":366,"column":9}},"33":{"start":{"line":365,"column":12},"end":{"line":365,"column":32}},"34":{"start":{"line":378,"column":8},"end":{"line":378,"column":38}},"35":{"start":{"line":380,"column":8},"end":{"line":380,"column":35}},"36":{"start":{"line":382,"column":8},"end":{"line":382,"column":30}},"37":{"start":{"line":384,"column":8},"end":{"line":390,"column":9}},"38":{"start":{"line":385,"column":12},"end":{"line":389,"column":13}},"39":{"start":{"line":386,"column":16},"end":{"line":386,"column":36}},"40":{"start":{"line":388,"column":16},"end":{"line":388,"column":58}},"41":{"start":{"line":407,"column":8},"end":{"line":407,"column":26}},"42":{"start":{"line":409,"column":8},"end":{"line":417,"column":9}},"43":{"start":{"line":410,"column":12},"end":{"line":410,"column":23}},"44":{"start":{"line":412,"column":12},"end":{"line":414,"column":13}},"45":{"start":{"line":413,"column":16},"end":{"line":413,"column":37}},"46":{"start":{"line":415,"column":15},"end":{"line":417,"column":9}},"47":{"start":{"line":416,"column":12},"end":{"line":416,"column":26}},"48":{"start":{"line":419,"column":8},"end":{"line":419,"column":76}},"49":{"start":{"line":430,"column":8},"end":{"line":430,"column":72}},"50":{"start":{"line":449,"column":8},"end":{"line":449,"column":59}},"51":{"start":{"line":469,"column":8},"end":{"line":469,"column":63}},"52":{"start":{"line":487,"column":8},"end":{"line":487,"column":53}},"53":{"start":{"line":501,"column":8},"end":{"line":502,"column":17}},"54":{"start":{"line":505,"column":8},"end":{"line":514,"column":9}},"55":{"start":{"line":507,"column":12},"end":{"line":507,"column":37}},"56":{"start":{"line":509,"column":12},"end":{"line":511,"column":13}},"57":{"start":{"line":510,"column":16},"end":{"line":510,"column":37}},"58":{"start":{"line":513,"column":12},"end":{"line":513,"column":44}},"59":{"start":{"line":516,"column":8},"end":{"line":516,"column":36}},"60":{"start":{"line":527,"column":8},"end":{"line":531,"column":11}},"61":{"start":{"line":545,"column":8},"end":{"line":547,"column":42}},"62":{"start":{"line":549,"column":8},"end":{"line":551,"column":9}},"63":{"start":{"line":550,"column":12},"end":{"line":550,"column":41}},"64":{"start":{"line":553,"column":8},"end":{"line":553,"column":25}},"65":{"start":{"line":570,"column":8},"end":{"line":570,"column":23}},"66":{"start":{"line":572,"column":8},"end":{"line":596,"column":9}},"67":{"start":{"line":573,"column":12},"end":{"line":573,"column":48}},"68":{"start":{"line":575,"column":12},"end":{"line":589,"column":13}},"69":{"start":{"line":576,"column":16},"end":{"line":576,"column":33}},"70":{"start":{"line":578,"column":16},"end":{"line":580,"column":17}},"71":{"start":{"line":579,"column":20},"end":{"line":579,"column":49}},"72":{"start":{"line":584,"column":16},"end":{"line":584,"column":46}},"73":{"start":{"line":586,"column":16},"end":{"line":588,"column":17}},"74":{"start":{"line":587,"column":20},"end":{"line":587,"column":49}},"75":{"start":{"line":595,"column":12},"end":{"line":595,"column":38}},"76":{"start":{"line":608,"column":8},"end":{"line":610,"column":23}},"77":{"start":{"line":614,"column":8},"end":{"line":614,"column":37}},"78":{"start":{"line":620,"column":8},"end":{"line":633,"column":9}},"79":{"start":{"line":621,"column":12},"end":{"line":622,"column":51}},"80":{"start":{"line":624,"column":12},"end":{"line":628,"column":13}},"81":{"start":{"line":625,"column":16},"end":{"line":625,"column":49}},"82":{"start":{"line":626,"column":19},"end":{"line":628,"column":13}},"83":{"start":{"line":627,"column":16},"end":{"line":627,"column":40}},"84":{"start":{"line":630,"column":12},"end":{"line":632,"column":13}},"85":{"start":{"line":631,"column":16},"end":{"line":631,"column":45}},"86":{"start":{"line":635,"column":8},"end":{"line":635,"column":28}},"87":{"start":{"line":637,"column":8},"end":{"line":637,"column":32}},"88":{"start":{"line":639,"column":8},"end":{"line":639,"column":31}},"89":{"start":{"line":654,"column":8},"end":{"line":654,"column":21}},"90":{"start":{"line":656,"column":8},"end":{"line":678,"column":9}},"91":{"start":{"line":657,"column":12},"end":{"line":657,"column":33}},"92":{"start":{"line":659,"column":12},"end":{"line":677,"column":13}},"93":{"start":{"line":660,"column":16},"end":{"line":660,"column":30}},"94":{"start":{"line":661,"column":16},"end":{"line":661,"column":30}},"95":{"start":{"line":668,"column":16},"end":{"line":670,"column":17}},"96":{"start":{"line":669,"column":20},"end":{"line":669,"column":35}},"97":{"start":{"line":672,"column":16},"end":{"line":672,"column":35}},"98":{"start":{"line":674,"column":16},"end":{"line":676,"column":17}},"99":{"start":{"line":675,"column":20},"end":{"line":675,"column":42}},"100":{"start":{"line":680,"column":8},"end":{"line":680,"column":25}},"101":{"start":{"line":682,"column":8},"end":{"line":682,"column":30}},"102":{"start":{"line":704,"column":8},"end":{"line":707,"column":41}},"103":{"start":{"line":709,"column":8},"end":{"line":733,"column":9}},"104":{"start":{"line":710,"column":12},"end":{"line":711,"column":28}},"105":{"start":{"line":713,"column":12},"end":{"line":713,"column":26}},"106":{"start":{"line":714,"column":12},"end":{"line":714,"column":35}},"107":{"start":{"line":716,"column":12},"end":{"line":730,"column":13}},"108":{"start":{"line":717,"column":16},"end":{"line":729,"column":17}},"109":{"start":{"line":718,"column":20},"end":{"line":718,"column":33}},"110":{"start":{"line":720,"column":20},"end":{"line":728,"column":21}},"111":{"start":{"line":721,"column":24},"end":{"line":721,"column":48}},"112":{"start":{"line":722,"column":27},"end":{"line":728,"column":21}},"113":{"start":{"line":723,"column":24},"end":{"line":723,"column":51}},"114":{"start":{"line":725,"column":24},"end":{"line":725,"column":77}},"115":{"start":{"line":727,"column":24},"end":{"line":727,"column":43}},"116":{"start":{"line":732,"column":12},"end":{"line":732,"column":24}},"117":{"start":{"line":735,"column":8},"end":{"line":747,"column":9}},"118":{"start":{"line":738,"column":12},"end":{"line":738,"column":44}},"119":{"start":{"line":740,"column":12},"end":{"line":744,"column":13}},"120":{"start":{"line":741,"column":16},"end":{"line":741,"column":39}},"121":{"start":{"line":743,"column":16},"end":{"line":743,"column":31}},"122":{"start":{"line":746,"column":12},"end":{"line":746,"column":24}},"123":{"start":{"line":749,"column":8},"end":{"line":788,"column":9}},"124":{"start":{"line":750,"column":12},"end":{"line":751,"column":34}},"125":{"start":{"line":753,"column":12},"end":{"line":785,"column":13}},"126":{"start":{"line":754,"column":16},"end":{"line":755,"column":78}},"127":{"start":{"line":757,"column":16},"end":{"line":757,"column":36}},"128":{"start":{"line":760,"column":16},"end":{"line":764,"column":17}},"129":{"start":{"line":763,"column":20},"end":{"line":763,"column":34}},"130":{"start":{"line":765,"column":16},"end":{"line":769,"column":17}},"131":{"start":{"line":768,"column":20},"end":{"line":768,"column":41}},"132":{"start":{"line":771,"column":16},"end":{"line":775,"column":17}},"133":{"start":{"line":772,"column":20},"end":{"line":772,"column":41}},"134":{"start":{"line":774,"column":20},"end":{"line":774,"column":39}},"135":{"start":{"line":780,"column":16},"end":{"line":780,"column":63}},"136":{"start":{"line":782,"column":16},"end":{"line":784,"column":17}},"137":{"start":{"line":783,"column":20},"end":{"line":783,"column":62}},"138":{"start":{"line":787,"column":12},"end":{"line":787,"column":27}},"139":{"start":{"line":790,"column":8},"end":{"line":790,"column":35}},"140":{"start":{"line":806,"column":8},"end":{"line":806,"column":33}},"141":{"start":{"line":808,"column":8},"end":{"line":808,"column":44}},"142":{"start":{"line":829,"column":8},"end":{"line":831,"column":9}},"143":{"start":{"line":830,"column":12},"end":{"line":830,"column":21}},"144":{"start":{"line":833,"column":8},"end":{"line":849,"column":9}},"145":{"start":{"line":834,"column":12},"end":{"line":834,"column":37}},"146":{"start":{"line":840,"column":12},"end":{"line":840,"column":51}},"147":{"start":{"line":845,"column":12},"end":{"line":845,"column":28}},"148":{"start":{"line":846,"column":15},"end":{"line":849,"column":9}},"149":{"start":{"line":848,"column":12},"end":{"line":848,"column":26}},"150":{"start":{"line":851,"column":8},"end":{"line":851,"column":19}},"151":{"start":{"line":867,"column":8},"end":{"line":867,"column":17}},"152":{"start":{"line":869,"column":8},"end":{"line":875,"column":9}},"153":{"start":{"line":870,"column":12},"end":{"line":870,"column":22}},"154":{"start":{"line":871,"column":12},"end":{"line":873,"column":15}},"155":{"start":{"line":872,"column":16},"end":{"line":872,"column":46}},"156":{"start":{"line":874,"column":12},"end":{"line":874,"column":23}},"157":{"start":{"line":877,"column":8},"end":{"line":877,"column":30}},"158":{"start":{"line":879,"column":8},"end":{"line":879,"column":19}},"159":{"start":{"line":899,"column":8},"end":{"line":899,"column":23}},"160":{"start":{"line":902,"column":8},"end":{"line":906,"column":9}},"161":{"start":{"line":903,"column":12},"end":{"line":903,"column":29}},"162":{"start":{"line":904,"column":15},"end":{"line":906,"column":9}},"163":{"start":{"line":905,"column":12},"end":{"line":905,"column":54}},"164":{"start":{"line":908,"column":8},"end":{"line":908,"column":37}}},"branchMap":{"1":{"line":234,"type":"if","locations":[{"start":{"line":234,"column":8},"end":{"line":234,"column":8}},{"start":{"line":234,"column":8},"end":{"line":234,"column":8}}]},"2":{"line":234,"type":"binary-expr","locations":[{"start":{"line":234,"column":12},"end":{"line":234,"column":26}},{"start":{"line":234,"column":30},"end":{"line":234,"column":44}}]},"3":{"line":235,"type":"if","locations":[{"start":{"line":235,"column":12},"end":{"line":235,"column":12}},{"start":{"line":235,"column":12},"end":{"line":235,"column":12}}]},"4":{"line":244,"type":"if","locations":[{"start":{"line":244,"column":8},"end":{"line":244,"column":8}},{"start":{"line":244,"column":8},"end":{"line":244,"column":8}}]},"5":{"line":250,"type":"if","locations":[{"start":{"line":250,"column":8},"end":{"line":250,"column":8}},{"start":{"line":250,"column":8},"end":{"line":250,"column":8}}]},"6":{"line":250,"type":"binary-expr","locations":[{"start":{"line":250,"column":12},"end":{"line":250,"column":26}},{"start":{"line":250,"column":30},"end":{"line":250,"column":43}}]},"7":{"line":254,"type":"binary-expr","locations":[{"start":{"line":254,"column":47},"end":{"line":254,"column":51}},{"start":{"line":254,"column":55},"end":{"line":254,"column":62}}]},"8":{"line":255,"type":"binary-expr","locations":[{"start":{"line":255,"column":23},"end":{"line":255,"column":36}},{"start":{"line":255,"column":40},"end":{"line":255,"column":62}}]},"9":{"line":258,"type":"binary-expr","locations":[{"start":{"line":258,"column":20},"end":{"line":258,"column":24}},{"start":{"line":258,"column":28},"end":{"line":258,"column":41}},{"start":{"line":258,"column":46},"end":{"line":258,"column":50}}]},"10":{"line":279,"type":"binary-expr","locations":[{"start":{"line":279,"column":21},"end":{"line":279,"column":44}},{"start":{"line":279,"column":48},"end":{"line":279,"column":77}}]},"11":{"line":281,"type":"if","locations":[{"start":{"line":281,"column":8},"end":{"line":281,"column":8}},{"start":{"line":281,"column":8},"end":{"line":281,"column":8}}]},"12":{"line":282,"type":"if","locations":[{"start":{"line":282,"column":12},"end":{"line":282,"column":12}},{"start":{"line":282,"column":12},"end":{"line":282,"column":12}}]},"13":{"line":287,"type":"if","locations":[{"start":{"line":287,"column":12},"end":{"line":287,"column":12}},{"start":{"line":287,"column":12},"end":{"line":287,"column":12}}]},"14":{"line":287,"type":"binary-expr","locations":[{"start":{"line":287,"column":16},"end":{"line":287,"column":23}},{"start":{"line":287,"column":27},"end":{"line":287,"column":36}},{"start":{"line":287,"column":40},"end":{"line":287,"column":59}}]},"15":{"line":292,"type":"binary-expr","locations":[{"start":{"line":292,"column":15},"end":{"line":292,"column":21}},{"start":{"line":292,"column":25},"end":{"line":292,"column":29}}]},"16":{"line":362,"type":"if","locations":[{"start":{"line":362,"column":8},"end":{"line":362,"column":8}},{"start":{"line":362,"column":8},"end":{"line":362,"column":8}}]},"17":{"line":362,"type":"binary-expr","locations":[{"start":{"line":362,"column":12},"end":{"line":362,"column":32}},{"start":{"line":362,"column":36},"end":{"line":362,"column":52}}]},"18":{"line":384,"type":"if","locations":[{"start":{"line":384,"column":8},"end":{"line":384,"column":8}},{"start":{"line":384,"column":8},"end":{"line":384,"column":8}}]},"19":{"line":384,"type":"binary-expr","locations":[{"start":{"line":384,"column":12},"end":{"line":384,"column":32}},{"start":{"line":384,"column":36},"end":{"line":384,"column":40}}]},"20":{"line":385,"type":"if","locations":[{"start":{"line":385,"column":12},"end":{"line":385,"column":12}},{"start":{"line":385,"column":12},"end":{"line":385,"column":12}}]},"21":{"line":409,"type":"if","locations":[{"start":{"line":409,"column":8},"end":{"line":409,"column":8}},{"start":{"line":409,"column":8},"end":{"line":409,"column":8}}]},"22":{"line":415,"type":"if","locations":[{"start":{"line":415,"column":15},"end":{"line":415,"column":15}},{"start":{"line":415,"column":15},"end":{"line":415,"column":15}}]},"23":{"line":449,"type":"cond-expr","locations":[{"start":{"line":449,"column":33},"end":{"line":449,"column":48}},{"start":{"line":449,"column":51},"end":{"line":449,"column":58}}]},"24":{"line":487,"type":"binary-expr","locations":[{"start":{"line":487,"column":15},"end":{"line":487,"column":18}},{"start":{"line":487,"column":23},"end":{"line":487,"column":32}},{"start":{"line":487,"column":36},"end":{"line":487,"column":51}}]},"25":{"line":501,"type":"binary-expr","locations":[{"start":{"line":501,"column":22},"end":{"line":501,"column":41}},{"start":{"line":501,"column":45},"end":{"line":501,"column":47}}]},"26":{"line":505,"type":"if","locations":[{"start":{"line":505,"column":8},"end":{"line":505,"column":8}},{"start":{"line":505,"column":8},"end":{"line":505,"column":8}}]},"27":{"line":505,"type":"binary-expr","locations":[{"start":{"line":505,"column":12},"end":{"line":505,"column":27}},{"start":{"line":505,"column":31},"end":{"line":505,"column":47}}]},"28":{"line":509,"type":"if","locations":[{"start":{"line":509,"column":12},"end":{"line":509,"column":12}},{"start":{"line":509,"column":12},"end":{"line":509,"column":12}}]},"29":{"line":549,"type":"if","locations":[{"start":{"line":549,"column":8},"end":{"line":549,"column":8}},{"start":{"line":549,"column":8},"end":{"line":549,"column":8}}]},"30":{"line":572,"type":"if","locations":[{"start":{"line":572,"column":8},"end":{"line":572,"column":8}},{"start":{"line":572,"column":8},"end":{"line":572,"column":8}}]},"31":{"line":575,"type":"if","locations":[{"start":{"line":575,"column":12},"end":{"line":575,"column":12}},{"start":{"line":575,"column":12},"end":{"line":575,"column":12}}]},"32":{"line":575,"type":"binary-expr","locations":[{"start":{"line":575,"column":16},"end":{"line":575,"column":20}},{"start":{"line":575,"column":24},"end":{"line":575,"column":33}},{"start":{"line":575,"column":37},"end":{"line":575,"column":48}}]},"33":{"line":578,"type":"if","locations":[{"start":{"line":578,"column":16},"end":{"line":578,"column":16}},{"start":{"line":578,"column":16},"end":{"line":578,"column":16}}]},"34":{"line":586,"type":"if","locations":[{"start":{"line":586,"column":16},"end":{"line":586,"column":16}},{"start":{"line":586,"column":16},"end":{"line":586,"column":16}}]},"35":{"line":620,"type":"if","locations":[{"start":{"line":620,"column":8},"end":{"line":620,"column":8}},{"start":{"line":620,"column":8},"end":{"line":620,"column":8}}]},"36":{"line":621,"type":"binary-expr","locations":[{"start":{"line":621,"column":26},"end":{"line":621,"column":43}},{"start":{"line":621,"column":47},"end":{"line":621,"column":72}},{"start":{"line":622,"column":28},"end":{"line":622,"column":50}}]},"37":{"line":624,"type":"if","locations":[{"start":{"line":624,"column":12},"end":{"line":624,"column":12}},{"start":{"line":624,"column":12},"end":{"line":624,"column":12}}]},"38":{"line":626,"type":"if","locations":[{"start":{"line":626,"column":19},"end":{"line":626,"column":19}},{"start":{"line":626,"column":19},"end":{"line":626,"column":19}}]},"39":{"line":626,"type":"binary-expr","locations":[{"start":{"line":626,"column":23},"end":{"line":626,"column":36}},{"start":{"line":626,"column":40},"end":{"line":626,"column":51}}]},"40":{"line":630,"type":"if","locations":[{"start":{"line":630,"column":12},"end":{"line":630,"column":12}},{"start":{"line":630,"column":12},"end":{"line":630,"column":12}}]},"41":{"line":668,"type":"if","locations":[{"start":{"line":668,"column":16},"end":{"line":668,"column":16}},{"start":{"line":668,"column":16},"end":{"line":668,"column":16}}]},"42":{"line":668,"type":"binary-expr","locations":[{"start":{"line":668,"column":20},"end":{"line":668,"column":23}},{"start":{"line":668,"column":27},"end":{"line":668,"column":36}}]},"43":{"line":674,"type":"if","locations":[{"start":{"line":674,"column":16},"end":{"line":674,"column":16}},{"start":{"line":674,"column":16},"end":{"line":674,"column":16}}]},"44":{"line":717,"type":"if","locations":[{"start":{"line":717,"column":16},"end":{"line":717,"column":16}},{"start":{"line":717,"column":16},"end":{"line":717,"column":16}}]},"45":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":20},"end":{"line":720,"column":20}},{"start":{"line":720,"column":20},"end":{"line":720,"column":20}}]},"46":{"line":722,"type":"if","locations":[{"start":{"line":722,"column":27},"end":{"line":722,"column":27}},{"start":{"line":722,"column":27},"end":{"line":722,"column":27}}]},"47":{"line":725,"type":"cond-expr","locations":[{"start":{"line":725,"column":47},"end":{"line":725,"column":59}},{"start":{"line":725,"column":62},"end":{"line":725,"column":76}}]},"48":{"line":740,"type":"if","locations":[{"start":{"line":740,"column":12},"end":{"line":740,"column":12}},{"start":{"line":740,"column":12},"end":{"line":740,"column":12}}]},"49":{"line":755,"type":"cond-expr","locations":[{"start":{"line":755,"column":42},"end":{"line":755,"column":58}},{"start":{"line":755,"column":61},"end":{"line":755,"column":77}}]},"50":{"line":760,"type":"if","locations":[{"start":{"line":760,"column":16},"end":{"line":760,"column":16}},{"start":{"line":760,"column":16},"end":{"line":760,"column":16}}]},"51":{"line":765,"type":"if","locations":[{"start":{"line":765,"column":16},"end":{"line":765,"column":16}},{"start":{"line":765,"column":16},"end":{"line":765,"column":16}}]},"52":{"line":771,"type":"if","locations":[{"start":{"line":771,"column":16},"end":{"line":771,"column":16}},{"start":{"line":771,"column":16},"end":{"line":771,"column":16}}]},"53":{"line":780,"type":"binary-expr","locations":[{"start":{"line":780,"column":32},"end":{"line":780,"column":40}},{"start":{"line":780,"column":44},"end":{"line":780,"column":51}},{"start":{"line":780,"column":55},"end":{"line":780,"column":61}}]},"54":{"line":782,"type":"if","locations":[{"start":{"line":782,"column":16},"end":{"line":782,"column":16}},{"start":{"line":782,"column":16},"end":{"line":782,"column":16}}]},"55":{"line":790,"type":"binary-expr","locations":[{"start":{"line":790,"column":15},"end":{"line":790,"column":18}},{"start":{"line":790,"column":22},"end":{"line":790,"column":34}}]},"56":{"line":808,"type":"cond-expr","locations":[{"start":{"line":808,"column":30},"end":{"line":808,"column":33}},{"start":{"line":808,"column":36},"end":{"line":808,"column":43}}]},"57":{"line":829,"type":"if","locations":[{"start":{"line":829,"column":8},"end":{"line":829,"column":8}},{"start":{"line":829,"column":8},"end":{"line":829,"column":8}}]},"58":{"line":833,"type":"if","locations":[{"start":{"line":833,"column":8},"end":{"line":833,"column":8}},{"start":{"line":833,"column":8},"end":{"line":833,"column":8}}]},"59":{"line":846,"type":"if","locations":[{"start":{"line":846,"column":15},"end":{"line":846,"column":15}},{"start":{"line":846,"column":15},"end":{"line":846,"column":15}}]},"60":{"line":846,"type":"binary-expr","locations":[{"start":{"line":846,"column":19},"end":{"line":846,"column":23}},{"start":{"line":846,"column":27},"end":{"line":846,"column":36}},{"start":{"line":846,"column":40},"end":{"line":846,"column":51}}]},"61":{"line":869,"type":"if","locations":[{"start":{"line":869,"column":8},"end":{"line":869,"column":8}},{"start":{"line":869,"column":8},"end":{"line":869,"column":8}}]},"62":{"line":869,"type":"binary-expr","locations":[{"start":{"line":869,"column":12},"end":{"line":869,"column":15}},{"start":{"line":869,"column":19},"end":{"line":869,"column":30}},{"start":{"line":869,"column":34},"end":{"line":869,"column":60}}]},"63":{"line":902,"type":"if","locations":[{"start":{"line":902,"column":8},"end":{"line":902,"column":8}},{"start":{"line":902,"column":8},"end":{"line":902,"column":8}}]},"64":{"line":902,"type":"binary-expr","locations":[{"start":{"line":902,"column":12},"end":{"line":902,"column":27}},{"start":{"line":902,"column":31},"end":{"line":902,"column":51}},{"start":{"line":902,"column":55},"end":{"line":902,"column":77}}]},"65":{"line":904,"type":"if","locations":[{"start":{"line":904,"column":15},"end":{"line":904,"column":15}},{"start":{"line":904,"column":15},"end":{"line":904,"column":15}}]},"66":{"line":908,"type":"binary-expr","locations":[{"start":{"line":908,"column":15},"end":{"line":908,"column":25}},{"start":{"line":908,"column":29},"end":{"line":908,"column":36}}]}},"code":["(function () { YUI.add('datatable-core', function (Y, NAME) {","","/**","The core implementation of the `DataTable` and `DataTable.Base` Widgets.","","@module datatable","@submodule datatable-core","@since 3.5.0","**/","","var INVALID = Y.Attribute.INVALID_VALUE,",""," Lang = Y.Lang,"," isFunction = Lang.isFunction,"," isObject = Lang.isObject,"," isArray = Lang.isArray,"," isString = Lang.isString,"," isNumber = Lang.isNumber,",""," toArray = Y.Array,",""," keys = Y.Object.keys,",""," Table;","","/**","_API docs for this extension are included in the DataTable class._","","Class extension providing the core API and structure for the DataTable Widget.","","Use this class extension with Widget or another Base-based superclass to create","the basic DataTable model API and composing class structure.","","@class DataTable.Core","@for DataTable","@since 3.5.0","**/","Table = Y.namespace('DataTable').Core = function () {};","","Table.ATTRS = {"," /**"," Columns to include in the rendered table.",""," If omitted, the attributes on the configured `recordType` or the first item"," in the `data` collection will be used as a source.",""," This attribute takes an array of strings or objects (mixing the two is"," fine). Each string or object is considered a column to be rendered."," Strings are converted to objects, so `columns: ['first', 'last']` becomes"," `columns: [{ key: 'first' }, { key: 'last' }]`.",""," DataTable.Core only concerns itself with a few properties of columns."," These properties are:",""," * `key` - Used to identify the record field/attribute containing content for"," this column. Also used to create a default Model if no `recordType` or"," `data` are provided during construction. If `name` is not specified, this"," is assigned to the `_id` property (with added incrementer if the key is"," used by multiple columns)."," * `children` - Traversed to initialize nested column objects"," * `name` - Used in place of, or in addition to, the `key`. Useful for"," columns that aren't bound to a field/attribute in the record data. This"," is assigned to the `_id` property."," * `id` - For backward compatibility. Implementers can specify the id of"," the header cell. This should be avoided, if possible, to avoid the"," potential for creating DOM elements with duplicate IDs."," * `field` - For backward compatibility. Implementers should use `name`."," * `_id` - Assigned unique-within-this-instance id for a column. By order"," of preference, assumes the value of `name`, `key`, `id`, or `_yuid`."," This is used by the rendering views as well as feature module"," as a means to identify a specific column without ambiguity (such as"," multiple columns using the same `key`."," * `_yuid` - Guid stamp assigned to the column object."," * `_parent` - Assigned to all child columns, referencing their parent"," column.",""," @attribute columns"," @type {Object[]|String[]}"," @default (from `recordType` ATTRS or first item in the `data`)"," @since 3.5.0"," **/"," columns: {"," // TODO: change to setter to clone input array/objects"," validator: isArray,"," setter: '_setColumns',"," getter: '_getColumns'"," },",""," /**"," Model subclass to use as the `model` for the ModelList stored in the `data`"," attribute.",""," If not provided, it will try really hard to figure out what to use. The"," following attempts will be made to set a default value:",""," 1. If the `data` attribute is set with a ModelList instance and its `model`"," property is set, that will be used."," 2. If the `data` attribute is set with a ModelList instance, and its"," `model` property is unset, but it is populated, the `ATTRS` of the"," `constructor of the first item will be used."," 3. If the `data` attribute is set with a non-empty array, a Model subclass"," will be generated using the keys of the first item as its `ATTRS` (see"," the `_createRecordClass` method)."," 4. If the `columns` attribute is set, a Model subclass will be generated"," using the columns defined with a `key`. This is least desirable because"," columns can be duplicated or nested in a way that's not parsable."," 5. If neither `data` nor `columns` is set or populated, a change event"," subscriber will listen for the first to be changed and try all over"," again.",""," @attribute recordType"," @type {Function}"," @default (see description)"," @since 3.5.0"," **/"," recordType: {"," getter: '_getRecordType',"," setter: '_setRecordType'"," },",""," /**"," The collection of data records to display. This attribute is a pass"," through to a `data` property, which is a ModelList instance.",""," If this attribute is passed a ModelList or subclass, it will be assigned to"," the property directly. If an array of objects is passed, a new ModelList"," will be created using the configured `recordType` as its `model` property"," and seeded with the array.",""," Retrieving this attribute will return the ModelList stored in the `data`"," property.",""," @attribute data"," @type {ModelList|Object[]}"," @default `new ModelList()`"," @since 3.5.0"," **/"," data: {"," valueFn: '_initData',"," setter : '_setData',"," lazyAdd: false"," },",""," /**"," Content for the `<table summary=\"ATTRIBUTE VALUE HERE\">`. Values assigned"," to this attribute will be HTML escaped for security.",""," @attribute summary"," @type {String}"," @default '' (empty string)"," @since 3.5.0"," **/"," //summary: {},",""," /**"," HTML content of an optional `<caption>` element to appear above the table."," Leave this config unset or set to a falsy value to remove the caption.",""," @attribute caption"," @type HTML"," @default '' (empty string)"," @since 3.5.0"," **/"," //caption: {},",""," /**"," Deprecated as of 3.5.0. Passes through to the `data` attribute.",""," WARNING: `get('recordset')` will NOT return a Recordset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute recordset"," @type {Object[]|Recordset}"," @deprecated Use the `data` attribute"," @since 3.5.0"," **/"," recordset: {"," setter: '_setRecordset',"," getter: '_getRecordset',"," lazyAdd: false"," },",""," /**"," Deprecated as of 3.5.0. Passes through to the `columns` attribute.",""," WARNING: `get('columnset')` will NOT return a Columnset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute columnset"," @type {Object[]}"," @deprecated Use the `columns` attribute"," @since 3.5.0"," **/"," columnset: {"," setter: '_setColumnset',"," getter: '_getColumnset',"," lazyAdd: false"," }","};","","Y.mix(Table.prototype, {"," // -- Instance properties -------------------------------------------------"," /**"," The ModelList that manages the table's data.",""," @property data"," @type {ModelList}"," @default undefined (initially unset)"," @since 3.5.0"," **/"," //data: null,",""," // -- Public methods ------------------------------------------------------",""," /**"," Gets the column configuration object for the given key, name, or index. For"," nested columns, `name` can be an array of indexes, each identifying the index"," of that column in the respective parent's \"children\" array.",""," If you pass a column object, it will be returned.",""," For columns with keys, you can also fetch the column with"," `instance.get('columns.foo')`.",""," @method getColumn"," @param {String|Number|Number[]} name Key, \"name\", index, or index array to"," identify the column"," @return {Object} the column configuration object"," @since 3.5.0"," **/"," getColumn: function (name) {"," var col, columns, i, len, cols;",""," if (isObject(name) && !isArray(name)) {"," if (name instanceof Y.Node) {"," col = this.body.getColumn(name);"," } else {"," col = name;"," }"," } else {"," col = this.get('columns.' + name);"," }",""," if (col) {"," return col;"," }",""," columns = this.get('columns');",""," if (isNumber(name) || isArray(name)) {"," name = toArray(name);"," cols = columns;",""," for (i = 0, len = name.length - 1; cols && i < len; ++i) {"," cols = cols[name[i]] && cols[name[i]].children;"," }",""," return (cols && cols[name[i]]) || null;"," }",""," return null;"," },",""," /**"," Returns the Model associated to the record `id`, `clientId`, or index (not"," row index). If none of those yield a Model from the `data` ModelList, the"," arguments will be passed to the `view` instance's `getRecord` method"," if it has one.",""," If no Model can be found, `null` is returned.",""," @method getRecord"," @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or"," identifier for a row or child element"," @return {Model}"," @since 3.5.0"," **/"," getRecord: function (seed) {"," var record = this.data.getById(seed) || this.data.getByClientId(seed);",""," if (!record) {"," if (isNumber(seed)) {"," record = this.data.item(seed);"," }",""," // TODO: this should be split out to base somehow"," if (!record && this.view && this.view.getRecord) {"," record = this.view.getRecord.apply(this.view, arguments);"," }"," }",""," return record || null;"," },",""," // -- Protected and private properties and methods ------------------------",""," /**"," This tells `Y.Base` that it should create ad-hoc attributes for config"," properties passed to DataTable's constructor. This is useful for setting"," configurations on the DataTable that are intended for the rendering View(s).",""," @property _allowAdHocAttrs"," @type Boolean"," @default true"," @protected"," @since 3.6.0"," **/"," _allowAdHocAttrs: true,",""," /**"," A map of column key to column configuration objects parsed from the"," `columns` attribute.",""," @property _columnMap"," @type {Object}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_columnMap: null,",""," /**"," The Node instance of the table containing the data rows. This is set when"," the table is rendered. It may also be set by progressive enhancement,"," though this extension does not provide the logic to parse from source.",""," @property _tableNode"," @type {Node}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_tableNode: null,",""," /**"," Updates the `_columnMap` property in response to changes in the `columns`"," attribute.",""," @method _afterColumnsChange"," @param {EventFacade} e The `columnsChange` event object"," @protected"," @since 3.5.0"," **/"," _afterColumnsChange: function (e) {"," this._setColumnMap(e.newVal);"," },",""," /**"," Updates the `modelList` attributes of the rendered views in response to the"," `data` attribute being assigned a new ModelList.",""," @method _afterDataChange"," @param {EventFacade} e the `dataChange` event"," @protected"," @since 3.5.0"," **/"," _afterDataChange: function (e) {"," var modelList = e.newVal;",""," this.data = e.newVal;",""," if (!this.get('columns') && modelList.size()) {"," // TODO: this will cause a re-render twice because the Views are"," // subscribed to columnsChange"," this._initColumns();"," }"," },",""," /**"," Assigns to the new recordType as the model for the data ModelList",""," @method _afterRecordTypeChange"," @param {EventFacade} e recordTypeChange event"," @protected"," @since 3.6.0"," **/"," _afterRecordTypeChange: function (e) {"," var data = this.data.toJSON();",""," this.data.model = e.newVal;",""," this.data.reset(data);",""," if (!this.get('columns') && data) {"," if (data.length) {"," this._initColumns();"," } else {"," this.set('columns', keys(e.newVal.ATTRS));"," }"," }"," },",""," /**"," Creates a Model subclass from an array of attribute names or an object of"," attribute definitions. This is used to generate a class suitable to"," represent the data passed to the `data` attribute if no `recordType` is"," set.",""," @method _createRecordClass"," @param {String[]|Object} attrs Names assigned to the Model subclass's"," `ATTRS` or its entire `ATTRS` definition object"," @return {Model}"," @protected"," @since 3.5.0"," **/"," _createRecordClass: function (attrs) {"," var ATTRS, i, len;",""," if (isArray(attrs)) {"," ATTRS = {};",""," for (i = 0, len = attrs.length; i < len; ++i) {"," ATTRS[attrs[i]] = {};"," }"," } else if (isObject(attrs)) {"," ATTRS = attrs;"," }",""," return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS });"," },",""," /**"," Tears down the instance.",""," @method destructor"," @protected"," @since 3.6.0"," **/"," destructor: function () {"," new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();"," },",""," /**"," The getter for the `columns` attribute. Returns the array of column"," configuration objects if `instance.get('columns')` is called, or the"," specific column object if `instance.get('columns.columnKey')` is called.",""," @method _getColumns"," @param {Object[]} columns The full array of column objects"," @param {String} name The attribute name requested"," (e.g. 'columns' or 'columns.foo');"," @protected"," @since 3.5.0"," **/"," _getColumns: function (columns, name) {"," // Workaround for an attribute oddity (ticket #2529254)"," // getter is expected to return an object if get('columns.foo') is called."," // Note 'columns.' is 8 characters"," return name.length > 8 ? this._columnMap : columns;"," },",""," /**"," Relays the `get()` request for the deprecated `columnset` attribute to the"," `columns` attribute.",""," THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will"," expect a Columnset instance returned from `get('columnset')`.",""," @method _getColumnset"," @param {Object} ignored The current value stored in the `columnset` state"," @param {String} name The attribute name requested"," (e.g. 'columnset' or 'columnset.foo');"," @deprecated This will be removed with the `columnset` attribute in a future"," version."," @protected"," @since 3.5.0"," **/"," _getColumnset: function (_, name) {"," return this.get(name.replace(/^columnset/, 'columns'));"," },",""," /**"," Returns the Model class of the instance's `data` attribute ModelList. If"," not set, returns the explicitly configured value.",""," @method _getRecordType"," @param {Model} val The currently configured value"," @return {Model}"," **/"," _getRecordType: function (val) {"," // Prefer the value stored in the attribute because the attribute"," // change event defaultFn sets e.newVal = this.get('recordType')"," // before notifying the after() subs. But if this getter returns"," // this.data.model, then after() subs would get e.newVal === previous"," // model before _afterRecordTypeChange can set"," // this.data.model = e.newVal"," return val || (this.data && this.data.model);"," },",""," /**"," Initializes the `_columnMap` property from the configured `columns`"," attribute. If `columns` is not set, but there are records in the `data`"," ModelList, use"," `ATTRS` of that class.",""," @method _initColumns"," @protected"," @since 3.5.0"," **/"," _initColumns: function () {"," var columns = this.get('columns') || [],"," item;",""," // Default column definition from the configured recordType"," if (!columns.length && this.data.size()) {"," // TODO: merge superclass attributes up to Model?"," item = this.data.item(0);",""," if (item.toJSON) {"," item = item.toJSON();"," }",""," this.set('columns', keys(item));"," }",""," this._setColumnMap(columns);"," },",""," /**"," Sets up the change event subscriptions to maintain internal state.",""," @method _initCoreEvents"," @protected"," @since 3.6.0"," **/"," _initCoreEvents: function () {"," this._eventHandles.coreAttrChanges = this.after({"," columnsChange : Y.bind('_afterColumnsChange', this),"," recordTypeChange: Y.bind('_afterRecordTypeChange', this),"," dataChange : Y.bind('_afterDataChange', this)"," });"," },",""," /**"," Defaults the `data` attribute to an empty ModelList if not set during"," construction. Uses the configured `recordType` for the ModelList's `model`"," proeprty if set.",""," @method _initData"," @protected"," @return {ModelList}"," @since 3.6.0"," **/"," _initData: function () {"," var recordType = this.get('recordType'),"," // TODO: LazyModelList if recordType doesn't have complex ATTRS"," modelList = new Y.ModelList();",""," if (recordType) {"," modelList.model = recordType;"," }",""," return modelList;"," },",""," /**"," Initializes the instance's `data` property from the value of the `data`"," attribute. If the attribute value is a ModelList, it is assigned directly"," to `this.data`. If it is an array, a ModelList is created, its `model`"," property is set to the configured `recordType` class, and it is seeded with"," the array data. This ModelList is then assigned to `this.data`.",""," @method _initDataProperty"," @param {Array|ModelList|ArrayList} data Collection of data to populate the"," DataTable"," @protected"," @since 3.6.0"," **/"," _initDataProperty: function (data) {"," var recordType;",""," if (!this.data) {"," recordType = this.get('recordType');",""," if (data && data.each && data.toJSON) {"," this.data = data;",""," if (recordType) {"," this.data.model = recordType;"," }"," } else {"," // TODO: customize the ModelList or read the ModelList class"," // from a configuration option?"," this.data = new Y.ModelList();",""," if (recordType) {"," this.data.model = recordType;"," }"," }",""," // TODO: Replace this with an event relay for specific events."," // Using bubbling causes subscription conflicts with the models'"," // aggregated change event and 'change' events from DOM elements"," // inside the table (via Widget UI event)."," this.data.addTarget(this);"," }"," },",""," /**"," Initializes the columns, `recordType` and data ModelList.",""," @method initializer"," @param {Object} config Configuration object passed to constructor"," @protected"," @since 3.5.0"," **/"," initializer: function (config) {"," var data = config.data,"," columns = config.columns,"," recordType;",""," // Referencing config.data to allow _setData to be more stringent"," // about its behavior"," this._initDataProperty(data);",""," // Default columns from recordType ATTRS if recordType is supplied at"," // construction. If no recordType is supplied, but the data is"," // supplied as a non-empty array, use the keys of the first item"," // as the columns."," if (!columns) {"," recordType = (config.recordType || config.data === this.data) &&"," this.get('recordType');",""," if (recordType) {"," columns = keys(recordType.ATTRS);"," } else if (isArray(data) && data.length) {"," columns = keys(data[0]);"," }",""," if (columns) {"," this.set('columns', columns);"," }"," }",""," this._initColumns();",""," this._eventHandles = {};",""," this._initCoreEvents();"," },",""," /**"," Iterates the array of column configurations to capture all columns with a"," `key` property. An map is built with column keys as the property name and"," the corresponding column object as the associated value. This map is then"," assigned to the instance's `_columnMap` property.",""," @method _setColumnMap"," @param {Object[]|String[]} columns The array of column config objects"," @protected"," @since 3.6.0"," **/"," _setColumnMap: function (columns) {"," var map = {};",""," function process(cols) {"," var i, len, col, key;",""," for (i = 0, len = cols.length; i < len; ++i) {"," col = cols[i];"," key = col.key;",""," // First in wins for multiple columns with the same key"," // because the first call to genId (in _setColumns) will"," // return the same key, which will then be overwritten by the"," // subsequent same-keyed column. So table.getColumn(key) would"," // return the last same-keyed column."," if (key && !map[key]) {"," map[key] = col;"," }"," //TODO: named columns can conflict with keyed columns"," map[col._id] = col;",""," if (col.children) {"," process(col.children);"," }"," }"," }",""," process(columns);",""," this._columnMap = map;"," },",""," /**"," Translates string columns into objects with that string as the value of its"," `key` property.",""," All columns are assigned a `_yuid` stamp and `_id` property corresponding"," to the column's configured `name` or `key` property with any spaces"," replaced with dashes. If the same `name` or `key` appears in multiple"," columns, subsequent appearances will have their `_id` appended with an"," incrementing number (e.g. if column \"foo\" is included in the `columns`"," attribute twice, the first will get `_id` of \"foo\", and the second an `_id`"," of \"foo1\"). Columns that are children of other columns will have the"," `_parent` property added, assigned the column object to which they belong.",""," @method _setColumns"," @param {null|Object[]|String[]} val Array of config objects or strings"," @return {null|Object[]}"," @protected"," **/"," _setColumns: function (val) {"," var keys = {},"," known = [],"," knownCopies = [],"," arrayIndex = Y.Array.indexOf;",""," function copyObj(o) {"," var copy = {},"," key, val, i;",""," known.push(o);"," knownCopies.push(copy);",""," for (key in o) {"," if (o.hasOwnProperty(key)) {"," val = o[key];",""," if (isArray(val)) {"," copy[key] = val.slice();"," } else if (isObject(val, true)) {"," i = arrayIndex(known, val);",""," copy[key] = i === -1 ? copyObj(val) : knownCopies[i];"," } else {"," copy[key] = o[key];"," }"," }"," }",""," return copy;"," }",""," function genId(name) {"," // Sanitize the name for use in generated CSS classes."," // TODO: is there more to do for other uses of _id?"," name = name.replace(/\\s+/, '-');",""," if (keys[name]) {"," name += (keys[name]++);"," } else {"," keys[name] = 1;"," }",""," return name;"," }",""," function process(cols, parent) {"," var columns = [],"," i, len, col, yuid;",""," for (i = 0, len = cols.length; i < len; ++i) {"," columns[i] = // chained assignment"," col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]);",""," yuid = Y.stamp(col);",""," // For backward compatibility"," if (!col.id) {"," // Implementers can shoot themselves in the foot by setting"," // this config property to a non-unique value"," col.id = yuid;"," }"," if (col.field) {"," // Field is now known as \"name\" to avoid confusion with data"," // fields or schema.resultFields"," col.name = col.field;"," }",""," if (parent) {"," col._parent = parent;"," } else {"," delete col._parent;"," }",""," // Unique id based on the column's configured name or key,"," // falling back to the yuid. Duplicates will have a counter"," // added to the end."," col._id = genId(col.name || col.key || col.id);",""," if (isArray(col.children)) {"," col.children = process(col.children, col);"," }"," }",""," return columns;"," }",""," return val && process(val);"," },",""," /**"," Relays attribute assignments of the deprecated `columnset` attribute to the"," `columns` attribute. If a Columnset is object is passed, its basic object"," structure is mined.",""," @method _setColumnset"," @param {Array|Columnset} val The columnset value to relay"," @deprecated This will be removed with the deprecated `columnset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setColumnset: function (val) {"," this.set('columns', val);",""," return isArray(val) ? val : INVALID;"," },",""," /**"," Accepts an object with `each` and `getAttrs` (preferably a ModelList or"," subclass) or an array of data objects. If an array is passes, it will"," create a ModelList to wrap the data. In doing so, it will set the created"," ModelList's `model` property to the class in the `recordType` attribute,"," which will be defaulted if not yet set.",""," If the `data` property is already set with a ModelList, passing an array as"," the value will call the ModelList's `reset()` method with that array rather"," than replacing the stored ModelList wholesale.",""," Any non-ModelList-ish and non-array value is invalid.",""," @method _setData"," @protected"," @since 3.5.0"," **/"," _setData: function (val) {"," if (val === null) {"," val = [];"," }",""," if (isArray(val)) {"," this._initDataProperty();",""," // silent to prevent subscribers to both reset and dataChange"," // from reacting to the change twice."," // TODO: would it be better to return INVALID to silence the"," // dataChange event, or even allow both events?"," this.data.reset(val, { silent: true });",""," // Return the instance ModelList to avoid storing unprocessed"," // data in the state and their vivified Model representations in"," // the instance's data property. Decreases memory consumption."," val = this.data;"," } else if (!val || !val.each || !val.toJSON) {"," // ModelList/ArrayList duck typing"," val = INVALID;"," }",""," return val;"," },",""," /**"," Relays the value assigned to the deprecated `recordset` attribute to the"," `data` attribute. If a Recordset instance is passed, the raw object data"," will be culled from it.",""," @method _setRecordset"," @param {Object[]|Recordset} val The recordset value to relay"," @deprecated This will be removed with the deprecated `recordset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setRecordset: function (val) {"," var data;",""," if (val && Y.Recordset && val instanceof Y.Recordset) {"," data = [];"," val.each(function (record) {"," data.push(record.get('data'));"," });"," val = data;"," }",""," this.set('data', val);",""," return val;"," },",""," /**"," Accepts a Base subclass (preferably a Model subclass). Alternately, it will"," generate a custom Model subclass from an array of attribute names or an"," object defining attributes and their respective configurations (it is"," assigned as the `ATTRS` of the new class).",""," Any other value is invalid.",""," @method _setRecordType"," @param {Function|String[]|Object} val The Model subclass, array of"," attribute names, or the `ATTRS` definition for a custom model"," subclass"," @return {Function} A Base/Model subclass"," @protected"," @since 3.5.0"," **/"," _setRecordType: function (val) {"," var modelClass;",""," // Duck type based on known/likely consumed APIs"," if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) {"," modelClass = val;"," } else if (isObject(val)) {"," modelClass = this._createRecordClass(val);"," }",""," return modelClass || INVALID;"," }","","});","","","","/**","_This is a documentation entry only_","","Columns are described by object literals with a set of properties.","There is not an actual `DataTable.Column` class.","However, for the purpose of documenting it, this pseudo-class is declared here.","","DataTables accept an array of column definitions in their [columns](DataTable.html#attr_columns)","attribute. Each entry in this array is a column definition which may contain","any combination of the properties listed below.","","There are no mandatory properties though a column will usually have a","[key](#property_key) property to reference the data it is supposed to show.","The [columns](DataTable.html#attr_columns) attribute can accept a plain string","in lieu of an object literal, which is the equivalent of an object with the","[key](#property_key) property set to that string.","","@class DataTable.Column","*/","","/**","Binds the column values to the named property in the [data](DataTable.html#attr_data).","","Optional if [formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter),","or [cellTemplate](#property_cellTemplate) is used to populate the content.","","It should not be set if [children](#property_children) is set.","","The value is used for the [\\_id](#property__id) property unless the [name](#property_name)","property is also set.",""," { key: 'username' }","","The above column definition can be reduced to this:",""," 'username'","","@property key","@type String"," */","/**","An identifier that can be used to locate a column via","[getColumn](DataTable.html#method_getColumn)","or style columns with class `yui3-datatable-col-NAME` after dropping characters","that are not valid for CSS class names.","","It defaults to the [key](#property_key).","","The value is used for the [\\_id](#property__id) property.",""," { name: 'fullname', formatter: ... }","","@property name","@type String","*/","/**","An alias for [name](#property_name) for backward compatibility.",""," { field: 'fullname', formatter: ... }","","@property field","@type String","*/","/**","Overrides the default unique id assigned `<th id=\"HERE\">`.","","__Use this with caution__, since it can result in","duplicate ids in the DOM.",""," {"," name: 'checkAll',"," id: 'check-all',"," label: ..."," formatter: ..."," }","","@property id","@type String"," */","/**","HTML to populate the header `<th>` for the column.","It defaults to the value of the [key](#property_key) property or the text","`Column n` where _n_ is an ordinal number.",""," { key: 'MfgvaPrtNum', label: 'Part Number' }","","@property label","@@type {HTML}"," */","/**","Used to create stacked headers.","","Child columns may also contain `children`. There is no limit","to the depth of nesting.","","Columns configured with `children` are for display only and","<strong>should not</strong> be configured with a [key](#property_key).","Configurations relating to the display of data, such as","[formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter),","[emptyCellValue](#property_emptyCellValue), etc. are ignored.",""," { label: 'Name', children: ["," { key: 'firstName', label: 'First`},"," { key: 'lastName', label: 'Last`}"," ]}","","@property children","@type Array","*/","/**","Assigns the value `<th abbr=\"HERE\">`.",""," {"," key : 'forecast',"," label: '1yr Target Forecast',"," abbr : 'Forecast'"," }","","@property abbr","@type String"," */","/**","Assigns the value `<th title=\"HERE\">`.",""," {"," key : 'forecast',"," label: '1yr Target Forecast',"," title: 'Target Forecast for the Next 12 Months'"," }","","@property title","@type String"," */","/**","Overrides the default [CELL_TEMPLATE](DataTable.HeaderView.html#property_CELL_TEMPLATE)","used by `Y.DataTable.HeaderView` to render the header cell","for this column. This is necessary when more control is","needed over the markup for the header itself, rather than","its content.","","Use the [label](#property_label) configuration if you don't need to","customize the `<th>` iteself.","","Implementers are strongly encouraged to preserve at least","the `{id}` and `{_id}` placeholders in the custom value.",""," {"," headerTemplate:"," '<th id=\"{id}\" ' +"," 'title=\"Unread\" ' +"," 'class=\"{className}\" ' +"," '{_id}>&#9679;</th>'"," }","","@property headerTemplate","@type HTML"," */","/**","Overrides the default [CELL_TEMPLATE](DataTable.BodyView.html#property_CELL_TEMPLATE)","used by `Y.DataTable.BodyView` to render the data cells","for this column. This is necessary when more control is","needed over the markup for the `<td>` itself, rather than","its content.",""," {"," key: 'id',"," cellTemplate:"," '<td class=\"{className}\">' +"," '<input type=\"checkbox\" ' +"," 'id=\"{content}\">' +"," '</td>'"," }","","","@property cellTemplate","@type HTML template"," */","/**","String or function used to translate the raw record data for each cell in a","given column into a format better suited to display.","","If it is a string, it will initially be assumed to be the name of one of the","formatting functions in","[Y.DataTable.BodyView.Formatters](DataTable.BodyView.Formatters.html).","If one such formatting function exists, it will be used.","","If no such named formatter is found, it will be assumed to be a template","string and will be expanded. The placeholders can contain the key to any","field in the record or the placeholder `{value}` which represents the value","of the current field.","","If the value is a function, it will be assumed to be a formatting function.","A formatting function receives a single argument, an object with the following properties:","","* __value__ The raw value from the record Model to populate this cell."," Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`.","* __data__ The Model data for this row in simple object format.","* __record__ The Model for this row.","* __column__ The column configuration object.","* __className__ A string of class names to add `<td class=\"HERE\">` in addition to"," the column class and any classes in the column's className configuration.","* __rowIndex__ The index of the current Model in the ModelList."," Typically correlates to the row index as well.","* __rowClass__ A string of css classes to add `<tr class=\"HERE\"><td....`"," This is useful to avoid the need for nodeFormatters to add classes to the containing row.","","The formatter function may return a string value that will be used for the cell","contents or it may change the value of the `value`, `className` or `rowClass`","properties which well then be used to format the cell. If the value for the cell","is returned in the `value` property of the input argument, no value should be returned.",""," {"," key: 'name',"," formatter: 'link', // named formatter"," linkFrom: 'website' // extra column property for link formatter"," },"," {"," key: 'cost',"," formatter: '${value}' // formatter template string"," //formatter: '${cost}' // same result but less portable"," },"," {"," name: 'Name', // column does not have associated field value"," // thus, it uses name instead of key"," formatter: '{firstName} {lastName}' // template references other fields"," },"," {"," key: 'price',"," formatter: function (o) { // function both returns a string to show"," if (o.value > 3) { // and a className to apply to the cell"," o.className += 'expensive';"," }",""," return '$' + o.value.toFixed(2);"," }"," },","@property formatter","@type String || Function","","*/","/**","Used to customize the content of the data cells for this column.","","`nodeFormatter` is significantly slower than [formatter](#property_formatter)","and should be avoided if possible. Unlike [formatter](#property_formatter),","`nodeFormatter` has access to the `<td>` element and its ancestors.","","The function provided is expected to fill in the `<td>` element itself.","__Node formatters should return `false`__ except in certain conditions as described","in the users guide.","","The function receives a single object","argument with the following properties:","","* __td__\tThe `<td>` Node for this cell.","* __cell__\tIf the cell `<td> contains an element with class `yui3-datatable-liner,"," this will refer to that Node. Otherwise, it is equivalent to `td` (default behavior).","* __value__\tThe raw value from the record Model to populate this cell."," Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`.","* __data__\tThe Model data for this row in simple object format.","* __record__\tThe Model for this row.","* __column__\tThe column configuration object.","* __rowIndex__\tThe index of the current Model in the ModelList."," _Typically_ correlates to the row index as well.","","@example"," nodeFormatter: function (o) {"," if (o.value < o.data.quota) {"," o.td.setAttribute('rowspan', 2);"," o.td.setAttribute('data-term-id', this.record.get('id'));",""," o.td.ancestor().insert("," '<tr><td colspan\"3\">' +"," '<button class=\"term\">terminate</button>' +"," '</td></tr>',"," 'after');"," }",""," o.cell.setHTML(o.value);"," return false;"," }","","@property nodeFormatter","@type Function","*/","/**","Provides the default value to populate the cell if the data","for that cell is `undefined`, `null`, or an empty string.",""," {"," key: 'price',"," emptyCellValue: '???'"," }","","@property emptyCellValue","@type {String|HTML} depending on the setting of allowHTML"," */","/**","Skips the security step of HTML escaping the value for cells","in this column.","","This is also necessary if [emptyCellValue](#property_emptyCellValue)","is set with an HTML string.","`nodeFormatter`s ignore this configuration. If using a","`nodeFormatter`, it is recommended to use","[Y.Escape.html()](Escape.html#method_html)","on any user supplied content that is to be displayed.",""," {"," key: 'preview',"," allowHTML: true"," }","","@property allowHTML","@type Boolean","*/","/**","A string of CSS classes that will be added to the `<td>`'s","`class` attribute.","","Note, all cells will automatically have a class in the","form of \"yui3-datatable-col-XXX\" added to the `<td>`, where","XXX is the column's configured `name`, `key`, or `id` (in","that order of preference) sanitized from invalid characters.",""," {"," key: 'symbol',"," className: 'no-hide'"," }","","@property className","@type String","*/","/**","(__read-only__) The unique identifier assigned","to each column. This is used for the `id` if not set, and","the `_id` if none of [name](#property_name),","[field](#property_field), [key](#property_key), or [id](#property_id) are","set.","","@property _yuid","@type String","@protected"," */","/**","(__read-only__) A unique-to-this-instance name","used extensively in the rendering process. It is also used","to create the column's classname, as the input name","`table.getColumn(HERE)`, and in the column header's","`<th data-yui3-col-id=\"HERE\">`.","","The value is populated by the first of [name](#property_name),","[field](#property_field), [key](#property_key), [id](#property_id),"," or [_yuid](#property__yuid) to have a value. If that value","has already been used (such as when multiple columns have","the same `key`), an incrementer is added to the end. For","example, two columns with `key: \"id\"` will have `_id`s of","\"id\" and \"id2\". `table.getColumn(\"id\")` will return the","first column, and `table.getColumn(\"id2\")` will return the","second.","","@property _id","@type String","@protected"," */","/**","(__read-only__) Used by","`Y.DataTable.HeaderView` when building stacked column","headers.","","@property _colspan","@type Integer","@protected"," */","/**","(__read-only__) Used by","`Y.DataTable.HeaderView` when building stacked column","headers.","","@property _rowspan","@type Integer","@protected"," */","/**","(__read-only__) Assigned to all columns in a","column's `children` collection. References the parent","column object.","","@property _parent","@type DataTable.Column","@protected"," */","/**","(__read-only__) Array of the `id`s of the","column and all parent columns. Used by","`Y.DataTable.BodyView` to populate `<td headers=\"THIS\">`","when a cell references more than one header.","","@property _headers","@type Array","@protected","*/","","","}, '@VERSION@', {\"requires\": [\"escape\", \"model-list\", \"node-event-delegate\"]});","","}());"]}; } var __cov_adU3eEuYYFqBLZ6_IZplXQ = __coverage__['build/datatable-core/datatable-core.js']; __cov_adU3eEuYYFqBLZ6_IZplXQ.s['1']++;YUI.add('datatable-core',function(Y,NAME){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['1']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['2']++;var INVALID=Y.Attribute.INVALID_VALUE,Lang=Y.Lang,isFunction=Lang.isFunction,isObject=Lang.isObject,isArray=Lang.isArray,isString=Lang.isString,isNumber=Lang.isNumber,toArray=Y.Array,keys=Y.Object.keys,Table;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['3']++;Table=Y.namespace('DataTable').Core=function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['2']++;};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['4']++;Table.ATTRS={columns:{validator:isArray,setter:'_setColumns',getter:'_getColumns'},recordType:{getter:'_getRecordType',setter:'_setRecordType'},data:{valueFn:'_initData',setter:'_setData',lazyAdd:false},recordset:{setter:'_setRecordset',getter:'_getRecordset',lazyAdd:false},columnset:{setter:'_setColumnset',getter:'_getColumnset',lazyAdd:false}};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['5']++;Y.mix(Table.prototype,{getColumn:function(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['3']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['6']++;var col,columns,i,len,cols;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['7']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][0]++,isObject(name))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][1]++,!isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['8']++;if(name instanceof Y.Node){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['9']++;col=this.body.getColumn(name);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['10']++;col=name;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['11']++;col=this.get('columns.'+name);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['12']++;if(col){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['13']++;return col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['14']++;columns=this.get('columns');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['15']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][0]++,isNumber(name))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][1]++,isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['16']++;name=toArray(name);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['17']++;cols=columns;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['18']++;for(i=0,len=name.length-1;(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][1]++,i<len);++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['19']++;cols=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][0]++,cols[name[i]])&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][1]++,cols[name[i]].children);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['20']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][1]++,cols[name[i]])||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][2]++,null);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['21']++;return null;},getRecord:function(seed){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['4']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['22']++;var record=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][0]++,this.data.getById(seed))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][1]++,this.data.getByClientId(seed));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['23']++;if(!record){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['24']++;if(isNumber(seed)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['25']++;record=this.data.item(seed);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['26']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][0]++,!record)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][1]++,this.view)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][2]++,this.view.getRecord)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['27']++;record=this.view.getRecord.apply(this.view,arguments);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['28']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][0]++,record)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][1]++,null);},_allowAdHocAttrs:true,_afterColumnsChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['5']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['29']++;this._setColumnMap(e.newVal);},_afterDataChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['6']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['30']++;var modelList=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['31']++;this.data=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['32']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][1]++,modelList.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['33']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][1]++;}},_afterRecordTypeChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['7']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['34']++;var data=this.data.toJSON();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['35']++;this.data.model=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['36']++;this.data.reset(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['37']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][1]++,data)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['38']++;if(data.length){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['39']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['40']++;this.set('columns',keys(e.newVal.ATTRS));}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][1]++;}},_createRecordClass:function(attrs){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['8']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['41']++;var ATTRS,i,len;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['42']++;if(isArray(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['43']++;ATTRS={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['44']++;for(i=0,len=attrs.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['45']++;ATTRS[attrs[i]]={};}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['46']++;if(isObject(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['47']++;ATTRS=attrs;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['48']++;return Y.Base.create('record',Y.Model,[],null,{ATTRS:ATTRS});},destructor:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['9']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['49']++;new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();},_getColumns:function(columns,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['10']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['50']++;return name.length>8?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][0]++,this._columnMap):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][1]++,columns);},_getColumnset:function(_,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['11']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['51']++;return this.get(name.replace(/^columnset/,'columns'));},_getRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['12']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['52']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][0]++,val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][1]++,this.data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][2]++,this.data.model);},_initColumns:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['13']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['53']++;var columns=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][0]++,this.get('columns'))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][1]++,[]),item;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['54']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][0]++,!columns.length)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][1]++,this.data.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['55']++;item=this.data.item(0);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['56']++;if(item.toJSON){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['57']++;item=item.toJSON();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['58']++;this.set('columns',keys(item));}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['59']++;this._setColumnMap(columns);},_initCoreEvents:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['14']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['60']++;this._eventHandles.coreAttrChanges=this.after({columnsChange:Y.bind('_afterColumnsChange',this),recordTypeChange:Y.bind('_afterRecordTypeChange',this),dataChange:Y.bind('_afterDataChange',this)});},_initData:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['15']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['61']++;var recordType=this.get('recordType'),modelList=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['62']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['63']++;modelList.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['64']++;return modelList;},_initDataProperty:function(data){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['16']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['65']++;var recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['66']++;if(!this.data){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['67']++;recordType=this.get('recordType');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['68']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][0]++,data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][1]++,data.each)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][2]++,data.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['69']++;this.data=data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['70']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['71']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['72']++;this.data=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['73']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['74']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['75']++;this.data.addTarget(this);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][1]++;}},initializer:function(config){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['17']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['76']++;var data=config.data,columns=config.columns,recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['77']++;this._initDataProperty(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['78']++;if(!columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['79']++;recordType=((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][0]++,config.recordType)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][1]++,config.data===this.data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][2]++,this.get('recordType'));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['80']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['81']++;columns=keys(recordType.ATTRS);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['82']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][0]++,isArray(data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][1]++,data.length)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['83']++;columns=keys(data[0]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['84']++;if(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['85']++;this.set('columns',columns);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['86']++;this._initColumns();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['87']++;this._eventHandles={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['88']++;this._initCoreEvents();},_setColumnMap:function(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['18']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['89']++;var map={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['90']++;function process(cols){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['19']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['91']++;var i,len,col,key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['92']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['93']++;col=cols[i];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['94']++;key=col.key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['95']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][0]++,key)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][1]++,!map[key])){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['96']++;map[key]=col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['97']++;map[col._id]=col;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['98']++;if(col.children){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['99']++;process(col.children);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][1]++;}}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['100']++;process(columns);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['101']++;this._columnMap=map;},_setColumns:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['20']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['102']++;var keys={},known=[],knownCopies=[],arrayIndex=Y.Array.indexOf;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['103']++;function copyObj(o){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['21']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['104']++;var copy={},key,val,i;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['105']++;known.push(o);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['106']++;knownCopies.push(copy);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['107']++;for(key in o){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['108']++;if(o.hasOwnProperty(key)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['109']++;val=o[key];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['110']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['111']++;copy[key]=val.slice();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['112']++;if(isObject(val,true)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['113']++;i=arrayIndex(known,val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['114']++;copy[key]=i===-1?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][0]++,copyObj(val)):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][1]++,knownCopies[i]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['115']++;copy[key]=o[key];}}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['116']++;return copy;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['117']++;function genId(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['22']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['118']++;name=name.replace(/\s+/,'-');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['119']++;if(keys[name]){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['120']++;name+=keys[name]++;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['121']++;keys[name]=1;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['122']++;return name;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['123']++;function process(cols,parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['23']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['124']++;var columns=[],i,len,col,yuid;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['125']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['126']++;columns[i]=col=isString(cols[i])?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][0]++,{key:cols[i]}):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][1]++,copyObj(cols[i]));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['127']++;yuid=Y.stamp(col);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['128']++;if(!col.id){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['129']++;col.id=yuid;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['130']++;if(col.field){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['131']++;col.name=col.field;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['132']++;if(parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['133']++;col._parent=parent;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['134']++;delete col._parent;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['135']++;col._id=genId((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][0]++,col.name)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][1]++,col.key)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][2]++,col.id));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['136']++;if(isArray(col.children)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['137']++;col.children=process(col.children,col);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['138']++;return columns;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['139']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][1]++,process(val));},_setColumnset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['24']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['140']++;this.set('columns',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['141']++;return isArray(val)?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][0]++,val):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][1]++,INVALID);},_setData:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['25']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['142']++;if(val===null){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['143']++;val=[];}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['144']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['145']++;this._initDataProperty();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['146']++;this.data.reset(val,{silent:true});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['147']++;val=this.data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['148']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][0]++,!val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][1]++,!val.each)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][2]++,!val.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['149']++;val=INVALID;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['150']++;return val;},_setRecordset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['26']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['151']++;var data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['152']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][1]++,Y.Recordset)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][2]++,val instanceof Y.Recordset)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['153']++;data=[];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['154']++;val.each(function(record){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['27']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['155']++;data.push(record.get('data'));});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['156']++;val=data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['157']++;this.set('data',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['158']++;return val;},_setRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['28']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['159']++;var modelClass;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['160']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][0]++,isFunction(val))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][1]++,val.prototype.toJSON)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][2]++,val.prototype.setAttrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['161']++;modelClass=val;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['162']++;if(isObject(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['163']++;modelClass=this._createRecordClass(val);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['164']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['66'][0]++,modelClass)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['66'][1]++,INVALID);}});},'@VERSION@',{'requires':['escape','model-list','node-event-delegate']});
specs/fixtures/bug-45.js
royriojas/esformatter-jsx
import React, { Component } from 'react'; import injectProps from '../../helpers/injectProps'; export default class Form extends Component { @injectProps // esfmt-ignore-line render({memberTypes}) { return ( <div style={ { minWidth: '400px'} }> <h4>New Title</h4> { /* Modal Form With Fields */ } </div> ); } }
src/routes.js
frankleng/react-redux-universal-hot-example
import React from 'react'; import {IndexRoute, Route} from 'react-router'; import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth'; import { App, Chat, Home, Widgets, About, Login, LoginSuccess, Survey, NotFound, } from 'containers'; export default (store) => { const requireLogin = (nextState, replaceState, cb) => { function checkAuth() { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replaceState(null, '/'); } cb(); } if (!isAuthLoaded(store.getState())) { store.dispatch(loadAuth()).then(checkAuth); } else { checkAuth(); } }; /** * Please keep routes in alphabetical order */ return ( <Route path="/" component={App}> { /* Home (main) route */ } <IndexRoute component={Home}/> { /* Routes requiring login */ } <Route onEnter={requireLogin}> <Route path="chat" component={Chat}/> <Route path="loginSuccess" component={LoginSuccess}/> </Route> { /* Routes */ } <Route path="about" component={About}/> <Route path="login" component={Login}/> <Route path="survey" component={Survey}/> <Route path="widgets" component={Widgets}/> { /* Catch all route */ } <Route path="*" component={NotFound} status={404} /> </Route> ); };
ajax/libs/6to5/1.13.13/browser.js
luanlmd/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.to5=e()}}(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(root,mod){if(typeof exports=="object"&&typeof module=="object")return mod(exports);if(typeof define=="function"&&define.amd)return define(["exports"],mod);mod(root.acorn||(root.acorn={}))})(this,function(exports){"use strict";exports.version="0.9.1";var options,input,inputLen,sourceFile;exports.parse=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();var startPos=options.locations?[tokPos,new Position]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};exports.parseExpressionAt=function(inpt,pos,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState(pos);initParserState();return parseExpression()};var isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};function setOptions(opts){options={};for(var opt in defaultOptions)options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];sourceFile=options.sourceFile||null;if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){tokens.push(token)}}if(isArray(options.onComment)){var comments=options.onComment;options.onComment=function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation;comment.loc.start=startLoc;comment.loc.end=endLoc}if(options.ranges)comment.range=[start,end];comments.push(comment)}}if(options.strictMode){strict=true}if(options.ecmaVersion>=7){isKeyword=isEcma7Keyword}else if(options.ecmaVersion===6){isKeyword=isEcma6Keyword}else{isKeyword=isEcma5AndLessKeyword}}var getLineInfo=exports.getLineInfo=function(input,offset){for(var line=1,cur=0;;){lineBreak.lastIndex=cur;var match=lineBreak.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length}else break}return{line:line,column:offset-cur}};function Token(){this.type=tokType;this.value=tokVal;this.start=tokStart;this.end=tokEnd;if(options.locations){this.loc=new SourceLocation;this.loc.end=tokEndLoc;this.startLoc=tokStartLoc;this.endLoc=tokEndLoc}if(options.ranges)this.range=[tokStart,tokEnd]}exports.Token=Token;exports.tokenize=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();skipSpace();function getToken(forceRegexp){lastEnd=tokEnd;readToken(forceRegexp);return new Token}getToken.jumpTo=function(pos,reAllowed){tokPos=pos;if(options.locations){tokCurLine=1;tokLineStart=lineBreak.lastIndex=0;var match;while((match=lineBreak.exec(input))&&match.index<pos){++tokCurLine;tokLineStart=match.index+match[0].length}}tokRegexpAllowed=reAllowed;skipSpace()};getToken.noRegexp=function(){tokRegexpAllowed=false};getToken.options=options;return getToken};var tokPos;var tokStart,tokEnd;var tokStartLoc,tokEndLoc;var tokType,tokVal;var tokRegexpAllowed;var tokCurLine,tokLineStart;var lastStart,lastEnd,lastEndLoc;var inFunction,inGenerator,inAsync,labels,strict,inXJSChild,inXJSTag,inXJSChildExpression;var metParenL;var inTemplate;function initParserState(){lastStart=lastEnd=tokPos;if(options.locations)lastEndLoc=new Position;inFunction=inGenerator=inAsync=strict=false;labels=[];skipSpace();readToken()}function raise(pos,message){var loc=getLineInfo(input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=tokPos;throw err}var empty=[];var _num={type:"num"},_regexp={type:"regexp"},_string={type:"string"};var _name={type:"name"},_eof={type:"eof"};var _xjsName={type:"xjsName"},_xjsText={type:"xjsText"};var _break={keyword:"break"},_case={keyword:"case",beforeExpr:true},_catch={keyword:"catch"};var _continue={keyword:"continue"},_debugger={keyword:"debugger"},_default={keyword:"default"};var _do={keyword:"do",isLoop:true},_else={keyword:"else",beforeExpr:true};var _finally={keyword:"finally"},_for={keyword:"for",isLoop:true},_function={keyword:"function"};var _if={keyword:"if"},_return={keyword:"return",beforeExpr:true},_switch={keyword:"switch"};var _throw={keyword:"throw",beforeExpr:true},_try={keyword:"try"},_var={keyword:"var"};var _let={keyword:"let"},_const={keyword:"const"};var _while={keyword:"while",isLoop:true},_with={keyword:"with"},_new={keyword:"new",beforeExpr:true};var _this={keyword:"this"};var _class={keyword:"class"},_extends={keyword:"extends",beforeExpr:true};var _export={keyword:"export"},_import={keyword:"import"};var _yield={keyword:"yield",beforeExpr:true};var _async={keyword:"async"},_await={keyword:"await",beforeExpr:true};var _null={keyword:"null",atomValue:null},_true={keyword:"true",atomValue:true};var _false={keyword:"false",atomValue:false};var _in={keyword:"in",binop:7,beforeExpr:true};var keywordTypes={"break":_break,"case":_case,"catch":_catch,"continue":_continue,"debugger":_debugger,"default":_default,"do":_do,"else":_else,"finally":_finally,"for":_for,"function":_function,"if":_if,"return":_return,"switch":_switch,"throw":_throw,"try":_try,"var":_var,let:_let,"const":_const,"while":_while,"with":_with,"null":_null,"true":_true,"false":_false,"new":_new,"in":_in,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":_this,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":_class,"extends":_extends,"export":_export,"import":_import,"yield":_yield,await:_await,async:_async};var _bracketL={type:"[",beforeExpr:true},_bracketR={type:"]"},_braceL={type:"{",beforeExpr:true};var _braceR={type:"}"},_parenL={type:"(",beforeExpr:true},_parenR={type:")"};var _comma={type:",",beforeExpr:true},_semi={type:";",beforeExpr:true};var _colon={type:":",beforeExpr:true},_dot={type:"."},_question={type:"?",beforeExpr:true};var _arrow={type:"=>",beforeExpr:true},_bquote={type:"`"},_dollarBraceL={type:"${",beforeExpr:true};var _ltSlash={type:"</"};var _ellipsis={type:"...",prefix:true,beforeExpr:true};var _doubleColon={type:"::",beforeExpr:true};var _slash={binop:10,beforeExpr:true},_eq={isAssign:true,beforeExpr:true};var _assign={isAssign:true,beforeExpr:true};var _incDec={postfix:true,prefix:true,isUpdate:true},_prefix={prefix:true,beforeExpr:true};var _logicalOR={binop:1,beforeExpr:true};var _logicalAND={binop:2,beforeExpr:true};var _bitwiseOR={binop:3,beforeExpr:true};var _bitwiseXOR={binop:4,beforeExpr:true};var _bitwiseAND={binop:5,beforeExpr:true};var _equality={binop:6,beforeExpr:true};var _relational={binop:7,beforeExpr:true};var _bitShift={binop:8,beforeExpr:true};var _plusMin={binop:9,prefix:true,beforeExpr:true};var _modulo={binop:10,beforeExpr:true};var _star={binop:10,beforeExpr:true};var _exponent={binop:10,beforeExpr:true};var _lt={binop:7,beforeExpr:true},_gt={binop:7,beforeExpr:true};exports.tokTypes={bracketL:_bracketL,bracketR:_bracketR,braceL:_braceL,braceR:_braceR,parenL:_parenL,parenR:_parenR,comma:_comma,semi:_semi,colon:_colon,dot:_dot,ellipsis:_ellipsis,question:_question,slash:_slash,eq:_eq,name:_name,eof:_eof,num:_num,regexp:_regexp,string:_string,arrow:_arrow,bquote:_bquote,dollarBraceL:_dollarBraceL,star:_star,assign:_assign,xjsName:_xjsName,xjsText:_xjsText,doubleColon:_doubleColon,exponent:_exponent};for(var kw in keywordTypes)exports.tokTypes["_"+kw]=keywordTypes[kw];function makePredicate(words){words=words.split(" ");var f="",cats=[];out:for(var i=0;i<words.length;++i){for(var j=0;j<cats.length;++j)if(cats[j][0].length==words[i].length){cats[j].push(words[i]);continue out}cats.push([words[i]])}function compareTo(arr){if(arr.length==1)return f+="return str === "+JSON.stringify(arr[0])+";";f+="switch(str){";for(var i=0;i<arr.length;++i)f+="case "+JSON.stringify(arr[i])+":";f+="return true}return false;"}if(cats.length>3){cats.sort(function(a,b){return b.length-a.length});f+="switch(str.length){";for(var i=0;i<cats.length;++i){var cat=cats[i];f+="case "+cat[0].length+":";compareTo(cat)}f+="}"}else{compareTo(words)}return new Function("str",f)}var isReservedWord3=makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile");var isReservedWord5=makePredicate("class enum extends super const export import");var isStrictReservedWord=makePredicate("implements interface let package private protected public static yield");var isStrictBadIdWord=makePredicate("eval arguments");var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var isEcma5AndLessKeyword=makePredicate(ecma5AndLessKeywords);var ecma6AndLessKeywords=ecma5AndLessKeywords+" let const class extends export import yield";var isEcma6Keyword=makePredicate(ecma6AndLessKeywords);var isEcma7Keyword=makePredicate(ecma6AndLessKeywords+" async await");var isKeyword=isEcma5AndLessKeyword;var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");var newline=/[\n\r\u2028\u2029]/;var lineBreak=/\r\n|[\n\r\u2028\u2029]/g;var isIdentifierStart=exports.isIdentifierStart=function(code){if(code<65)return code===36;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))};var isIdentifierChar=exports.isIdentifierChar=function(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))};function Position(){this.line=tokCurLine;this.column=tokPos-tokLineStart}function initTokenState(pos){if(pos){tokPos=pos;tokLineStart=Math.max(0,input.lastIndexOf("\n",pos));tokCurLine=input.slice(0,tokLineStart).split(newline).length}else{tokCurLine=1;tokPos=tokLineStart=0}tokRegexpAllowed=true;metParenL=0;inTemplate=inXJSChild=inXJSTag=false}function finishToken(type,val,shouldSkipSpace){tokEnd=tokPos;if(options.locations)tokEndLoc=new Position;tokType=type;if(shouldSkipSpace!==false&&!(inXJSChild&&tokType!==_braceL)){skipSpace()}tokVal=val;tokRegexpAllowed=type.beforeExpr;if(options.onToken){options.onToken(new Token)}}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&new Position;var start=tokPos,end=input.indexOf("*/",tokPos+=2);if(end===-1)raise(tokPos-2,"Unterminated comment");tokPos=end+2;if(options.locations){lineBreak.lastIndex=start;var match;while((match=lineBreak.exec(input))&&match.index<tokPos){++tokCurLine;tokLineStart=match.index+match[0].length}}if(options.onComment)options.onComment(true,input.slice(start+2,end),start,tokPos,startLoc,options.locations&&new Position)}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&new Position;var ch=input.charCodeAt(tokPos+=startSkip);while(tokPos<inputLen&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++tokPos;ch=input.charCodeAt(tokPos)}if(options.onComment)options.onComment(false,input.slice(start+startSkip,tokPos),start,tokPos,startLoc,options.locations&&new Position)}function skipSpace(){while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(ch===32){++tokPos}else if(ch===13){++tokPos;var next=input.charCodeAt(tokPos);if(next===10){++tokPos}if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch===10||ch===8232||ch===8233){++tokPos;if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch>8&&ch<14){++tokPos}else if(ch===47){var next=input.charCodeAt(tokPos+1);if(next===42){skipBlockComment()}else if(next===47){skipLineComment(2)}else break}else if(ch===160){++tokPos}else if(ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++tokPos}else{break}}}function readToken_dot(){var next=input.charCodeAt(tokPos+1);if(next>=48&&next<=57)return readNumber(true);var next2=input.charCodeAt(tokPos+2);if(options.ecmaVersion>=6&&next===46&&next2===46){tokPos+=3;return finishToken(_ellipsis)}else{++tokPos;return finishToken(_dot)}}function readToken_slash(){var next=input.charCodeAt(tokPos+1);if(tokRegexpAllowed){++tokPos;return readRegexp()}if(next===61)return finishOp(_assign,2);return finishOp(_slash,1)}function readToken_modulo(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_modulo,1)}function readToken_mult(){var type=_star;var width=1;var next=input.charCodeAt(tokPos+1);if(options.ecmaVersion>=7&&next===42){width++;next=input.charCodeAt(tokPos+2);type=_exponent}if(next===61){width++;type=_assign}return finishOp(type,width)}function readToken_pipe_amp(code){var next=input.charCodeAt(tokPos+1);if(next===code)return finishOp(code===124?_logicalOR:_logicalAND,2);if(next===61)return finishOp(_assign,2);return finishOp(code===124?_bitwiseOR:_bitwiseAND,1)}function readToken_caret(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_bitwiseXOR,1)}function readToken_plus_min(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(next==45&&input.charCodeAt(tokPos+2)==62&&newline.test(input.slice(lastEnd,tokPos))){skipLineComment(3);skipSpace();return readToken()}return finishOp(_incDec,2)}if(next===61)return finishOp(_assign,2);return finishOp(_plusMin,1)}function readToken_lt_gt(code){var next=input.charCodeAt(tokPos+1);var size=1;if(next===code){size=code===62&&input.charCodeAt(tokPos+2)===62?3:2;if(input.charCodeAt(tokPos+size)===61)return finishOp(_assign,size+1);return finishOp(_bitShift,size)}if(next==33&&code==60&&input.charCodeAt(tokPos+2)==45&&input.charCodeAt(tokPos+3)==45){skipLineComment(4);skipSpace();return readToken()}if(next===61){size=input.charCodeAt(tokPos+2)===61?3:2;return finishOp(_relational,size)}if(next===47){size=2;return finishOp(_ltSlash,size)}return code===60?finishOp(_lt,size):finishOp(_gt,size,!inXJSTag)}function readToken_eq_excl(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_equality,input.charCodeAt(tokPos+2)===61?3:2);if(code===61&&next===62&&options.ecmaVersion>=6){tokPos+=2;return finishToken(_arrow)}return finishOp(code===61?_eq:_prefix,1)}function getTemplateToken(code){if(tokType===_string){if(code===96){++tokPos;return finishToken(_bquote)}else if(code===36&&input.charCodeAt(tokPos+1)===123){tokPos+=2;return finishToken(_dollarBraceL)}}if(code===125){++tokPos;return finishToken(_braceR,undefined,false)}return readTmplString()}function getTokenFromCode(code){switch(code){case 46:return readToken_dot();case 40:++tokPos;return finishToken(_parenL);case 41:++tokPos;return finishToken(_parenR);case 59:++tokPos;return finishToken(_semi);case 44:++tokPos;return finishToken(_comma);case 91:++tokPos;return finishToken(_bracketL);case 93:++tokPos;return finishToken(_bracketR);case 123:++tokPos;return finishToken(_braceL);case 125:++tokPos;return finishToken(_braceR,undefined,!inXJSChildExpression);case 63:++tokPos;return finishToken(_question);case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_doubleColon)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return finishToken(_bquote,undefined,false)}case 48:var next=input.charCodeAt(tokPos+1);if(next===120||next===88)return readRadixNumber(16);if(options.ecmaVersion>=6){if(next===111||next===79)return readRadixNumber(8);if(next===98||next===66)return readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(false);case 34:case 39:return inXJSTag?readXJSStringLiteral():readString(code);case 47:return readToken_slash();case 37:return readToken_modulo();case 42:return readToken_mult();case 124:case 38:return readToken_pipe_amp(code);case 94:return readToken_caret();case 43:case 45:return readToken_plus_min(code);case 60:case 62:return readToken_lt_gt(code);case 61:case 33:return readToken_eq_excl(code);case 126:return finishOp(_prefix,1)}return false}function readToken(forceRegexp){if(!forceRegexp)tokStart=tokPos;else tokPos=tokStart+1;if(options.locations)tokStartLoc=new Position;if(forceRegexp)return readRegexp();if(tokPos>=inputLen)return finishToken(_eof);var code=input.charCodeAt(tokPos);if(inXJSChild&&tokType!==_braceL&&code!==60&&code!==123&&code!==125){return readXJSText(["<","{"])}if(inTemplate)return getTemplateToken(code);if(isIdentifierStart(code)||code===92)return readWord();var tok=getTokenFromCode(code);if(tok===false){var ch=String.fromCharCode(code);if(ch==="\\"||nonASCIIidentifierStart.test(ch))return readWord();raise(tokPos,"Unexpected character '"+ch+"'")}return tok}function finishOp(type,size,shouldSkipSpace){var str=input.slice(tokPos,tokPos+size);tokPos+=size;finishToken(type,str,shouldSkipSpace)}var regexpUnicodeSupport=false;try{new RegExp("￿","u");regexpUnicodeSupport=true}catch(e){}function readRegexp(){var content="",escaped,inClass,start=tokPos;for(;;){if(tokPos>=inputLen)raise(start,"Unterminated regular expression");var ch=nextChar();if(newline.test(ch))raise(start,"Unterminated regular expression");if(!escaped){if(ch==="[")inClass=true;else if(ch==="]"&&inClass)inClass=false;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}else escaped=false;++tokPos}var content=input.slice(start,tokPos);++tokPos;var mods=readWord1();var tmp=content;if(mods){var validFlags=/^[gmsiy]*$/;if(options.ecmaVersion>=6)validFlags=/^[gmsiyu]*$/;if(!validFlags.test(mods))raise(start,"Invalid regular expression flag");if(mods.indexOf("u")>=0&&!regexpUnicodeSupport){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(tmp)}catch(e){if(e instanceof SyntaxError)raise(start,"Error parsing regular expression: "+e.message);raise(e)}try{var value=new RegExp(content,mods)}catch(err){value=null}return finishToken(_regexp,{pattern:content,flags:mods,value:value})}function readInt(radix,len){var start=tokPos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=input.charCodeAt(tokPos),val;if(code>=97)val=code-97+10;else if(code>=65)val=code-65+10;else if(code>=48&&code<=57)val=code-48;else val=Infinity;if(val>=radix)break;++tokPos;total=total*radix+val}if(tokPos===start||len!=null&&tokPos-start!==len)return null;return total}function readRadixNumber(radix){tokPos+=2;var val=readInt(radix);if(val==null)raise(tokStart+2,"Expected number in radix "+radix);if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");return finishToken(_num,val)}function readNumber(startsWithDot){var start=tokPos,isFloat=false,octal=input.charCodeAt(tokPos)===48;if(!startsWithDot&&readInt(10)===null)raise(start,"Invalid number");if(input.charCodeAt(tokPos)===46){++tokPos;readInt(10);isFloat=true}var next=input.charCodeAt(tokPos);if(next===69||next===101){next=input.charCodeAt(++tokPos);if(next===43||next===45)++tokPos;if(readInt(10)===null)raise(start,"Invalid number");isFloat=true}if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");var str=input.slice(start,tokPos),val;if(isFloat)val=parseFloat(str);else if(!octal||str.length===1)val=parseInt(str,10);else if(/[89]/.test(str)||strict)raise(start,"Invalid number");else val=parseInt(str,8);return finishToken(_num,val)}function readCodePoint(){var ch=input.charCodeAt(tokPos),code;if(ch===123){if(options.ecmaVersion<6)unexpected();++tokPos;code=readHexChar(input.indexOf("}",tokPos)-tokPos);++tokPos;if(code>1114111)unexpected()}else{code=readHexChar(4)}if(code<=65535){return String.fromCharCode(code)}var cu1=(code-65536>>10)+55296;var cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function readString(quote){++tokPos;var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===quote){++tokPos;return finishToken(_string,out)}if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){raise(tokStart,"Unterminated string constant")}out+=String.fromCharCode(ch)}}}function readTmplString(){var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===96||ch===36&&input.charCodeAt(tokPos+1)===123)return finishToken(_string,out);if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;ch=10}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=String.fromCharCode(ch)}}}function readEscapedChar(){var ch=input.charCodeAt(++tokPos);var octal=/^[0-7]+/.exec(input.slice(tokPos,tokPos+3));if(octal)octal=octal[0];while(octal&&parseInt(octal,8)>255)octal=octal.slice(0,-1);if(octal==="0")octal=null;++tokPos;if(octal){if(strict)raise(tokPos-2,"Octal literal in strict mode");tokPos+=octal.length-1;return String.fromCharCode(parseInt(octal,8))}else{switch(ch){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(readHexChar(2));case 117:return readCodePoint();case 116:return" ";case 98:return"\b";case 118:return" ";case 102:return"\f";case 48:return"\x00";case 13:if(input.charCodeAt(tokPos)===10)++tokPos;case 10:if(options.locations){tokLineStart=tokPos;++tokCurLine}return"";default:return String.fromCharCode(ch)}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readXJSEntity(){var str="",count=0,entity;var ch=nextChar();if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");tokPos++;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){break}str+=ch}if(str[0]==="#"&&str[1]==="x"){entity=String.fromCharCode(parseInt(str.substr(2),16))}else if(str[0]==="#"){entity=String.fromCharCode(parseInt(str.substr(1),10))}else{entity=XHTMLEntities[str]}return entity}function readXJSText(stopChars){var str="";while(tokPos<inputLen){var ch=nextChar();if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=readXJSEntity()}else{++tokPos;if(ch==="\r"&&nextChar()==="\n"){str+=ch;++tokPos;ch="\n"}if(ch==="\n"&&options.locations){tokLineStart=tokPos;++tokCurLine}str+=ch}}return finishToken(_xjsText,str)}function readXJSStringLiteral(){var quote=input.charCodeAt(tokPos);if(quote!==34&&quote!==39){raise("String literal must starts with a quote")}++tokPos;readXJSText([String.fromCharCode(quote)]);if(quote!==input.charCodeAt(tokPos)){unexpected()}++tokPos;return finishToken(tokType,tokVal)}function readHexChar(len){var n=readInt(16,len);if(n===null)raise(tokStart,"Bad character escape sequence");return n}var containsEsc;function readWord1(){containsEsc=false;var word,first=true,start=tokPos;for(;;){var ch=input.charCodeAt(tokPos);if(isIdentifierChar(ch)||inXJSTag&&ch===45){if(containsEsc)word+=nextChar();++tokPos}else if(ch===92&&!inXJSTag){if(!containsEsc)word=input.slice(start,tokPos);containsEsc=true;if(input.charCodeAt(++tokPos)!=117)raise(tokPos,"Expecting Unicode escape sequence \\uXXXX");++tokPos;var esc=readHexChar(4);var escStr=String.fromCharCode(esc);if(!escStr)raise(tokPos-1,"Invalid Unicode escape");if(!(first?isIdentifierStart(esc):isIdentifierChar(esc)))raise(tokPos-4,"Invalid Unicode escape");word+=escStr}else{break}first=false}return containsEsc?word:input.slice(start,tokPos)}function readWord(){var word=readWord1();var type=inXJSTag?_xjsName:_name;if(!containsEsc&&isKeyword(word))type=keywordTypes[word];return finishToken(type,word)}function next(){lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;readToken()}function setStrict(strct){strict=strct;tokPos=tokStart;if(options.locations){while(tokPos<tokLineStart){tokLineStart=input.lastIndexOf("\n",tokLineStart-2)+1;--tokCurLine}}skipSpace();readToken()}function Node(){this.type=null;this.start=tokStart;this.end=null}exports.Node=Node;function SourceLocation(){this.start=tokStartLoc;this.end=null;if(sourceFile!==null)this.source=sourceFile}function startNode(){var node=new Node;if(options.locations)node.loc=new SourceLocation;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[tokStart,0];return node}function storeCurrentPos(){return options.locations?[tokStart,tokStartLoc]:tokStart}function startNodeAt(pos){var node=new Node,start=pos;if(options.locations){node.loc=new SourceLocation;node.loc.start=start[1];start=pos[0]}node.start=start;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[start,0];return node}function finishNode(node,type){node.type=type;node.end=lastEnd;if(options.locations)node.loc.end=lastEndLoc;if(options.ranges)node.range[1]=lastEnd;return node}function isUseStrict(stmt){return options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.value==="use strict"}function eat(type){if(tokType===type){next();return true}else{return false}}function canInsertSemicolon(){return!options.strictSemicolons&&(tokType===_eof||tokType===_braceR||newline.test(input.slice(lastEnd,tokStart)))}function semicolon(){if(!eat(_semi)&&!canInsertSemicolon())unexpected()}function expect(type){eat(type)||unexpected()}function nextChar(){return input.charAt(tokPos)}function unexpected(pos){raise(pos!=null?pos:tokStart,"Unexpected token")}function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)}function toAssignable(node,allowSpread,checkType){if(options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":case"MemberExpression":break;case"ObjectExpression":node.type="ObjectPattern";for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(prop.type==="Property"&&prop.kind!=="init")unexpected(prop.key.start);toAssignable(prop.value,false,checkType)}break;case"ArrayExpression":node.type="ArrayPattern";for(var i=0,lastI=node.elements.length-1;i<=lastI;i++){toAssignable(node.elements[i],i===lastI,checkType)}break;case"SpreadElement":if(allowSpread){toAssignable(node.argument,false,checkType);checkSpreadAssign(node.argument)}else{unexpected(node.start)}break;default:if(checkType)unexpected(node.start)}}return node}function checkSpreadAssign(node){if(node.type!=="Identifier"&&node.type!=="ArrayPattern")unexpected(node.start)}function checkFunctionParam(param,nameHash){switch(param.type){case"Identifier":if(isStrictReservedWord(param.name)||isStrictBadIdWord(param.name))raise(param.start,"Defining '"+param.name+"' in strict mode");if(has(nameHash,param.name))raise(param.start,"Argument name clash in strict mode");nameHash[param.name]=true;break;case"ObjectPattern":for(var i=0;i<param.properties.length;i++)checkFunctionParam(param.properties[i].value,nameHash);break;case"ArrayPattern":for(var i=0;i<param.elements.length;i++){var elem=param.elements[i];if(elem)checkFunctionParam(elem,nameHash)}break}}function checkPropClash(prop,propHash){if(options.ecmaVersion>=6)return; var key=prop.key,name;switch(key.type){case"Identifier":name=key.name;break;case"Literal":name=String(key.value);break;default:return}var kind=prop.kind||"init",other;if(has(propHash,name)){other=propHash[name];var isGetSet=kind!=="init";if((strict||isGetSet)&&other[kind]||!(isGetSet^other.init))raise(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}}other[kind]=true}function checkLVal(expr,isBinding){switch(expr.type){case"Identifier":if(strict&&(isStrictBadIdWord(expr.name)||isStrictReservedWord(expr.name)))raise(expr.start,isBinding?"Binding "+expr.name+" in strict mode":"Assigning to "+expr.name+" in strict mode");break;case"MemberExpression":if(!isBinding)break;case"ObjectPattern":for(var i=0;i<expr.properties.length;i++){var prop=expr.properties[i];if(prop.type==="Property")prop=prop.value;checkLVal(prop,isBinding)}break;case"ArrayPattern":for(var i=0;i<expr.elements.length;i++){var elem=expr.elements[i];if(elem)checkLVal(elem,isBinding)}break;case"SpreadProperty":case"SpreadElement":case"VirtualPropertyExpression":break;default:raise(expr.start,"Assigning to rvalue")}}function parseTopLevel(node){var first=true;if(!node.body)node.body=[];while(tokType!==_eof){var stmt=parseStatement();node.body.push(stmt);if(first&&isUseStrict(stmt))setStrict(true);first=false}lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;return finishNode(node,"Program")}var loopLabel={kind:"loop"},switchLabel={kind:"switch"};function parseStatement(){if(tokType===_slash||tokType===_assign&&tokVal=="/=")readToken(true);var starttype=tokType,node=startNode();switch(starttype){case _break:case _continue:return parseBreakContinueStatement(node,starttype.keyword);case _debugger:return parseDebuggerStatement(node);case _do:return parseDoStatement(node);case _for:return parseForStatement(node);case _async:return parseAsync(node,true);case _function:return parseFunctionStatement(node);case _class:return parseClass(node,true);case _if:return parseIfStatement(node);case _return:return parseReturnStatement(node);case _switch:return parseSwitchStatement(node);case _throw:return parseThrowStatement(node);case _try:return parseTryStatement(node);case _var:case _let:case _const:return parseVarStatement(node,starttype.keyword);case _while:return parseWhileStatement(node);case _with:return parseWithStatement(node);case _braceL:return parseBlock();case _semi:return parseEmptyStatement(node);case _export:return parseExport(node);case _import:return parseImport(node);default:var maybeName=tokVal,expr=parseExpression();if(starttype===_name&&expr.type==="Identifier"&&eat(_colon))return parseLabeledStatement(node,maybeName,expr);else return parseExpressionStatement(node,expr)}}function parseBreakContinueStatement(node,keyword){var isBreak=keyword=="break";next();if(eat(_semi)||canInsertSemicolon())node.label=null;else if(tokType!==_name)unexpected();else{node.label=parseIdent();semicolon()}for(var i=0;i<labels.length;++i){var lab=labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break;if(node.label&&isBreak)break}}if(i===labels.length)raise(node.start,"Unsyntactic "+keyword);return finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}function parseDebuggerStatement(node){next();semicolon();return finishNode(node,"DebuggerStatement")}function parseDoStatement(node){next();labels.push(loopLabel);node.body=parseStatement();labels.pop();expect(_while);node.test=parseParenExpression();semicolon();return finishNode(node,"DoWhileStatement")}function parseForStatement(node){next();labels.push(loopLabel);expect(_parenL);if(tokType===_semi)return parseFor(node,null);if(tokType===_var||tokType===_let){var init=startNode(),varKind=tokType.keyword,isLet=tokType===_let;next();parseVar(init,true,varKind);finishNode(init,"VariableDeclaration");if((tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of")&&init.declarations.length===1&&!(isLet&&init.declarations[0].init))return parseForIn(node,init);return parseFor(node,init)}var init=parseExpression(false,true);if(tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of"){checkLVal(init);return parseForIn(node,init)}return parseFor(node,init)}function parseFunctionStatement(node){next();return parseFunction(node,true,false)}function parseAsync(node,isStatement){if(options.ecmaVersion<7){unexpected()}next();switch(tokType){case _function:next();return parseFunction(node,isStatement,true);if(!isStatement)unexpected();case _name:var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(node,[id],true)}case _parenL:var oldParenL=++metParenL;var exprList=[];next();if(tokType!==_parenR){var val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){return parseArrowExpression(node,exprList,true)}default:unexpected()}}function parseIfStatement(node){next();node.test=parseParenExpression();node.consequent=parseStatement();node.alternate=eat(_else)?parseStatement():null;return finishNode(node,"IfStatement")}function parseReturnStatement(node){if(!inFunction&&!options.allowReturnOutsideFunction)raise(tokStart,"'return' outside of function");next();if(eat(_semi)||canInsertSemicolon())node.argument=null;else{node.argument=parseExpression();semicolon()}return finishNode(node,"ReturnStatement")}function parseSwitchStatement(node){next();node.discriminant=parseParenExpression();node.cases=[];expect(_braceL);labels.push(switchLabel);for(var cur,sawDefault;tokType!=_braceR;){if(tokType===_case||tokType===_default){var isCase=tokType===_case;if(cur)finishNode(cur,"SwitchCase");node.cases.push(cur=startNode());cur.consequent=[];next();if(isCase)cur.test=parseExpression();else{if(sawDefault)raise(lastStart,"Multiple default clauses");sawDefault=true;cur.test=null}expect(_colon)}else{if(!cur)unexpected();cur.consequent.push(parseStatement())}}if(cur)finishNode(cur,"SwitchCase");next();labels.pop();return finishNode(node,"SwitchStatement")}function parseThrowStatement(node){next();if(newline.test(input.slice(lastEnd,tokStart)))raise(lastEnd,"Illegal newline after throw");node.argument=parseExpression();semicolon();return finishNode(node,"ThrowStatement")}function parseTryStatement(node){next();node.block=parseBlock();node.handler=null;if(tokType===_catch){var clause=startNode();next();expect(_parenL);clause.param=parseIdent();if(strict&&isStrictBadIdWord(clause.param.name))raise(clause.param.start,"Binding "+clause.param.name+" in strict mode");expect(_parenR);clause.guard=null;clause.body=parseBlock();node.handler=finishNode(clause,"CatchClause")}node.guardedHandlers=empty;node.finalizer=eat(_finally)?parseBlock():null;if(!node.handler&&!node.finalizer)raise(node.start,"Missing catch or finally clause");return finishNode(node,"TryStatement")}function parseVarStatement(node,kind){next();parseVar(node,false,kind);semicolon();return finishNode(node,"VariableDeclaration")}function parseWhileStatement(node){next();node.test=parseParenExpression();labels.push(loopLabel);node.body=parseStatement();labels.pop();return finishNode(node,"WhileStatement")}function parseWithStatement(node){if(strict)raise(tokStart,"'with' in strict mode");next();node.object=parseParenExpression();node.body=parseStatement();return finishNode(node,"WithStatement")}function parseEmptyStatement(node){next();return finishNode(node,"EmptyStatement")}function parseLabeledStatement(node,maybeName,expr){for(var i=0;i<labels.length;++i)if(labels[i].name===maybeName)raise(expr.start,"Label '"+maybeName+"' is already declared");var kind=tokType.isLoop?"loop":tokType===_switch?"switch":null;labels.push({name:maybeName,kind:kind});node.body=parseStatement();labels.pop();node.label=expr;return finishNode(node,"LabeledStatement")}function parseExpressionStatement(node,expr){node.expression=expr;semicolon();return finishNode(node,"ExpressionStatement")}function parseParenExpression(){expect(_parenL);var val=parseExpression();expect(_parenR);return val}function parseBlock(allowStrict){var node=startNode(),first=true,oldStrict;node.body=[];expect(_braceL);while(!eat(_braceR)){var stmt=parseStatement();node.body.push(stmt);if(first&&allowStrict&&isUseStrict(stmt)){oldStrict=strict;setStrict(strict=true)}first=false}if(oldStrict===false)setStrict(false);return finishNode(node,"BlockStatement")}function parseFor(node,init){node.init=init;expect(_semi);node.test=tokType===_semi?null:parseExpression();expect(_semi);node.update=tokType===_parenR?null:parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,"ForStatement")}function parseForIn(node,init){var type=tokType===_in?"ForInStatement":"ForOfStatement";next();node.left=init;node.right=parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,type)}function parseVar(node,noIn,kind){node.declarations=[];node.kind=kind;for(;;){var decl=startNode();decl.id=options.ecmaVersion>=6?toAssignable(parseExprAtom()):parseIdent();checkLVal(decl.id,true);decl.init=eat(_eq)?parseExpression(true,noIn):kind===_const.keyword?unexpected():null;node.declarations.push(finishNode(decl,"VariableDeclarator"));if(!eat(_comma))break}return node}function parseExpression(noComma,noIn){var start=storeCurrentPos();var expr=parseMaybeAssign(noIn);if(!noComma&&tokType===_comma){var node=startNodeAt(start);node.expressions=[expr];while(eat(_comma))node.expressions.push(parseMaybeAssign(noIn));return finishNode(node,"SequenceExpression")}return expr}function parseMaybeAssign(noIn){var start=storeCurrentPos();var left=parseMaybeConditional(noIn);if(tokType.isAssign){var node=startNodeAt(start);node.operator=tokVal;node.left=tokType===_eq?toAssignable(left):left;checkLVal(left);next();node.right=parseMaybeAssign(noIn);return finishNode(node,"AssignmentExpression")}return left}function parseMaybeConditional(noIn){var start=storeCurrentPos();var expr=parseExprOps(noIn);if(eat(_question)){var node=startNodeAt(start);node.test=expr;node.consequent=parseExpression(true);expect(_colon);node.alternate=parseExpression(true,noIn);return finishNode(node,"ConditionalExpression")}return expr}function parseExprOps(noIn){var start=storeCurrentPos();return parseExprOp(parseMaybeUnary(),start,-1,noIn)}function parseExprOp(left,leftStart,minPrec,noIn){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)){if(prec>minPrec){var node=startNodeAt(leftStart);node.left=left;node.operator=tokVal;var op=tokType;next();var start=storeCurrentPos();node.right=parseExprOp(parseMaybeUnary(),start,prec,noIn);finishNode(node,op===_logicalOR||op===_logicalAND?"LogicalExpression":"BinaryExpression");return parseExprOp(node,leftStart,minPrec,noIn)}}return left}function parseMaybeUnary(){if(tokType.prefix){var node=startNode(),update=tokType.isUpdate,nodeType;if(tokType===_ellipsis){nodeType="SpreadElement"}else{nodeType=update?"UpdateExpression":"UnaryExpression";node.operator=tokVal;node.prefix=true}tokRegexpAllowed=true;next();node.argument=parseMaybeUnary();if(update)checkLVal(node.argument);else if(strict&&node.operator==="delete"&&node.argument.type==="Identifier")raise(node.start,"Deleting local variable in strict mode");return finishNode(node,nodeType)}var start=storeCurrentPos();var expr=parseExprSubscripts();while(tokType.postfix&&!canInsertSemicolon()){var node=startNodeAt(start);node.operator=tokVal;node.prefix=false;node.argument=expr;checkLVal(expr);next();expr=finishNode(node,"UpdateExpression")}return expr}function parseExprSubscripts(){var start=storeCurrentPos();return parseSubscripts(parseExprAtom(),start)}function parseSubscripts(base,start,noCalls){if(eat(_doubleColon)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);return parseSubscripts(finishNode(node,"VirtualPropertyExpression"),start,noCalls)}else if(eat(_dot)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);node.computed=false;return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(eat(_bracketL)){var node=startNodeAt(start);node.object=base;node.property=parseExpression();node.computed=true;expect(_bracketR);return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(!noCalls&&eat(_parenL)){var node=startNodeAt(start);node.callee=base;node.arguments=parseExprList(_parenR,false);return parseSubscripts(finishNode(node,"CallExpression"),start,noCalls)}else if(tokType===_bquote){var node=startNodeAt(start);node.tag=base;node.quasi=parseTemplate();return parseSubscripts(finishNode(node,"TaggedTemplateExpression"),start,noCalls)}return base}function parseExprAtom(){switch(tokType){case _this:var node=startNode();next();return finishNode(node,"ThisExpression");case _yield:if(inGenerator)return parseYield();case _await:if(inAsync)return parseAwait();case _name:var start=storeCurrentPos();var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(startNodeAt(start),[id])}return id;case _regexp:var node=startNode();node.regex={pattern:tokVal.pattern,flags:tokVal.flags};node.value=tokVal.value;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _num:case _string:case _xjsText:var node=startNode();node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _null:case _true:case _false:var node=startNode();node.value=tokType.atomValue;node.raw=tokType.keyword;next();return finishNode(node,"Literal");case _parenL:var start=storeCurrentPos();var val,exprList;next();if(options.ecmaVersion>=7&&tokType===_for){val=parseComprehension(startNodeAt(start),true)}else{var oldParenL=++metParenL;if(tokType!==_parenR){val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){val=parseArrowExpression(startNodeAt(start),exprList)}else{if(!val)unexpected(lastStart);if(options.ecmaVersion>=6){for(var i=0;i<exprList.length;i++){if(exprList[i].type==="SpreadElement")unexpected()}}if(options.preserveParens){var par=startNodeAt(start);par.expression=val;val=finishNode(par,"ParenthesizedExpression")}}}return val;case _bracketL:var node=startNode();next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(node,false)}node.elements=parseExprList(_bracketR,true,true);return finishNode(node,"ArrayExpression");case _braceL:return parseObj();case _async:return parseAsync(startNode(),false);case _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _bquote:return parseTemplate();case _lt:return parseXJSElement();default:unexpected()}}function parseNew(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL))node.arguments=parseExprList(_parenR,false);else node.arguments=empty;return finishNode(node,"NewExpression")}function parseTemplate(){var node=startNode();node.expressions=[];node.quasis=[];inTemplate=true;next();for(;;){var elem=startNode();elem.value={cooked:tokVal,raw:input.slice(tokStart,tokEnd)};elem.tail=false;next();node.quasis.push(finishNode(elem,"TemplateElement"));if(tokType===_bquote){elem.tail=true;break}inTemplate=false;expect(_dollarBraceL);node.expressions.push(parseExpression());inTemplate=true;tokPos=tokEnd;expect(_braceR)}inTemplate=false;next();return finishNode(node,"TemplateLiteral")}function parseObj(){var node=startNode(),first=true,propHash={};node.properties=[];var origInXJSChildExpression=inXJSChildExpression;inXJSChildExpression=false;next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),isGenerator,isAsync;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;isGenerator=eat(_star)}if(options.ecmaVersion>=7&&tokType===_ellipsis){if(isAsync||isGenerator)unexpected();prop=parseMaybeUnary();prop.type="SpreadProperty";node.properties.push(prop);continue}parsePropertyName(prop);if(eat(_colon)){prop.value=parseExpression(true);prop.kind="init"}else if(options.ecmaVersion>=6&&tokType===_parenL){prop.kind="init";prop.method=true;prop.value=parseMethod(isGenerator,isAsync)}else if(options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")){if(isGenerator||isAsync)unexpected();prop.kind=prop.key.name;parsePropertyName(prop);prop.value=parseMethod(false,false)}else if(options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){prop.kind="init";prop.value=prop.key;prop.shorthand=true}else unexpected();checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}inXJSChildExpression=origInXJSChildExpression;return finishNode(node,"ObjectExpression")}function parsePropertyName(prop){if(options.ecmaVersion>=6){if(eat(_bracketL)){prop.computed=true;prop.key=parseExpression();expect(_bracketR);return}else{prop.computed=false}}prop.key=tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function initFunction(node,isAsync){node.id=null;node.params=[];if(options.ecmaVersion>=6){node.defaults=[];node.rest=null;node.generator=false}if(options.ecmaVersion>=7){node.async=isAsync}}function parseFunction(node,isStatement,isAsync,allowExpressionBody){initFunction(node,isAsync);if(options.ecmaVersion>=6){if(isAsync&&tokType===_star)unexpected();node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}parseFunctionParams(node);parseFunctionBody(node,allowExpressionBody);return finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")}function parseMethod(isGenerator,isAsync){var node=startNode();initFunction(node,isAsync);parseFunctionParams(node);var allowExpressionBody;if(options.ecmaVersion>=6){node.generator=isGenerator;allowExpressionBody=true}else{allowExpressionBody=false}parseFunctionBody(node,allowExpressionBody);return finishNode(node,"FunctionExpression")}function parseArrowExpression(node,params,isAsync){initFunction(node,isAsync);var defaults=node.defaults,hasDefaults=false;for(var i=0,lastI=params.length-1;i<=lastI;i++){var param=params[i];if(param.type==="AssignmentExpression"&&param.operator==="="){hasDefaults=true;params[i]=param.left;defaults.push(param.right)}else{toAssignable(param,i===lastI,true);defaults.push(null);if(param.type==="SpreadElement"){params.length--;node.rest=param.argument;break}}}node.params=params;if(!hasDefaults)node.defaults=[];parseFunctionBody(node,true);return finishNode(node,"ArrowFunctionExpression")}function parseFunctionParams(node){var defaults=[],hasDefaults=false;expect(_parenL);for(;;){if(eat(_parenR)){break}else if(options.ecmaVersion>=6&&eat(_ellipsis)){node.rest=toAssignable(parseExprAtom(),false,true);checkSpreadAssign(node.rest);expect(_parenR);defaults.push(null);break}else{node.params.push(options.ecmaVersion>=6?toAssignable(parseExprAtom(),false,true):parseIdent());if(options.ecmaVersion>=6){if(eat(_eq)){hasDefaults=true;defaults.push(parseExpression(true))}else{defaults.push(null)}}if(!eat(_comma)){expect(_parenR);break}}}if(hasDefaults)node.defaults=defaults}function parseFunctionBody(node,allowExpression){var isExpression=allowExpression&&tokType!==_braceL;var oldInAsync=inAsync;inAsync=node.async;if(isExpression){node.body=parseExpression(true);node.expression=true}else{var oldInFunc=inFunction,oldInGen=inGenerator,oldLabels=labels;inFunction=true;inGenerator=node.generator;labels=[];node.body=parseBlock(true);node.expression=false;inFunction=oldInFunc;inGenerator=oldInGen;labels=oldLabels}inAsync=oldInAsync;if(strict||!isExpression&&node.body.body.length&&isUseStrict(node.body.body[0])){var nameHash={};if(node.id)checkFunctionParam(node.id,{});for(var i=0;i<node.params.length;i++)checkFunctionParam(node.params[i],nameHash);if(node.rest)checkFunctionParam(node.rest,nameHash)}}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;node.superClass=eat(_extends)?parseExpression():null;var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){var method=startNode();if(tokType===_name&&tokVal==="static"){next();method["static"]=true}else{method["static"]=false}var isAsync=false;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}var isGenerator=eat(_star);parsePropertyName(method);if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set")){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}method.value=parseMethod(isGenerator,isAsync);classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseExprList(close,allowTrailingComma,allowEmpty){var elts=[],first=true;while(!eat(close)){if(!first){expect(_comma);if(allowTrailingComma&&options.allowTrailingCommas&&eat(close))break}else first=false;if(allowEmpty&&tokType===_comma)elts.push(null);else elts.push(parseExpression(true))}return elts}function parseIdent(liberal){var node=startNode();if(liberal&&options.forbidReserved=="everywhere")liberal=false;if(tokType===_name){if(!liberal&&(options.forbidReserved&&(options.ecmaVersion===3?isReservedWord3:isReservedWord5)(tokVal)||strict&&isStrictReservedWord(tokVal))&&input.slice(tokStart,tokEnd).indexOf("\\")==-1)raise(tokStart,"The keyword '"+tokVal+"' is reserved");node.name=tokVal}else if(liberal&&tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"Identifier")}function parseExport(node){next();if(tokType===_var||tokType===_const||tokType===_let||tokType===_function||tokType===_class||tokType===_async){node.declaration=parseStatement();node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){node.declaration=parseExpression(true);node["default"]=true;node.specifiers=null;node.source=null;semicolon()}else{var isBatch=tokType===_star;node.declaration=null;node["default"]=false;node.specifiers=parseExportSpecifiers();if(tokType===_name&&tokVal==="from"){next();node.source=tokType===_string?parseExprAtom():unexpected()}else{if(isBatch)unexpected();node.source=null}semicolon()}return finishNode(node,"ExportDeclaration")}function parseExportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();nodes.push(finishNode(node,"ExportBatchSpecifier"))}else{expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(tokType===_default);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent(true)}else{node.name=null}nodes.push(finishNode(node,"ExportSpecifier"))}}return nodes}function parseImport(node){next();if(tokType===_string){node.specifiers=[];node.source=parseExprAtom();node.kind=""}else{node.specifiers=parseImportSpecifiers();if(tokType!==_name||tokVal!=="from")unexpected();next();node.source=tokType===_string?parseExprAtom():unexpected();node.kind=node.specifiers[0]["default"]?"default":"named"}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();if(tokType!==_name||tokVal!=="as")unexpected();next();node.name=parseIdent();checkLVal(node.name,true);nodes.push(finishNode(node,"ImportBatchSpecifier"));return nodes}if(tokType===_name){var node=startNode();node.id=parseIdent();checkLVal(node.id,true);node.name=null;node["default"]=true;nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(true);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent()}else{node.name=null}checkLVal(node.name||node.id,true);node["default"]=false;nodes.push(finishNode(node,"ImportSpecifier"))}return nodes}function parseYield(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){node.delegate=false;node.argument=null}else{node.delegate=eat(_star);node.argument=parseExpression(true)}return finishNode(node,"YieldExpression")}function parseAwait(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){unexpected()}node.delegate=eat(_star);node.argument=parseExpression(true);return finishNode(node,"AwaitExpression")}function parseComprehension(node,isGenerator){node.blocks=[];while(tokType===_for){var block=startNode();next();expect(_parenL);block.left=toAssignable(parseExprAtom());checkLVal(block.left,true);if(tokType!==_name||tokVal!=="of")unexpected();next();block.of=true;block.right=parseExpression();expect(_parenR);node.blocks.push(finishNode(block,"ComprehensionBlock"))}node.filter=eat(_if)?parseParenExpression():null;node.body=parseExpression();expect(isGenerator?_parenR:_bracketR);node.generator=isGenerator;return finishNode(node,"ComprehensionExpression")}function getQualifiedXJSName(object){if(object.type==="XJSIdentifier"){return object.name}if(object.type==="XJSNamespacedName"){return object.namespace.name+":"+object.name.name}if(object.type==="XJSMemberExpression"){return getQualifiedXJSName(object.object)+"."+getQualifiedXJSName(object.property)}}function parseXJSIdentifier(){var node=startNode();if(tokType===_xjsName){node.name=tokVal}else if(tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"XJSIdentifier")}function parseXJSNamespacedName(){var node=startNode();node.namespace=parseXJSIdentifier();expect(_colon);node.name=parseXJSIdentifier();return finishNode(node,"XJSNamespacedName")}function parseXJSMemberExpression(){var start=storeCurrentPos();var node=parseXJSIdentifier();while(eat(_dot)){var newNode=startNodeAt(start);newNode.object=node;newNode.property=parseXJSIdentifier();node=finishNode(newNode,"XJSMemberExpression")}return node}function parseXJSElementName(){switch(nextChar()){case":":return parseXJSNamespacedName();case".":return parseXJSMemberExpression();default:return parseXJSIdentifier()}}function parseXJSAttributeName(){if(nextChar()===":"){return parseXJSNamespacedName()}return parseXJSIdentifier()}function parseXJSAttributeValue(){switch(tokType){case _braceL:var node=parseXJSExpressionContainer();if(node.expression.type==="XJSEmptyExpression"){raise(node.start,"XJS attributes must only be assigned a non-empty "+"expression")}return node;case _lt:return parseXJSElement();case _xjsText:return parseExprAtom();default:raise(tokStart,"XJS value should be either an expression or a quoted XJS text")}}function parseXJSEmptyExpression(){if(tokType!==_braceR){unexpected()}var tmp;tmp=tokStart;tokStart=lastEnd;lastEnd=tmp;tmp=tokStartLoc;tokStartLoc=lastEndLoc;lastEndLoc=tmp;return finishNode(startNode(),"XJSEmptyExpression")}function parseXJSExpressionContainer(){var node=startNode();var origInXJSTag=inXJSTag,origInXJSChild=inXJSChild;inXJSTag=false;inXJSChild=false;inXJSChildExpression=origInXJSChild;next();node.expression=tokType===_braceR?parseXJSEmptyExpression():parseExpression();inXJSTag=origInXJSTag;inXJSChild=origInXJSChild;inXJSChildExpression=false;expect(_braceR);return finishNode(node,"XJSExpressionContainer")}function parseXJSAttribute(){if(tokType===_braceL){var tokStart1=tokStart,tokStartLoc1=tokStartLoc;var origInXJSTag=inXJSTag,origInXJSChildExpression=inXJSChildExpression;inXJSTag=inXJSChildExpression=false;next();if(tokType!==_ellipsis)unexpected();var node=parseMaybeUnary();inXJSChildExpression=origInXJSChildExpression;inXJSTag=origInXJSTag;expect(_braceR);node.type="XJSSpreadAttribute";node.start=tokStart1;node.end=lastEnd;if(options.locations){node.loc.start=tokStartLoc1;node.loc.end=lastEndLoc}if(options.ranges){node.range=[tokStart1,lastEnd]}return node}var node=startNode();node.name=parseXJSAttributeName();if(tokType===_eq){next();node.value=parseXJSAttributeValue()}else{node.value=null}return finishNode(node,"XJSAttribute")}function parseXJSChild(){switch(tokType){case _braceL:return parseXJSExpressionContainer();case _xjsText:return parseExprAtom();default:return parseXJSElement()}}function parseXJSOpeningElement(){var node=startNode(),attributes=node.attributes=[];var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;next();node.name=parseXJSElementName();while(tokType!==_eof&&tokType!==_slash&&tokType!==_gt){attributes.push(parseXJSAttribute())}inXJSTag=false;if(node.selfClosing=!!eat(_slash)){inXJSTag=origInXJSTag;inXJSChild=origInXJSChild}else{inXJSChild=true}expect(_gt);return finishNode(node,"XJSOpeningElement")}function parseXJSClosingElement(){var node=startNode();var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;tokRegexpAllowed=false;expect(_ltSlash);node.name=parseXJSElementName();skipSpace();inXJSChild=origInXJSChild;inXJSTag=origInXJSTag;tokRegexpAllowed=false;if(inXJSChild){tokPos=tokEnd}expect(_gt);return finishNode(node,"XJSClosingElement")}function parseXJSElement(){var node=startNode();var children=[];var origInXJSChild=inXJSChild;var openingElement=parseXJSOpeningElement();var closingElement=null;if(!openingElement.selfClosing){while(tokType!==_eof&&tokType!==_ltSlash){inXJSChild=true;children.push(parseXJSChild())}inXJSChild=origInXJSChild;closingElement=parseXJSClosingElement();if(getQualifiedXJSName(closingElement.name)!==getQualifiedXJSName(openingElement.name)){raise(closingElement.start,"Expected corresponding XJS closing tag for '"+getQualifiedXJSName(openingElement.name)+"'")}}if(!origInXJSChild&&tokType===_lt){raise(tokStart,"Adjacent XJS elements must be wrapped in an enclosing tag")}node.openingElement=openingElement;node.closingElement=closingElement;node.children=children;return finishNode(node,"XJSElement")}})},{}],2:[function(require,module,exports){(function(global){var transform=module.exports=require("./transformation/transform");transform.transform=transform;transform.run=function(code,opts){opts=opts||{};opts.sourceMap="inline";return new Function(transform(code,opts).code)()};transform.load=function(url,callback,opts,hold){opts=opts||{};opts.filename=opts.filename||url;var xhr=global.ActiveXObject?new global.ActiveXObject("Microsoft.XMLHTTP"):new global.XMLHttpRequest;xhr.open("GET",url,true);if("overrideMimeType"in xhr)xhr.overrideMimeType("text/plain");xhr.onreadystatechange=function(){if(xhr.readyState!==4)return;var status=xhr.status;if(status===0||status===200){var param=[xhr.responseText,opts];if(!hold)transform.run.apply(transform,param);if(callback)callback(param)}else{throw new Error("Could not load "+url)}};xhr.send(null)};var runScripts=function(){var scripts=[];var types=["text/ecmascript-6","text/6to5"];var index=0;var exec=function(){var param=scripts[index];if(param instanceof Array){transform.run.apply(transform,param);index++;exec()}};var run=function(script,i){var opts={};if(script.src){transform.load(script.src,function(param){scripts[i]=param;exec()},opts,true)}else{opts.filename="embedded";scripts[i]=[script.innerHTML,opts]}};var _scripts=global.document.getElementsByTagName("script");for(var i in _scripts){var _script=_scripts[i];if(types.indexOf(_script.type)>=0)scripts.push(_script)}for(i in scripts){run(scripts[i],i)}exec()};if(global.addEventListener){global.addEventListener("DOMContentLoaded",runScripts,false)}else if(global.attachEvent){global.attachEvent("onload",runScripts)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transformation/transform":29}],3:[function(require,module,exports){module.exports=File; var SHEBANG_REGEX=/^\#\!.*/;var transform=require("./transformation/transform");var generate=require("./generation/generator");var Scope=require("./traverse/scope");var util=require("./util");var t=require("./types");var _=require("lodash");function File(opts){this.opts=File.normaliseOptions(opts);this.uids={};this.ast={}}File.declarations=["extends","class-props","apply-constructor","tagged-template-literal","interop-require","to-array","arguments-to-array","object-spread"];File.normaliseOptions=function(opts){opts=_.cloneDeep(opts||{});_.defaults(opts,{experimental:false,whitespace:true,blacklist:[],whitelist:[],sourceMap:false,comments:true,filename:"unknown",modules:"common",runtime:false,code:true});opts.filename=opts.filename.replace(/\\/g,"/");opts.blacklist=util.arrayify(opts.blacklist);opts.whitelist=util.arrayify(opts.whitelist);_.defaults(opts,{moduleRoot:opts.sourceRoot});_.defaults(opts,{sourceRoot:opts.moduleRoot});_.defaults(opts,{filenameRelative:opts.filename});_.defaults(opts,{sourceFileName:opts.filenameRelative,sourceMapName:opts.filenameRelative});if(opts.runtime===true){opts.runtime="to5Runtime"}transform._ensureTransformerNames("blacklist",opts.blacklist);transform._ensureTransformerNames("whitelist",opts.whitelist);return opts};File.prototype.toArray=function(node){if(t.isArrayExpression(node)){return node}var templateName="to-array";if(t.isIdentifier(node)&&node.name==="arguments"){templateName="arguments-to-array"}return t.callExpression(this.addDeclaration(templateName),[node])};File.prototype.getModuleFormatter=function(type){var ModuleFormatter=_.isFunction(type)?type:transform.moduleFormatters[type];if(!ModuleFormatter){var loc=util.resolve(type);if(loc)ModuleFormatter=require(loc)}if(!ModuleFormatter){throw new ReferenceError("unknown module formatter type "+type)}return new ModuleFormatter(this)};File.prototype.parseShebang=function(code){var shebangMatch=code.match(SHEBANG_REGEX);if(shebangMatch){this.shebang=shebangMatch[0];code=code.replace(SHEBANG_REGEX,"")}return code};File.prototype.addDeclaration=function(name){if(!_.contains(File.declarations,name)){throw new ReferenceError("unknown declaration "+name)}var program=this.ast.program;var declar=program._declarations&&program._declarations[name];if(declar)return declar.id;var ref;var runtimeNamespace=this.opts.runtime;if(runtimeNamespace){name=t.identifier(t.toIdentifier(name));return t.memberExpression(t.identifier(runtimeNamespace),name)}else{ref=util.template(name)}var uid=this.generateUidIdentifier(name);this.scope.push(name,uid,ref);return uid};File.prototype.errorWithNode=function(node,msg,Error){Error=Error||SyntaxError;var loc=node.loc.start;var err=new Error("Line "+loc.line+": "+msg);err.loc=loc;return err};File.prototype.parse=function(code){code=(code||"")+"";var self=this;this.code=code;code=this.parseShebang(code);return util.parse(this.opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){this.ast=ast;this.scope=new Scope(ast.program);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);var self=this;_.each(transform.transformers,function(transformer){transformer.transform(self)})};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;if(!opts.code){return{code:"",map:null,ast:ast}}var result=generate(ast,opts,this.code);if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}result.ast=result;return result};File.prototype.generateUid=function(name,scope){name=t.toIdentifier(name);scope=scope||this.scope;var uid;do{uid=this._generateUid(name)}while(scope.has(uid));return uid};File.prototype.generateUidIdentifier=function(name,scope){return t.identifier(this.generateUid(name,scope))};File.prototype._generateUid=function(name){var uids=this.uids;var i=uids[name]||1;var id=name;if(i>1)id+=i;uids[name]=i+1;return"_"+id}},{"./generation/generator":5,"./transformation/transform":29,"./traverse/scope":69,"./types":72,"./util":74,lodash:105}],4:[function(require,module,exports){module.exports=Buffer;var util=require("../util");var _=require("lodash");function Buffer(position,format){this.position=position;this._indent=format.indent.base;this.format=format;this.buf=""}Buffer.prototype.get=function(){return util.trimRight(this.buf)};Buffer.prototype.getIndent=function(){if(this.format.compact){return""}else{return util.repeat(this._indent,this.format.indent.style)}};Buffer.prototype.indentSize=function(){return this.getIndent().length};Buffer.prototype.indent=function(){this._indent++};Buffer.prototype.dedent=function(){this._indent--};Buffer.prototype.semicolon=function(){if(this.format.semicolons)this.push(";")};Buffer.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};Buffer.prototype.rightBrace=function(){this.newline(true);this.push("}")};Buffer.prototype.keyword=function(name){this.push(name);this.push(" ")};Buffer.prototype.space=function(){if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};Buffer.prototype.removeLast=function(cha){if(!this.isLast(cha))return;this.buf=this.buf.slice(0,-1);this.position.unshift(cha)};Buffer.prototype.newline=function(i,removeLast){if(!this.buf)return;if(this.format.compact)return;if(this.endsWith("{\n"))return;if(_.isBoolean(i)){removeLast=i;i=null}if(_.isNumber(i)){if(this.endsWith(util.repeat(i,"\n")))return;var self=this;_.times(i,function(){self.newline(null,removeLast)});return}if(removeLast&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this.buf=this.buf.replace(/\n +$/,"\n");this._push("\n")};Buffer.prototype.push=function(str,noIndent){if(this._indent&&!noIndent&&str!=="\n"){var indent=this.getIndent();str=str.replace(/\n/g,"\n"+indent);if(this.isLast("\n"))str=indent+str}this._push(str)};Buffer.prototype._push=function(str){this.position.push(str);this.buf+=str};Buffer.prototype.endsWith=function(str){return this.buf.slice(-str.length)===str};Buffer.prototype.isLast=function(cha,trimRight){var buf=this.buf;if(trimRight)buf=util.trimRight(buf);var chars=[].concat(cha);return _.contains(chars,_.last(buf))}},{"../util":74,lodash:105}],5:[function(require,module,exports){module.exports=function(ast,opts,code){var gen=new CodeGenerator(ast,opts,code);return gen.generate()};module.exports.CodeGenerator=CodeGenerator;var Whitespace=require("./whitespace");var SourceMap=require("./source-map");var Position=require("./position");var Buffer=require("./buffer");var util=require("../util");var n=require("./node");var t=require("../types");var _=require("lodash");function CodeGenerator(ast,opts,code){opts=opts||{};this.comments=ast.comments||[];this.tokens=ast.tokens||[];this.format=CodeGenerator.normaliseOptions(opts);this.ast=ast;this.whitespace=new Whitespace(this.tokens,this.comments);this.position=new Position;this.map=new SourceMap(this.position,opts,code);this.buffer=new Buffer(this.position,this.format)}_.each(Buffer.prototype,function(fn,key){CodeGenerator.prototype[key]=function(){return fn.apply(this.buffer,arguments)}});CodeGenerator.normaliseOptions=function(opts){return _.merge({parentheses:true,semicolons:true,comments:opts.comments==null||opts.comments,compact:false,indent:{adjustMultilineComment:true,style:" ",base:0}},opts.format||{})};CodeGenerator.generators={templateLiterals:require("./generators/template-literals"),comprehensions:require("./generators/comprehensions"),expressions:require("./generators/expressions"),statements:require("./generators/statements"),classes:require("./generators/classes"),methods:require("./generators/methods"),modules:require("./generators/modules"),types:require("./generators/types"),base:require("./generators/base"),jsx:require("./generators/jsx")};_.each(CodeGenerator.generators,function(generator){_.extend(CodeGenerator.prototype,generator)});CodeGenerator.prototype.generate=function(){var ast=this.ast;this.print(ast);return{map:this.map.get(),code:this.buffer.get()}};CodeGenerator.prototype.buildPrint=function(parent){var self=this;var print=function(node,opts){return self.print(node,parent,opts)};print.sequence=function(nodes,opts){opts=opts||{};opts.statement=true;return self.printJoin(print,nodes,opts)};print.join=function(nodes,opts){return self.printJoin(print,nodes,opts)};print.block=function(node){return self.printBlock(print,node)};print.indentOnComments=function(node){return self.printAndIndentOnComments(print,node)};return print};CodeGenerator.prototype.print=function(node,parent,opts){if(!node)return"";var self=this;opts=opts||{};var newline=function(leading){if(!opts.statement&&!n.isUserWhitespacable(node,parent)){return}var lines=0;if(node.start!=null){if(leading){lines=self.whitespace.getNewlinesBefore(node)}else{lines=self.whitespace.getNewlinesAfter(node)}}else{if(!leading)lines++;var needs=n.needsWhitespaceAfter;if(leading)needs=n.needsWhitespaceBefore;lines+=needs(node,parent)}self.newline(lines)};if(this[node.type]){this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node,"start");var needsParens=parent!==node._parent&&n.needsParens(node,parent);if(needsParens)this.push("(");this[node.type](node,this.buildPrint(node),parent);if(needsParens)this.push(")");this.map.mark(node,"end");if(opts.after)opts.after();newline(false);this.printTrailingComments(node,parent)}else{throw new ReferenceError("unknown node "+node.type+" "+JSON.stringify(node))}};CodeGenerator.prototype.printJoin=function(print,nodes,opts){if(!nodes||!nodes.length)return;opts=opts||{};var self=this;var len=nodes.length;if(opts.indent)self.indent();_.each(nodes,function(node,i){print(node,{statement:opts.statement,after:function(){if(opts.iterator){opts.iterator(node,i)}if(opts.separator&&i<len-1){self.push(opts.separator)}}})});if(opts.indent)self.dedent()};CodeGenerator.prototype.printAndIndentOnComments=function(print,node){var indent=!!node.leadingComments;if(indent)this.indent();print(node);if(indent)this.dedent()};CodeGenerator.prototype.printBlock=function(print,node){if(t.isEmptyStatement(node)){this.semicolon()}else{this.push(" ");print(node)}};CodeGenerator.prototype.generateComment=function(comment){var val=comment.value;if(comment.type==="Line"){val="//"+val}else{val="/*"+val+"*/"}return val};CodeGenerator.prototype.printTrailingComments=function(node,parent){this._printComments(this.getComments("trailingComments",node,parent))};CodeGenerator.prototype.printLeadingComments=function(node,parent){this._printComments(this.getComments("leadingComments",node,parent))};CodeGenerator.prototype.getComments=function(key,node,parent){if(t.isExpressionStatement(parent)){return[]}var comments=[];var nodes=[node];var self=this;if(t.isExpressionStatement(node)){nodes.push(node.argument)}_.each(nodes,function(node){comments=comments.concat(self._getComments(key,node))});return comments};CodeGenerator.prototype._getComments=function(key,node){return node&&node[key]||[]};CodeGenerator.prototype._printComments=function(comments){if(this.format.compact)return;if(!this.format.comments)return;if(!comments||!comments.length)return;var self=this;_.each(comments,function(comment){self.newline(self.whitespace.getNewlinesBefore(comment));var column=self.position.column;var val=self.generateComment(comment);if(column&&!self.isLast(["\n"," ","[","{"])){self._push(" ");column++}if(comment.type==="Block"&&self.format.indent.adjustMultilineComment){var offset=comment.loc.start.column;if(offset){var newlineRegex=new RegExp("\\n\\s{1,"+offset+"}","g");val=val.replace(newlineRegex,"\n")}var indent=Math.max(self.indentSize(),column);val=val.replace(/\n/g,"\n"+util.repeat(indent))}if(column===0){val=self.getIndent()+val}self._push(val);self.newline(self.whitespace.getNewlinesAfter(comment))})}},{"../types":72,"../util":74,"./buffer":4,"./generators/base":6,"./generators/classes":7,"./generators/comprehensions":8,"./generators/expressions":9,"./generators/jsx":10,"./generators/methods":11,"./generators/modules":12,"./generators/statements":13,"./generators/template-literals":14,"./generators/types":15,"./node":16,"./position":19,"./source-map":20,"./whitespace":21,lodash:105}],6:[function(require,module,exports){exports.File=function(node,print){print(node.program)};exports.Program=function(node,print){print.sequence(node.body)};exports.BlockStatement=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();print.sequence(node.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],7:[function(require,module,exports){exports.ClassExpression=exports.ClassDeclaration=function(node,print){this.push("class");if(node.id){this.space();print(node.id)}if(node.superClass){this.push(" extends ");print(node.superClass)}this.space();print(node.body)};exports.ClassBody=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();print.sequence(node.body);this.dedent();this.rightBrace()}};exports.MethodDefinition=function(node,print){if(node.static){this.push("static ")}this._method(node,print)}},{}],8:[function(require,module,exports){exports.ComprehensionBlock=function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" of ");print(node.right);this.push(")")};exports.ComprehensionExpression=function(node,print){this.push(node.generator?"(":"[");print.join(node.blocks,{separator:" "});this.space();if(node.filter){this.keyword("if");this.push("(");print(node.filter);this.push(")");this.space()}print(node.body);this.push(node.generator?")":"]")}},{}],9:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.UnaryExpression=function(node,print){var hasSpace=/[a-z]$/.test(node.operator);var arg=node.argument;if(t.isUpdateExpression(arg)||t.isUnaryExpression(arg)){hasSpace=true}if(t.isUnaryExpression(arg)&&arg.operator==="!"){hasSpace=false}this.push(node.operator);if(hasSpace)this.space();print(node.argument)};exports.ParenthesizedExpression=function(node,print){this.push("(");print(node.expression);this.push(")")};exports.UpdateExpression=function(node,print){if(node.prefix){this.push(node.operator);print(node.argument)}else{print(node.argument);this.push(node.operator)}};exports.ConditionalExpression=function(node,print){print(node.test);this.push(" ? ");print(node.consequent);this.push(" : ");print(node.alternate)};exports.NewExpression=function(node,print){this.push("new ");print(node.callee);if(node.arguments.length||this.format.parentheses){this.push("(");print.join(node.arguments,{separator:", "});this.push(")")}};exports.SequenceExpression=function(node,print){print.join(node.expressions,{separator:", "})};exports.ThisExpression=function(){this.push("this")};exports.CallExpression=function(node,print){print(node.callee);this.push("(");print.join(node.arguments,{separator:", "});this.push(")")};var buildYieldAwait=function(keyword){return function(node,print){this.push(keyword);if(node.delegate)this.push("*");if(node.argument){this.space();print(node.argument)}}};exports.YieldExpression=buildYieldAwait("yield");exports.AwaitExpression=buildYieldAwait("await");exports.EmptyStatement=function(){this.semicolon()};exports.ExpressionStatement=function(node,print){print(node.expression);this.semicolon()};exports.BinaryExpression=exports.LogicalExpression=exports.AssignmentExpression=function(node,print){print(node.left);this.push(" "+node.operator+" ");print(node.right)};exports.MemberExpression=function(node,print){print(node.object);if(node.computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(node.object)&&util.isInteger(node.object.value)){this.push(".")}this.push(".");print(node.property)}}},{"../../types":72,"../../util":74}],10:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.XJSAttribute=function(node,print){print(node.name);if(node.value){this.push("=");print(node.value)}};exports.XJSIdentifier=function(node){this.push(node.name)};exports.XJSNamespacedName=function(node,print){print(node.namespace);this.push(":");print(node.name)};exports.XJSMemberExpression=function(node,print){print(node.object);this.push(".");print(node.property)};exports.XJSSpreadAttribute=function(node,print){this.push("{...");print(node.argument);this.push("}")};exports.XJSExpressionContainer=function(node,print){this.push("{");print(node.expression);this.push("}")};exports.XJSElement=function(node,print){var self=this;var open=node.openingElement;print(open);if(open.selfClosing)return;this.indent();_.each(node.children,function(child){if(t.isLiteral(child)){self.push(child.value)}else{print(child)}});this.dedent();print(node.closingElement)};exports.XJSOpeningElement=function(node,print){this.push("<");print(node.name);if(node.attributes.length>0){this.space();print.join(node.attributes,{separator:" "})}this.push(node.selfClosing?" />":">")};exports.XJSClosingElement=function(node,print){this.push("</");print(node.name);this.push(">")};exports.XJSEmptyExpression=function(){}},{"../../types":72,lodash:105}],11:[function(require,module,exports){var t=require("../../types");exports._params=function(node,print){var self=this;this.push("(");print.join(node.params,{separator:", ",iterator:function(param,i){var def=node.defaults&&node.defaults[i];if(def){self.push(" = ");print(def)}}});if(node.rest){if(node.params.length){this.push(", ")}this.push("...");print(node.rest)}this.push(")")};exports._method=function(node,print){var value=node.value;var kind=node.kind;var key=node.key;if(!kind||kind==="init"){if(value.generator){this.push("*")}}else{this.push(kind+" ")}if(value.async)this.push("async ");if(node.computed){this.push("[");print(key);this.push("]")}else{print(key)}this._params(value,print);this.space();print(value.body)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,print){if(node.async)this.push("async ");this.push("function");if(node.generator)this.push("*");this.space();if(node.id)print(node.id);this._params(node,print);this.space();print(node.body)};exports.ArrowFunctionExpression=function(node,print){if(node.async)this.push("async ");if(node.params.length===1&&!node.defaults.length&&!node.rest&&t.isIdentifier(node.params[0])){print(node.params[0])}else{this._params(node,print)}this.push(" => ");print(node.body)}},{"../../types":72}],12:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ImportSpecifier=exports.ExportSpecifier=function(node,print){print(node.id);if(node.name){this.push(" as ");print(node.name)}};exports.ExportBatchSpecifier=function(){this.push("*")};exports.ExportDeclaration=function(node,print){this.push("export ");var specifiers=node.specifiers;if(node.default){this.push("default ")}if(node.declaration){print(node.declaration);if(t.isStatement(node.declaration))return}else{if(specifiers.length===1&&t.isExportBatchSpecifier(specifiers[0])){print(specifiers[0])}else{this.push("{");if(specifiers.length){this.space();print.join(specifiers,{separator:", "});this.space()}this.push("}")}if(node.source){this.push(" from ");print(node.source)}}this.ensureSemicolon()};exports.ImportDeclaration=function(node,print){var self=this;this.push("import ");var specfiers=node.specifiers;if(specfiers&&specfiers.length){var foundImportSpecifier=false;_.each(node.specifiers,function(spec,i){if(+i>0){self.push(", ")}if(!spec.default&&spec.type!=="ImportBatchSpecifier"&&!foundImportSpecifier){foundImportSpecifier=true;self.push("{ ")}print(spec)});if(foundImportSpecifier){this.push(" }")}this.push(" from ")}print(node.source);this.semicolon()};exports.ImportBatchSpecifier=function(node,print){this.push("* as ");print(node.name)}},{"../../types":72,lodash:105}],13:[function(require,module,exports){var t=require("../../types");exports.WithStatement=function(node,print){this.keyword("with");this.push("(");print(node.object);this.push(")");print.block(node.body)};exports.IfStatement=function(node,print){this.keyword("if");this.push("(");print(node.test);this.push(") ");print.indentOnComments(node.consequent);if(node.alternate){if(this.isLast("}"))this.space();this.keyword("else");print.indentOnComments(node.alternate)}};exports.ForStatement=function(node,print){this.keyword("for");this.push("(");print(node.init);this.push(";");if(node.test){this.space();print(node.test)}this.push(";");if(node.update){this.space();print(node.update)}this.push(")");print.block(node.body)};exports.WhileStatement=function(node,print){this.keyword("while");this.push("(");print(node.test);this.push(")");print.block(node.body)};var buildForXStatement=function(op){return function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" "+op+" ");print(node.right);this.push(")");print.block(node.body)}};exports.ForInStatement=buildForXStatement("in");exports.ForOfStatement=buildForXStatement("of");exports.DoWhileStatement=function(node,print){this.keyword("do");print(node.body);this.space();this.keyword("while");this.push("(");print(node.test);this.push(");")};var buildLabelStatement=function(prefix,key){return function(node,print){this.push(prefix);var label=node[key||"label"];if(label){this.space();print(label)}this.semicolon()}};exports.ContinueStatement=buildLabelStatement("continue");exports.ReturnStatement=buildLabelStatement("return","argument");exports.BreakStatement=buildLabelStatement("break");exports.LabeledStatement=function(node,print){print(node.label);this.push(": ");print(node.body)};exports.TryStatement=function(node,print){this.keyword("try");print(node.block);this.space();print(node.handler);if(node.finalizer){this.space();this.push("finally ");print(node.finalizer)}};exports.CatchClause=function(node,print){this.keyword("catch");this.push("(");print(node.param);this.push(") ");print(node.body)};exports.ThrowStatement=function(node,print){this.push("throw ");print(node.argument);this.semicolon()};exports.SwitchStatement=function(node,print){this.keyword("switch");this.push("(");print(node.discriminant);this.push(") {");print.sequence(node.cases,{indent:true});this.push("}")};exports.SwitchCase=function(node,print){if(node.test){this.push("case ");print(node.test);this.push(":")}else{this.push("default:")}this.space();print.sequence(node.consequent,{indent:true})};exports.DebuggerStatement=function(){this.push("debugger;")};exports.VariableDeclaration=function(node,print,parent){this.push(node.kind+" ");print.join(node.declarations,{separator:", "});if(!t.isFor(parent)){this.semicolon()}};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.push(" = ");print(node.init)}else{print(node.id)}}},{"../../types":72}],14:[function(require,module,exports){var _=require("lodash");exports.TaggedTemplateExpression=function(node,print){print(node.tag);print(node.quasi)};exports.TemplateElement=function(node){this._push(node.value.raw)};exports.TemplateLiteral=function(node,print){this.push("`");var quasis=node.quasis;var self=this;var len=quasis.length;_.each(quasis,function(quasi,i){print(quasi);if(i+1<len){self.push("${ ");print(node.expressions[i]);self.push(" }")}});this._push("`")}},{lodash:105}],15:[function(require,module,exports){var _=require("lodash");exports.Identifier=function(node){this.push(node.name)};exports.SpreadElement=exports.SpreadProperty=function(node,print){this.push("...");print(node.argument)};exports.VirtualPropertyExpression=function(node,print){print(node.object);this.push("::");print(node.property)};exports.ObjectExpression=exports.ObjectPattern=function(node,print){var props=node.properties;if(props.length){this.push("{");this.space();print.join(props,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};exports.Property=function(node,print){if(node.method||node.kind==="get"||node.kind==="set"){this._method(node,print)}else{if(node.computed){this.push("[");print(node.key);this.push("]")}else{print(node.key);if(node.shorthand)return}this.push(": ");print(node.value)}};exports.ArrayExpression=exports.ArrayPattern=function(node,print){var elems=node.elements;var self=this;var len=elems.length;this.push("[");_.each(elems,function(elem,i){if(!elem){self.push(",")}else{if(i>0)self.push(" ");print(elem);if(i<len-1)self.push(",")}});this.push("]")};exports.Literal=function(node){var val=node.value;var type=typeof val;if(type==="string"){val=JSON.stringify(val);val=val.replace(/[\u007f-\uffff]/g,function(c){return"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)});this.push(val)}else if(type==="boolean"||type==="number"){this.push(JSON.stringify(val))}else if(node.regex){this.push("/"+node.regex.pattern+"/"+node.regex.flags)}else if(val===null){this.push("null")}}},{lodash:105}],16:[function(require,module,exports){module.exports=Node;var whitespace=require("./whitespace");var parens=require("./parentheses");var t=require("../../types");var _=require("lodash");var find=function(obj,node,parent){var result;_.each(obj,function(fn,type){if(t["is"+type](node)){result=fn(node,parent);if(result!=null)return false}});return result};function Node(node,parent){this.parent=parent;this.node=node}Node.prototype.isUserWhitespacable=function(){return t.isUserWhitespacable(this.node)};Node.prototype.needsWhitespace=function(type){var parent=this.parent;var node=this.node;if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var lines=find(whitespace[type].nodes,node,parent);if(lines)return lines;_.each(find(whitespace[type].list,node,parent),function(expr){lines=Node.needsWhitespace(expr,node,type);if(lines)return false});return lines||0};Node.prototype.needsWhitespaceBefore=function(){return this.needsWhitespace("before")};Node.prototype.needsWhitespaceAfter=function(){return this.needsWhitespace("after")};Node.prototype.needsParens=function(){var parent=this.parent;var node=this.node;if(!parent)return false;if(t.isNewExpression(parent)&&parent.callee===node){return t.isCallExpression(node)||_.some(node,function(val){return t.isCallExpression(val)})}return find(parens,node,parent)};_.each(Node.prototype,function(fn,key){Node[key]=function(node,parent){var n=new Node(node,parent);var args=_.toArray(arguments).slice(2);return n[key].apply(n,args)}})},{"../../types":72,"./parentheses":17,"./whitespace":18,lodash:105}],17:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var PRECEDENCE={};_.each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]],function(tier,i){_.each(tier,function(op){PRECEDENCE[op]=i})});exports.Binary=function(node,parent){if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isUnaryLike(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isBinary(parent)){var parentOp=parent.operator;var parentPos=PRECEDENCE[parentOp];var nodeOp=node.operator;var nodePos=PRECEDENCE[nodeOp];if(parentPos>nodePos){return true}if(parentPos===nodePos&&parent.right===node){return true}}};exports.BinaryExpression=function(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}};exports.SequenceExpression=function(node,parent){if(t.isForStatement(parent)){return false}if(t.isExpressionStatement(parent)&&parent.expression===node){return false}return true};exports.YieldExpression=function(node,parent){return t.isBinary(parent)||t.isUnaryLike(parent)||t.isCallExpression(parent)||t.isMemberExpression(parent)||t.isNewExpression(parent)||t.isConditionalExpression(parent)||t.isYieldExpression(parent)};exports.Literal=function(node,parent){if(_.isNumber(node.value)&&t.isMemberExpression(parent)&&parent.object===node){return true}};exports.ClassExpression=function(node,parent){return t.isExpressionStatement(parent)};exports.UnaryLike=function(node,parent){return t.isMemberExpression(parent)&&parent.object===node};exports.FunctionExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}};exports.AssignmentExpression=exports.ConditionalExpression=function(node,parent){if(t.isUnaryLike(parent)){return true}if(t.isBinary(parent)){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isConditionalExpression(parent)&&parent.test===node){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false}},{"../../types":72,lodash:105}],18:[function(require,module,exports){var _=require("lodash");var t=require("../../types");exports.before={nodes:{Property:function(node,parent){if(parent.properties[0]===node){return 1}},SpreadProperty:function(node,parent){return exports.before.nodes.Property(node,parent)},SwitchCase:function(node,parent){if(parent.cases[0]===node){return 1}},CallExpression:function(node){if(t.isFunction(node.callee)){return 1}}}};exports.after={nodes:{},list:{VariableDeclaration:function(node){return _.map(node.declarations,"init")},ArrayExpression:function(node){return node.elements},ObjectExpression:function(node){return node.properties}}};_.each({Function:1,Class:1,For:1,SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(amounts,type){if(_.isNumber(amounts))amounts={after:amounts,before:amounts};_.each(amounts,function(amount,key){exports[key].nodes[type]=function(){return amount}})})},{"../../types":72,lodash:105}],19:[function(require,module,exports){module.exports=Position;var _=require("lodash");function Position(){this.line=1;this.column=0}Position.prototype.push=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line++;self.column=0}else{self.column++}})};Position.prototype.unshift=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line--}else{self.column--}})}},{lodash:105}],20:[function(require,module,exports){module.exports=SourceMap;var sourceMap=require("source-map");var t=require("../types");function SourceMap(position,opts,code){this.position=position;this.opts=opts;if(opts.sourceMap){this.map=new sourceMap.SourceMapGenerator({file:opts.sourceMapName,sourceRoot:opts.sourceRoot});this.map.setSourceContent(opts.sourceFileName,code)}else{this.map=null}}SourceMap.prototype.get=function(){var map=this.map;if(map){return map.toJSON()}else{return map}};SourceMap.prototype.mark=function(node,type){var loc=node.loc;if(!loc)return;var map=this.map;if(!map)return;if(t.isProgram(node)||t.isFile(node))return;var position=this.position;var generated={line:position.line,column:position.column};var original=loc[type];if(generated.line===original.line&&generated.column===original.column)return;map.addMapping({source:this.opts.sourceFileName,generated:generated,original:original})}},{"../types":72,"source-map":113}],21:[function(require,module,exports){module.exports=Whitespace;var _=require("lodash");function Whitespace(tokens,comments){this.tokens=_.sortBy(tokens.concat(comments),"start");this.used=[]}Whitespace.prototype.getNewlinesBefore=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.start===token.start){startToken=tokens[i-1];endToken=token;return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesAfter=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.end===token.end){startToken=token;endToken=tokens[i+1];return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesBetween=function(startToken,endToken){var start=startToken?startToken.loc.end.line:1;var end=endToken.loc.start.line;var lines=0;for(var line=start;line<end;line++){if(!_.contains(this.used,line)){this.used.push(line);lines++}}return lines}},{lodash:105}],22:[function(require,module,exports){var t=require("./types"); var _=require("lodash");var types=require("ast-types");var def=types.Type.def;var or=types.Type.or;def("File").bases("Node").build("program").field("program",def("Program"));def("ParenthesizedExpression").bases("Expression").build("expression").field("expression",def("Expression"));def("ImportBatchSpecifier").bases("Specifier").build("name").field("name",def("Identifier"));def("VirtualPropertyExpression").bases("Expression").build("object","property").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression")));types.finalize();var estraverse=require("estraverse");_.extend(estraverse.VisitorKeys,t.VISITOR_KEYS)},{"./types":72,"ast-types":88,estraverse:100,lodash:105}],23:[function(require,module,exports){module.exports=AMDFormatter;var CommonJSFormatter=require("./common");var util=require("../../util");var t=require("../../types");var _=require("lodash");function AMDFormatter(file){this.file=file;this.ids={}}util.inherits(AMDFormatter,CommonJSFormatter);AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")];_.each(this.ids,function(id,name){names.push(t.literal(name))});names=t.arrayExpression(names);var params=_.values(this.ids);params.unshift(t.identifier("exports"));var container=t.functionExpression(null,params,t.blockStatement(body));var defineArgs=[names,container];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var call=t.callExpression(t.identifier("define"),defineArgs);program.body=[t.expressionStatement(call)]};AMDFormatter.prototype.getModuleName=function(){if(this.file.opts.amdModuleIds){return CommonJSFormatter.prototype.getModuleName.apply(this,arguments)}else{return null}};AMDFormatter.prototype._push=function(node){var id=node.source.value;var ids=this.ids;if(ids[id]){return ids[id]}else{return this.ids[id]=this.file.generateUidIdentifier(id)}};AMDFormatter.prototype.import=function(node){this._push(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var id=specifier.id;if(specifier.default){id=t.identifier("default")}var ref;if(t.isImportBatchSpecifier(specifier)){ref=this._push(node)}else{ref=t.memberExpression(this._push(node),id,false)}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,ref)]))};AMDFormatter.prototype.exportSpecifier=function(specifier,node,nodes){var self=this;return this._exportSpecifier(function(){return self._push(node)},specifier,node,nodes)}},{"../../types":72,"../../util":74,"./common":25,lodash:105}],24:[function(require,module,exports){module.exports=CommonJSInteropFormatter;var CommonJSFormatter=require("./common");var util=require("../../util");var t=require("../../types");function CommonJSInteropFormatter(){this.has=false;CommonJSFormatter.apply(this,arguments)}util.inherits(CommonJSInteropFormatter,CommonJSFormatter);CommonJSInteropFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(specifier.default){nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.callExpression(this.file.addDeclaration("interop-require"),[util.template("require",{MODULE_NAME:node.source.raw})]))]))}else{CommonJSFormatter.prototype.importSpecifier.apply(this,arguments)}};CommonJSInteropFormatter.prototype.export=function(node,nodes){if(node.default&&!this.has){var declar=node.declaration;var assign=util.template("exports-default-module",{VALUE:this._pushStatement(declar,nodes)},true);nodes.push(this._hoistExport(declar,assign));return}else{this.has=true}CommonJSFormatter.prototype.export.apply(this,arguments)};CommonJSInteropFormatter.prototype.exportSpecifier=function(){this.has=true;CommonJSFormatter.prototype.exportSpecifier.apply(this,arguments)}},{"../../types":72,"../../util":74,"./common":25}],25:[function(require,module,exports){module.exports=CommonJSFormatter;var util=require("../../util");var t=require("../../types");function CommonJSFormatter(file){this.file=file}CommonJSFormatter.prototype.getModuleName=function(){var opts=this.file.opts;var filenameRelative=opts.filenameRelative;var moduleName="";if(opts.moduleRoot){moduleName=opts.moduleRoot+"/"}if(!opts.filenameRelative){return moduleName+opts.filename.replace(/^\//,"")}if(opts.sourceRoot){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}filenameRelative=filenameRelative.replace(/\.(.*?)$/,"");moduleName+=filenameRelative;return moduleName};CommonJSFormatter.prototype.import=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source.raw},true))};CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(specifier.default){specifier.id=t.identifier("default")}var templateName="require-assign";if(specifier.type!=="ImportBatchSpecifier")templateName+="-key";nodes.push(util.template(templateName,{VARIABLE_NAME:variableName,MODULE_NAME:node.source.raw,KEY:specifier.id}))};CommonJSFormatter.prototype._hoistExport=function(declar,assign){if(t.isFunctionDeclaration(declar)){assign._blockHoist=true}return assign};CommonJSFormatter.prototype._pushStatement=function(ref,nodes){if(t.isClass(ref)||t.isFunction(ref)){if(ref.id){nodes.push(t.toStatement(ref));ref=ref.id}}return ref};CommonJSFormatter.prototype.export=function(node,nodes){var declar=node.declaration;if(node.default){nodes.push(util.template("exports-default",{VALUE:this._pushStatement(declar,nodes)},true))}else{var assign;if(t.isVariableDeclaration(declar)){var decl=declar.declarations[0];if(decl.init){decl.init=util.template("exports-assign",{VALUE:decl.init,KEY:decl.id})}nodes.push(declar)}else{assign=util.template("exports-assign",{VALUE:declar.id,KEY:declar.id},true);nodes.push(t.toStatement(declar));nodes.push(assign);this._hoistExport(declar,assign)}}};CommonJSFormatter.prototype._exportSpecifier=function(getRef,specifier,node,nodes){var variableName=t.getSpecifierName(specifier);var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){if(t.isExportBatchSpecifier(specifier)){nodes.push(util.template("exports-wildcard",{OBJECT:getRef()},true))}else{nodes.push(util.template("exports-assign-key",{VARIABLE_NAME:variableName.name,OBJECT:getRef(),KEY:specifier.id},true))}}else{nodes.push(util.template("exports-assign",{VALUE:specifier.id,KEY:variableName},true))}};CommonJSFormatter.prototype.exportSpecifier=function(specifier,node,nodes){this._exportSpecifier(function(){return t.callExpression(t.identifier("require"),[node.source])},specifier,node,nodes)}},{"../../types":72,"../../util":74}],26:[function(require,module,exports){module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.import=function(){};IgnoreFormatter.prototype.importSpecifier=function(){};IgnoreFormatter.prototype.export=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":72}],27:[function(require,module,exports){module.exports=SystemFormatter;var util=require("../../util");var t=require("../../types");var _=require("lodash");var SETTER_MODULE_NAMESPACE=t.identifier("m");var DEFAULT_IDENTIFIER=t.identifier("default");var NULL_SETTER=t.literal(null);function SystemFormatter(file){this.exportedStatements=[];this.importedModule={};this.exportIdentifier=file.generateUidIdentifier("export");this.file=file}SystemFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var moduleName=this.file.opts.filename.replace(/^.*\//,"").replace(/\..*$/,"");var dependencies=Object.keys(this.importedModule).map(t.literal);var moduleNameVariableNode=t.variableDeclaration("var",[t.variableDeclarator(t.identifier("__moduleName"),t.literal(moduleName))]);body.splice(1,0,moduleNameVariableNode);var declaredSetters=_(this.importedModule).map().flatten().pluck("variableName").pluck("name").uniq().map(t.identifier).map(function(name){return t.variableDeclarator(name)}).value();if(declaredSetters.length){body.splice(2,0,t.variableDeclaration("var",declaredSetters))}var executeFunctionExpression=t.functionExpression(null,[],t.blockStatement(this.exportedStatements));var settersArrayExpression=t.arrayExpression(this._buildSetters());var moduleReturnStatement=t.returnStatement(t.objectExpression([t.property("init",t.identifier("setters"),settersArrayExpression),t.property("init",t.identifier("execute"),executeFunctionExpression)]));body.push(moduleReturnStatement);var runner=util.template("register",{MODULE_NAME:t.literal(moduleName),MODULE_DEPENDENCIES:t.arrayExpression(dependencies),MODULE_BODY:t.functionExpression(null,[this.exportIdentifier],t.blockStatement(body))});program.body=[t.expressionStatement(runner)]};SystemFormatter.prototype._buildSetters=function(){return _.map(this.importedModule,function(specs){if(!specs.length){return NULL_SETTER}var expressionStatements=_.map(specs,function(spec){var right=SETTER_MODULE_NAMESPACE;if(!spec.isBatch){right=t.memberExpression(right,spec.key)}return t.expressionStatement(t.assignmentExpression("=",spec.variableName,right))});return t.functionExpression(null,[SETTER_MODULE_NAMESPACE],t.blockStatement(expressionStatements))})};SystemFormatter.prototype.import=function(node){var MODULE_NAME=node.source.value;this.importedModule[MODULE_NAME]=this.importedModule[MODULE_NAME]||[]};SystemFormatter.prototype.importSpecifier=function(specifier,node){var variableName=t.getSpecifierName(specifier);if(specifier.default){specifier.id=DEFAULT_IDENTIFIER}var MODULE_NAME=node.source.value;this.importedModule[MODULE_NAME]=this.importedModule[MODULE_NAME]||[];this.importedModule[MODULE_NAME].push({variableName:variableName,isBatch:specifier.type==="ImportBatchSpecifier",key:specifier.id})};SystemFormatter.prototype._export=function(name,identifier){this.exportedStatements.push(t.expressionStatement(t.callExpression(this.exportIdentifier,[t.literal(name),identifier])))};SystemFormatter.prototype.export=function(node,nodes){var declar=node.declaration;var variableName,identifier;if(node.default){variableName=DEFAULT_IDENTIFIER.name;if(t.isClass(declar)||t.isFunction(declar)){if(!declar.id){declar.id=this.file.generateUidIdentifier("anonymous")}nodes.push(t.toStatement(declar));declar=declar.id}identifier=declar}else if(t.isVariableDeclaration(declar)){variableName=declar.declarations[0].id.name;identifier=declar.declarations[0].id;nodes.push(declar)}else{variableName=declar.id.name;identifier=declar.id;nodes.push(declar)}this._export(variableName,identifier)};SystemFormatter.prototype.exportSpecifier=function(specifier,node){var variableName=t.getSpecifierName(specifier);if(node.source){if(t.isExportBatchSpecifier(specifier)){var exportIdentifier=t.identifier("exports");this.exportedStatements.push(t.variableDeclaration("var",[t.variableDeclarator(exportIdentifier,this.exportIdentifier)]));this.exportedStatements.push(util.template("exports-wildcard",{OBJECT:t.identifier(node.source.value)},true))}else{this._export(variableName.name,t.memberExpression(t.identifier(node.source.value),specifier.id))}}else{this._export(variableName.name,specifier.id)}}},{"../../types":72,"../../util":74,lodash:105}],28:[function(require,module,exports){module.exports=UMDFormatter;var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var _=require("lodash");function UMDFormatter(){AMDFormatter.apply(this,arguments)}util.inherits(UMDFormatter,AMDFormatter);UMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[];_.each(this.ids,function(id,name){names.push(t.literal(name))});var ids=_.values(this.ids);var args=[t.identifier("exports")].concat(ids);var factory=t.functionExpression(null,args,t.blockStatement(body));var defineArgs=[t.arrayExpression([t.literal("exports")].concat(names))];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var runner=util.template("umd-runner-body",{AMD_ARGUMENTS:defineArgs,COMMON_ARGUMENTS:names.map(function(name){return t.callExpression(t.identifier("require"),[name])})});var call=t.callExpression(runner,[factory]);program.body=[t.expressionStatement(call)]}},{"../../types":72,"../../util":74,"./amd":23,lodash:105}],29:[function(require,module,exports){module.exports=transform;var Transformer=require("./transformer");var File=require("../file");var _=require("lodash");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform._ensureTransformerNames=function(type,keys){_.each(keys,function(key){if(!_.has(transform.transformers,key)){throw new ReferenceError("unknown transformer "+key+" specified in "+type)}})};transform.transformers={};transform.moduleFormatters={common:require("./modules/common"),commonInterop:require("./modules/common-interop"),system:require("./modules/system"),ignore:require("./modules/ignore"),amd:require("./modules/amd"),umd:require("./modules/umd")};_.each({modules:require("./transformers/es6-modules"),propertyNameShorthand:require("./transformers/es6-property-name-shorthand"),arrayComprehension:require("./transformers/es7-array-comprehension"),generatorComprehension:require("./transformers/es7-generator-comprehension"),arrowFunctions:require("./transformers/es6-arrow-functions"),classes:require("./transformers/es6-classes"),_propertyLiterals:require("./transformers/_property-literals"),computedPropertyNames:require("./transformers/es6-computed-property-names"),objectSpread:require("./transformers/es7-object-spread"),exponentiationOperator:require("./transformers/es7-exponentiation-operator"),spread:require("./transformers/es6-spread"),templateLiterals:require("./transformers/es6-template-literals"),propertyMethodAssignment:require("./transformers/es5-property-method-assignment"),defaultParameters:require("./transformers/es6-default-parameters"),restParameters:require("./transformers/es6-rest-parameters"),destructuring:require("./transformers/es6-destructuring"),forOf:require("./transformers/es6-for-of"),unicodeRegex:require("./transformers/es6-unicode-regex"),abstractReferences:require("./transformers/es7-abstract-references"),react:require("./transformers/react"),constants:require("./transformers/es6-constants"),letScoping:require("./transformers/es6-let-scoping"),generators:require("./transformers/es6-generators"),_blockHoist:require("./transformers/_block-hoist"),_declarations:require("./transformers/_declarations"),_aliasFunctions:require("./transformers/_alias-functions"),useStrict:require("./transformers/use-strict"),_memberExpressionKeywords:require("./transformers/_member-expression-keywords"),_moduleFormatter:require("./transformers/_module-formatter")},function(transformer,key){transform.transformers[key]=new Transformer(key,transformer)})},{"../file":3,"./modules/amd":23,"./modules/common":25,"./modules/common-interop":24,"./modules/ignore":26,"./modules/system":27,"./modules/umd":28,"./transformer":30,"./transformers/_alias-functions":31,"./transformers/_block-hoist":32,"./transformers/_declarations":33,"./transformers/_member-expression-keywords":34,"./transformers/_module-formatter":35,"./transformers/_property-literals":36,"./transformers/es5-property-method-assignment":37,"./transformers/es6-arrow-functions":38,"./transformers/es6-classes":39,"./transformers/es6-computed-property-names":40,"./transformers/es6-constants":41,"./transformers/es6-default-parameters":42,"./transformers/es6-destructuring":43,"./transformers/es6-for-of":44,"./transformers/es6-generators":49,"./transformers/es6-let-scoping":54,"./transformers/es6-modules":55,"./transformers/es6-property-name-shorthand":56,"./transformers/es6-rest-parameters":57,"./transformers/es6-spread":58,"./transformers/es6-template-literals":59,"./transformers/es6-unicode-regex":60,"./transformers/es7-abstract-references":61,"./transformers/es7-array-comprehension":62,"./transformers/es7-exponentiation-operator":63,"./transformers/es7-generator-comprehension":64,"./transformers/es7-object-spread":65,"./transformers/react":66,"./transformers/use-strict":67,lodash:105}],30:[function(require,module,exports){module.exports=Transformer;var traverse=require("../traverse");var t=require("../types");var _=require("lodash");function Transformer(key,transformer){this.transformer=Transformer.normalise(transformer);this.key=key}Transformer.normalise=function(transformer){if(_.isFunction(transformer)){transformer={ast:transformer}}_.each(transformer,function(fns,type){if(type[0]==="_")return;if(_.isFunction(fns))fns={enter:fns};transformer[type]=fns});return transformer};Transformer.prototype.transform=function(file){if(!this.canRun(file))return;var transformer=this.transformer;var ast=file.ast;var astRun=function(key){if(transformer.ast&&transformer.ast[key]){transformer.ast[key](ast,file)}};astRun("enter");var build=function(exit){return function(node,parent,scope){var types=[node.type].concat(t.ALIAS_KEYS[node.type]||[]);var fns=transformer.all;_.each(types,function(type){fns=transformer[type]||fns});if(!fns)return;var fn=fns.enter;if(exit)fn=fns.exit;if(!fn)return;return fn(node,parent,file,scope)}};traverse(ast,{enter:build(),exit:build(true)});astRun("exit")};Transformer.prototype.canRun=function(file){var opts=file.opts;var key=this.key;var blacklist=opts.blacklist;if(blacklist.length&&_.contains(blacklist,key))return false;if(key[0]!=="_"){var whitelist=opts.whitelist;if(whitelist.length&&!_.contains(whitelist,key))return false}return true}},{"../traverse":68,"../types":72,lodash:105}],31:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var go=function(getBody,node,file,scope){var argumentsId;var thisId;var getArgumentsId=function(){return argumentsId=argumentsId||file.generateUidIdentifier("arguments",scope)};var getThisId=function(){return thisId=thisId||file.generateUidIdentifier("this",scope)};traverse(node,function(node){if(!node._aliasFunction){if(t.isFunction(node)){return false}else{return}}traverse(node,function(node,parent){if(t.isFunction(node)&&!node._aliasFunction){return false}if(node._ignoreAliasFunctions)return false;var getId;if(t.isIdentifier(node)&&node.name==="arguments"){getId=getArgumentsId}else if(t.isThisExpression(node)){getId=getThisId}else{return}if(t.isReferenced(node,parent))return getId()});return false});var body;var pushDeclaration=function(id,init){body=body||getBody();body.unshift(t.variableDeclaration("var",[t.variableDeclarator(id,init)]))};if(argumentsId){pushDeclaration(argumentsId,t.identifier("arguments"))}if(thisId){pushDeclaration(thisId,t.identifier("this"))}};exports.Program=function(node,parent,file,scope){go(function(){return node.body},node,file,scope)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,file,scope){go(function(){t.ensureBlock(node);return node.body.body},node,file,scope)}},{"../../traverse":68,"../../types":72}],32:[function(require,module,exports){exports.BlockStatement=exports.Program={exit:function(node){var unshift=[];node.body=node.body.filter(function(bodyNode){if(bodyNode._blockHoist){unshift.push(bodyNode);return false}else{return true}});node.body=unshift.concat(node.body)}}},{}],33:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.BlockStatement=exports.Program=function(node){_.each(node._declarations,function(declar){node.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(declar.id,declar.init)]))})}},{"../../types":72,lodash:105}],34:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");exports.MemberExpression=function(node){var prop=node.property;if(t.isIdentifier(prop)&&esutils.keyword.isKeywordES6(prop.name,true)){node.property=t.literal(prop.name);node.computed=true}}},{"../../types":72,esutils:104}],35:[function(require,module,exports){var transform=require("../transform");exports.ast={exit:function(ast,file){if(!transform.transformers.modules.canRun(file))return;if(file.moduleFormatter.transform){file.moduleFormatter.transform(ast)}}}},{"../transform":29}],36:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");var _=require("lodash");exports.Property=function(node){var key=node.key;if(t.isLiteral(key)&&_.isString(key.value)&&esutils.keyword.isIdentifierName(key.value)){key.type="Identifier";key.name=key.value;delete key.value;node.computed=false}}},{"../../types":72,esutils:104,lodash:105}],37:[function(require,module,exports){var util=require("../../util");var _=require("lodash");exports.Property=function(node){if(node.method)node.method=false};exports.ObjectExpression=function(node,parent,file){var mutatorMap={};node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.value);return false}else{return true}});if(_.isEmpty(mutatorMap))return;var objId=util.getUid(parent,file);return util.template("object-define-properties-closure",{KEY:objId,OBJECT:node,CONTENT:util.template("object-define-properties",{OBJECT:objId,PROPS:util.buildDefineProperties(mutatorMap)})})}},{"../../util":74,lodash:105}],38:[function(require,module,exports){var t=require("../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction=true;node.expression=false;node.type="FunctionExpression";return node}},{"../../types":72}],39:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ClassDeclaration=function(node,parent,file,scope){return t.variableDeclaration("let",[t.variableDeclarator(node.id,new Class(node,file,scope).run())])};exports.ClassExpression=function(node,parent,file,scope){return new Class(node,file,scope).run()};var getMemberExpressionObject=function(node){while(t.isMemberExpression(node)){node=node.object}return node};function Class(node,file,scope){this.scope=scope;this.node=node;this.file=file;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||file.generateUidIdentifier("class",scope);this.superName=node.superClass}Class.prototype.run=function(){var superClassArgument=this.superName;var superClassCallee=this.superName;var superName=this.superName;var className=this.className;var file=this.file;if(superName){if(t.isMemberExpression(superName)){superClassArgument=superClassCallee=getMemberExpressionObject(superName)}else if(!t.isIdentifier(superName)){superClassArgument=superName;superClassCallee=superName=file.generateUidIdentifier("ref",this.scope)}}this.superName=superName;var container=util.template("class",{CLASS_NAME:className});var block=container.callee.expression.body;var body=this.body=block.body;var constructor=this.constructor=body[0].declarations[0].init;if(this.node.id)constructor.id=className;var returnStatement=body.pop();if(superName){body.push(t.expressionStatement(t.callExpression(file.addDeclaration("extends"),[className,superName])));container.arguments.push(superClassArgument);container.callee.expression.params.push(superClassCallee)}this.buildBody();if(body.length===1){return constructor}else{body.push(returnStatement);return container}};Class.prototype.buildBody=function(){var constructor=this.constructor;var className=this.className;var superName=this.superName;var classBody=this.node.body.body;var body=this.body;var self=this;_.each(classBody,function(node){self.replaceInstanceSuperReferences(node);if(node.key.name==="constructor"){self.pushConstructor(node)}else{self.pushMethod(node)}});if(!this.hasConstructor&&superName){constructor.body.body.push(util.template("class-super-constructor-call",{SUPER_NAME:superName},true))}var instanceProps;var staticProps;if(!_.isEmpty(this.instanceMutatorMap)){var protoId=util.template("prototype-identifier",{CLASS_NAME:className});instanceProps=util.buildDefineProperties(this.instanceMutatorMap,protoId)}if(!_.isEmpty(this.staticMutatorMap)){staticProps=util.buildDefineProperties(this.staticMutatorMap,className)}if(instanceProps||staticProps){staticProps=staticProps||t.literal(null);var args=[className,staticProps];if(instanceProps)args.push(instanceProps);body.push(t.expressionStatement(t.callExpression(this.file.addDeclaration("class-props"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var mutatorMap=this.instanceMutatorMap;if(node.static)mutatorMap=this.staticMutatorMap;var kind=node.kind;if(kind===""){kind="value";util.pushMutatorMap(mutatorMap,methodName,"writable",t.identifier("true"))}util.pushMutatorMap(mutatorMap,methodName,kind,node)};Class.prototype.superIdentifier=function(methodNode,id,parent){var methodName=methodNode.key;var superName=this.superName||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){parent.arguments.unshift(t.thisExpression());if(methodName.name==="constructor"){return t.memberExpression(superName,t.identifier("call"))}else{id=superName;if(!methodNode.static){id=t.memberExpression(id,t.identifier("prototype"))}id=t.memberExpression(id,methodName,methodNode.computed);return t.memberExpression(id,t.identifier("call"))}}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superName,t.identifier("prototype"))}else{return superName}};Class.prototype.replaceInstanceSuperReferences=function(methodNode){var method=methodNode.value;var self=this;traverse(method,function(node,parent){if(t.isIdentifier(node,{name:"super"})){return self.superIdentifier(methodNode,node,parent)}else if(t.isCallExpression(node)){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;callee.property=t.memberExpression(callee.property,t.identifier("call"));node.arguments.unshift(t.thisExpression())}})};Class.prototype.pushConstructor=function(method){if(method.kind!==""){throw this.file.errorWithNode(method,"illegal kind for constructor method")}var construct=this.constructor;var fn=method.value;this.hasConstructor=true;t.inherits(construct,fn);t.inheritsComments(construct,method);construct.defaults=fn.defaults;construct.params=fn.params;construct.body=fn.body;construct.rest=fn.rest}},{"../../traverse":68,"../../types":72,"../../util":74,lodash:105}],40:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ObjectExpression=function(node,parent,file){var hasComputed=false;var computed=[];node.properties=node.properties.filter(function(prop){if(prop.computed){hasComputed=true;computed.unshift(prop);return false}else{return true}});if(!hasComputed)return;var objId=util.getUid(parent,file);var container=util.template("function-return-obj",{KEY:objId,OBJECT:node});var containerCallee=container.callee.expression;var containerBody=containerCallee.body.body;containerCallee._aliasFunction=true;_.each(computed,function(prop){containerBody.unshift(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,true),prop.value)))});return container}},{"../../types":72,"../../util":74,lodash:105}],41:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var _=require("lodash");exports.Program=exports.BlockStatement=exports.ForInStatement=exports.ForOfStatement=exports.ForStatement=function(node,parent,file){var constants={};var check=function(parent,names){_.each(names,function(nameNode,name){if(!_.has(constants,name))return;if(parent&&t.isBlockStatement(parent)&&parent!==constants[name])return;throw file.errorWithNode(nameNode,name+" is read-only")})};var getIds=function(node){return t.getIds(node,true,["MemberExpression"])};_.each(node.body,function(child,parent){if(child&&t.isVariableDeclaration(child,{kind:"const"})){_.each(child.declarations,function(declar){_.each(getIds(declar),function(nameNode,name){var names={};names[name]=nameNode;check(parent,names);constants[name]=parent});declar._ignoreConstant=true});child._ignoreConstant=true;child.kind="let"}});if(_.isEmpty(constants))return;traverse(node,function(child,parent){if(child._ignoreConstant)return;if(t.isVariableDeclaration(child))return;if(t.isVariableDeclarator(child)||t.isDeclaration(child)||t.isAssignmentExpression(child)){check(parent,getIds(child))}})}},{"../../traverse":68,"../../types":72,lodash:105}],42:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.Function=function(node,parent,file,scope){if(!node.defaults||!node.defaults.length)return;t.ensureBlock(node);var ids=node.params.map(function(param){return t.getIds(param)});var closure=false;_.each(node.defaults,function(def,i){if(!def)return;var param=node.params[i];_.each(ids.slice(i),function(ids){var check=function(node,parent){if(!t.isIdentifier(node)||!t.isReferenced(node,parent))return;if(_.contains(ids,node.name)){throw file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}if(scope.has(node.name)){closure=true}};check(def,node);traverse(def,check)});var has=scope.get(param.name);if(has&&!_.contains(node.params,has)){closure=true}});var body=[];_.each(node.defaults,function(def,i){if(!def)return;body.push(util.template("if-undefined-set-to",{VARIABLE:node.params[i],DEFAULT:def},true))});if(closure){var container=t.functionExpression(null,[],node.body,node.generator);container._aliasFunction=true;body.push(t.returnStatement(t.callExpression(container,[])));node.body=t.blockStatement(body)}else{node.body.body=body.concat(node.body.body)}node.defaults=[]}},{"../../traverse":68,"../../types":72,"../../util":74,lodash:105}],43:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildVariableAssign=function(kind,id,init){if(kind===false){return t.expressionStatement(t.assignmentExpression("=",id,init))}else{return t.variableDeclaration(kind,[t.variableDeclarator(id,init)])}};var push=function(opts,nodes,elem,parentId){if(t.isObjectPattern(elem)){pushObjectPattern(opts,nodes,elem,parentId)}else if(t.isArrayPattern(elem)){pushArrayPattern(opts,nodes,elem,parentId)}else if(t.isMemberExpression(elem)){nodes.push(buildVariableAssign(false,elem,parentId))}else{nodes.push(buildVariableAssign(opts.kind,elem,parentId))}};var pushObjectPattern=function(opts,nodes,pattern,parentId){_.each(pattern.properties,function(prop,i){if(t.isSpreadProperty(prop)){var keys=[];_.each(pattern.properties,function(prop2,i2){if(i2>=i)return false;if(t.isSpreadProperty(prop2))return;var key=prop2.key;if(t.isIdentifier(key)){key=t.literal(prop2.key.name)}keys.push(key)});keys=t.arrayExpression(keys);var value=t.callExpression(opts.file.addDeclaration("object-spread"),[parentId,keys]);nodes.push(buildVariableAssign(opts.kind,prop.argument,value))}else{var pattern2=prop.value;var patternId2=t.memberExpression(parentId,prop.key,prop.computed);if(t.isPattern(pattern2)){push(opts,nodes,pattern2,patternId2)}else{nodes.push(buildVariableAssign(opts.kind,pattern2,patternId2))}}})};var pushArrayPattern=function(opts,nodes,pattern,parentId){var _parentId=opts.file.generateUidIdentifier("ref",opts.scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(_parentId,opts.file.toArray(parentId))]));parentId=_parentId;_.each(pattern.elements,function(elem,i){if(!elem)return;var newPatternId;if(t.isSpreadElement(elem)){newPatternId=opts.file.toArray(parentId);if(+i>0){newPatternId=t.callExpression(t.memberExpression(newPatternId,t.identifier("slice")),[t.literal(i)])}elem=elem.argument}else{newPatternId=t.memberExpression(parentId,t.literal(i),true) }push(opts,nodes,elem,newPatternId)})};var pushPattern=function(opts){var nodes=opts.nodes;var pattern=opts.pattern;var parentId=opts.id;var file=opts.file;var scope=opts.scope;if(!t.isMemberExpression(parentId)&&!t.isIdentifier(parentId)){var key=file.generateUidIdentifier("ref",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,parentId)]));parentId=key}push(opts,nodes,pattern,parentId)};exports.ForInStatement=exports.ForOfStatement=function(node,parent,file,scope){var declar=node.left;if(!t.isVariableDeclaration(declar))return;var pattern=declar.declarations[0].id;if(!t.isPattern(pattern))return;var key=file.generateUidIdentifier("ref",scope);node.left=t.variableDeclaration(declar.kind,[t.variableDeclarator(key,null)]);var nodes=[];push({kind:declar.kind,file:file,scope:scope},nodes,pattern,key);t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.Function=function(node,parent,file,scope){var nodes=[];var hasDestructuring=false;node.params=node.params.map(function(pattern){if(!t.isPattern(pattern))return pattern;hasDestructuring=true;var parentId=file.generateUidIdentifier("ref",scope);pushPattern({kind:"var",nodes:nodes,pattern:pattern,id:parentId,file:file,scope:scope});return parentId});if(!hasDestructuring)return;t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.ExpressionStatement=function(node,parent,file,scope){var expr=node.expression;if(expr.type!=="AssignmentExpression")return;if(!t.isPattern(expr.left))return;var nodes=[];var ref=file.generateUidIdentifier("ref",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(ref,expr.right)]));push({kind:false,file:file,scope:scope},nodes,expr.left,ref);return nodes};exports.AssignmentExpression=function(node,parent,file,scope){if(parent.type==="ExpressionStatement")return;if(!t.isPattern(node.left))return;var tempName=file.generateUid("temp",scope);var temp=t.identifier(tempName);scope.push(tempName,temp);var nodes=[];nodes.push(t.assignmentExpression("=",temp,node.right));push({kind:false,file:file,scope:scope},nodes,node.left,temp);nodes.push(temp);nodes=nodes.map(function(node){if(t.isExpressionStatement(node)){return node.expression}else if(t.isVariableDeclaration(node)){var declar=node.declarations[0];scope.push(declar.id.name,declar.id);return t.assignmentExpression("=",declar.id,declar.init)}else{return node}});return t.sequenceExpression(nodes)};exports.VariableDeclaration=function(node,parent,file,scope){if(t.isForInStatement(parent)||t.isForOfStatement(parent))return;var nodes=[];var hasPattern=false;_.each(node.declarations,function(declar){if(t.isPattern(declar.id)){hasPattern=true;return false}});if(!hasPattern)return;_.each(node.declarations,function(declar){var patternId=declar.init;var pattern=declar.id;if(t.isPattern(pattern)&&patternId){pushPattern({kind:node.kind,nodes:nodes,pattern:pattern,id:patternId,file:file,scope:scope})}else{nodes.push(buildVariableAssign(node.kind,declar.id,declar.init))}});if(!t.isProgram(parent)&&!t.isBlockStatement(parent)){var declar;_.each(nodes,function(node){declar=declar||t.variableDeclaration(node.kind,[]);if(!t.isVariableDeclaration(node)&&declar.kind!==node.kind){throw file.errorWithNode(node,"Cannot use this node within the current parent")}declar.declarations=declar.declarations.concat(node.declarations)});return declar}return nodes}},{"../../types":72,lodash:105}],44:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.ForOfStatement=function(node,parent,file,scope){var left=node.left;var declar;var stepKey=file.generateUidIdentifier("step",scope);var stepValue=t.memberExpression(stepKey,t.identifier("value"));if(t.isIdentifier(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var node2=util.template("for-of",{ITERATOR_KEY:file.generateUidIdentifier("iterator",scope),STEP_KEY:stepKey,OBJECT:node.right});t.ensureBlock(node);var block=node2.body;block.body.push(declar);block.body=block.body.concat(node.body.body);return node2}},{"../../types":72,"../../util":74}],45:[function(require,module,exports){var assert=require("assert");var loc=require("../util").loc;var t=require("../../../../types");exports.ParenthesizedExpression=function(expr,path,explodeViaTempVar,finish){return finish(this.explodeExpression(path.get("expression")))};exports.MemberExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.memberExpression(this.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed))};exports.CallExpression=function(expr,path,explodeViaTempVar,finish){var oldCalleePath=path.get("callee");var newCallee=this.explodeExpression(oldCalleePath);if(!t.isMemberExpression(oldCalleePath.node)&&t.isMemberExpression(newCallee)){newCallee=t.sequenceExpression([t.literal(0),newCallee])}return finish(t.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})))};exports.NewExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})))};exports.ObjectExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.objectExpression(path.get("properties").map(function(propPath){return t.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})))};exports.ArrayExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})))};exports.SequenceExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var lastIndex=expr.expressions.length-1;var self=this;var result;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result};exports.LogicalExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var after=loc();var result;if(!ignoreResult){result=this.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){this.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");this.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);this.mark(after);return result};exports.ConditionalExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var elseLoc=loc();var after=loc();var test=this.explodeExpression(path.get("test"));var result;this.jumpIfNot(test,elseLoc);if(!ignoreResult){result=this.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);this.jump(after);this.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);this.mark(after);return result};exports.UnaryExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.unaryExpression(expr.operator,this.explodeExpression(path.get("argument")),!!expr.prefix))};exports.BinaryExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))))};exports.AssignmentExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.assignmentExpression(expr.operator,this.explodeExpression(path.get("left")),this.explodeExpression(path.get("right"))))};exports.UpdateExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.updateExpression(expr.operator,this.explodeExpression(path.get("argument")),expr.prefix))};exports.YieldExpression=function(expr,path){var after=loc();var arg=expr.argument&&this.explodeExpression(path.get("argument"));var result;if(arg&&expr.delegate){result=this.makeTempVar();this.emit(t.returnStatement(t.callExpression(this.contextProperty("delegateYield"),[arg,t.literal(result.property.name),after])));this.mark(after);return result}this.emitAssign(this.contextProperty("next"),after);this.emit(t.returnStatement(arg||null));this.mark(after);return this.contextProperty("sent")}},{"../../../../types":72,"../util":52,assert:90}],46:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var leap=require("../leap");var util=require("../util");var t=require("../../../../types");var runtimeKeysMethod=util.runtimeProperty("keys");var loc=util.loc;exports.ExpressionStatement=function(path){this.explodeExpression(path.get("expression"),true)};exports.LabeledStatement=function(path,stmt){this.explodeStatement(path.get("body"),stmt.label)};exports.WhileStatement=function(path,stmt,labelId){var before=loc();var after=loc();this.mark(before);this.jumpIfNot(this.explodeExpression(path.get("test")),after);this.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){this.explodeStatement(path.get("body"))});this.jump(before);this.mark(after)};exports.DoWhileStatement=function(path,stmt,labelId){var first=loc();var test=loc();var after=loc();this.mark(first);this.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){this.explode(path.get("body"))});this.mark(test);this.jumpIf(this.explodeExpression(path.get("test")),first);this.mark(after)};exports.ForStatement=function(path,stmt,labelId){var head=loc();var update=loc();var after=loc();if(stmt.init){this.explode(path.get("init"),true)}this.mark(head);if(stmt.test){this.jumpIfNot(this.explodeExpression(path.get("test")),after)}else{}this.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){this.explodeStatement(path.get("body"))});this.mark(update);if(stmt.update){this.explode(path.get("update"),true)}this.jump(head);this.mark(after)};exports.ForInStatement=function(path,stmt,labelId){t.assertIdentifier(stmt.left);var head=loc();var after=loc();var keyIterNextFn=this.makeTempVar();this.emitAssign(keyIterNextFn,t.callExpression(runtimeKeysMethod,[this.explodeExpression(path.get("right"))]));this.mark(head);var keyInfoTmpVar=this.makeTempVar();this.jumpIf(t.memberExpression(t.assignmentExpression("=",keyInfoTmpVar,t.callExpression(keyIterNextFn,[])),t.identifier("done"),false),after);this.emitAssign(stmt.left,t.memberExpression(keyInfoTmpVar,t.identifier("value"),false));this.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){this.explodeStatement(path.get("body"))});this.jump(head);this.mark(after)};exports.BreakStatement=function(path,stmt){this.emitAbruptCompletion({type:"break",target:this.leapManager.getBreakLoc(stmt.label)})};exports.ContinueStatement=function(path,stmt){this.emitAbruptCompletion({type:"continue",target:this.leapManager.getContinueLoc(stmt.label)})};exports.SwitchStatement=function(path,stmt){var disc=this.emitAssign(this.makeTempVar(),this.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var self=this;var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];t.assertSwitchCase(c);if(c.test){condition=t.conditionalExpression(t.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}this.jump(this.explodeExpression(new types.NodePath(condition,path,"discriminant")));this.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});this.mark(after);if(defaultLoc.value===-1){this.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}};exports.IfStatement=function(path,stmt){var elseLoc=stmt.alternate&&loc();var after=loc();this.jumpIfNot(this.explodeExpression(path.get("test")),elseLoc||after);this.explodeStatement(path.get("consequent"));if(elseLoc){this.jump(after);this.mark(elseLoc);this.explodeStatement(path.get("alternate"))}this.mark(after)};exports.ReturnStatement=function(path){this.emitAbruptCompletion({type:"return",value:this.explodeExpression(path.get("argument"))})};exports.TryStatement=function(path,stmt){var after=loc();var self=this;var handler=stmt.handler;if(!handler&&stmt.handlers){handler=stmt.handlers[0]||null}var catchLoc=handler&&loc();var catchEntry=catchLoc&&new leap.CatchEntry(catchLoc,handler.param);var finallyLoc=stmt.finalizer&&loc();var finallyEntry=finallyLoc&&new leap.FinallyEntry(finallyLoc);var tryEntry=new leap.TryEntry(this.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);this.tryEntries.push(tryEntry);this.updateContextPrevLoc(tryEntry.firstLoc);this.leapManager.withEntry(tryEntry,function(){this.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){this.jump(finallyLoc)}else{this.jump(after)}this.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=this.makeTempVar();this.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;t.assertCatchClause(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(path.value.name===catchParamName&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)}});this.leapManager.withEntry(catchEntry,function(){this.explodeStatement(bodyPath)})}if(finallyLoc){this.updateContextPrevLoc(this.mark(finallyLoc));this.leapManager.withEntry(finallyEntry,function(){this.explodeStatement(path.get("finalizer"))});this.emit(t.callExpression(this.contextProperty("finish"),[finallyEntry.firstLoc]))}});this.mark(after)};exports.ThrowStatement=function(path){this.emit(t.throwStatement(this.explodeExpression(path.get("argument"))))}},{"../../../../types":72,"../leap":50,"../util":52,assert:90,"ast-types":88}],47:[function(require,module,exports){exports.Emitter=Emitter;var explodeExpressions=require("./explode-expressions");var explodeStatements=require("./explode-statements");var assert=require("assert");var types=require("ast-types");var leap=require("../leap");var meta=require("../meta");var util=require("../util");var t=require("../../../../types");var _=require("lodash");var loc=util.loc;var n=types.namedTypes;function Emitter(contextId){assert.ok(this instanceof Emitter);t.assertIdentifier(contextId);this.contextId=contextId;this.listing=[];this.marked=[true];this.finalLoc=loc();this.tryEntries=[];this.leapManager=new leap.LeapManager(this)}Emitter.prototype.mark=function(loc){t.assertLiteral(loc);var index=this.listing.length;if(loc.value===-1){loc.value=index}else{assert.strictEqual(loc.value,index)}this.marked[index]=true;return loc};Emitter.prototype.emit=function(node){if(t.isExpression(node))node=t.expressionStatement(node);t.assertStatement(node);this.listing.push(node)};Emitter.prototype.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Emitter.prototype.assign=function(lhs,rhs){return t.expressionStatement(t.assignmentExpression("=",lhs,rhs))};Emitter.prototype.contextProperty=function(name,computed){return t.memberExpression(this.contextId,computed?t.literal(name):t.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Emitter.prototype.isVolatileContextProperty=function(expr){if(t.isMemberExpression(expr)){if(expr.computed){return true}if(t.isIdentifier(expr.object)&&t.isIdentifier(expr.property)&&expr.object.name===this.contextId.name&&_.has(volatileContextPropertyNames,expr.property.name)){return true}}return false};Emitter.prototype.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Emitter.prototype.setReturnValue=function(valuePath){t.assertExpression(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Emitter.prototype.clearPendingException=function(tryLoc,assignee){t.assertLiteral(tryLoc);var catchCall=t.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Emitter.prototype.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(t.breakStatement())};Emitter.prototype.jumpIf=function(test,toLoc){t.assertExpression(test);t.assertLiteral(toLoc);this.emit(t.ifStatement(test,t.blockStatement([this.assign(this.contextProperty("next"),toLoc),t.breakStatement()])))};Emitter.prototype.jumpIfNot=function(test,toLoc){t.assertExpression(test);t.assertLiteral(toLoc);var negatedTest;if(t.isUnaryExpression(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=t.unaryExpression("!",test)}this.emit(t.ifStatement(negatedTest,t.blockStatement([this.assign(this.contextProperty("next"),toLoc),t.breakStatement()])))};var nextTempId=0;Emitter.prototype.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Emitter.prototype.getContextFunction=function(id){var node=t.functionExpression(id||null,[this.contextId],t.blockStatement([this.getDispatchLoop()]),false,false);node._aliasFunction=true;return node};Emitter.prototype.getDispatchLoop=function(){var self=this;var cases=[];var current;var alreadyEnded=false;self.listing.forEach(function(stmt,i){if(self.marked.hasOwnProperty(i)){cases.push(t.switchCase(t.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(t.switchCase(this.finalLoc,[]),t.switchCase(t.literal("end"),[t.returnStatement(t.callExpression(this.contextProperty("stop"),[]))]));return t.whileStatement(t.literal(true),t.switchStatement(t.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return t.isBreakStatement(stmt)||t.isContinueStatement(stmt)||t.isReturnStatement(stmt)||t.isThrowStatement(stmt)}Emitter.prototype.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return t.arrayExpression(this.tryEntries.map(function(tryEntry){var thisLocValue=tryEntry.firstLoc.value;assert.ok(thisLocValue>=lastLocValue,"try entries out of order");lastLocValue=thisLocValue;var ce=tryEntry.catchEntry;var fe=tryEntry.finallyEntry;var triple=[tryEntry.firstLoc,ce?ce.firstLoc:null];if(fe){triple[2]=fe.firstLoc}return t.arrayExpression(triple)}))};Emitter.prototype.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.check(node);if(t.isStatement(node))return self.explodeStatement(path);if(t.isExpression(node))return self.explodeExpression(path,ignoreResult);if(t.isDeclaration(node))throw getDeclError(node);switch(node.type){case"Program":return path.get("body").map(self.explodeStatement,self);case"VariableDeclarator":throw getDeclError(node);case"Property":case"SwitchCase":case"CatchClause":throw new Error(node.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(node.type))}};function getDeclError(node){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(node))}Emitter.prototype.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;t.assertStatement(stmt);if(labelId){t.assertIdentifier(labelId)}else{labelId=null}if(t.isBlockStatement(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}var fn=explodeStatements[stmt.type];if(fn){fn.call(this,path,stmt,labelId)}else{throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Emitter.prototype.emitAbruptCompletion=function(record){if(!isValidCompletion(record)){assert.ok(false,"invalid completion record: "+JSON.stringify(record))}assert.notStrictEqual(record.type,"normal","normal completions are not abrupt");var abruptArgs=[t.literal(record.type)];if(record.type==="break"||record.type==="continue"){t.assertLiteral(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){t.assertExpression(record.value);abruptArgs[1]=record.value}}this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!_.has(record,"target")}if(type==="break"||type==="continue"){return!_.has(record,"value")&&t.isLiteral(record.target)}if(type==="return"||type==="throw"){return _.has(record,"value")&&!_.has(record,"target")}return false}Emitter.prototype.getUnmarkedCurrentLoc=function(){return t.literal(this.listing.length)};Emitter.prototype.updateContextPrevLoc=function(loc){if(loc){t.assertLiteral(loc);if(loc.value===-1){loc.value=this.listing.length}else{assert.strictEqual(loc.value,this.listing.length)}}else{loc=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),loc)};Emitter.prototype.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){t.assertExpression(expr)}else{return expr}var self=this;function finish(expr){t.assertExpression(expr);if(ignoreResult){self.emit(expr)}else{return expr}}if(!meta.containsLeap(expr)){return finish(expr)}var hasLeapingChildren=meta.containsLeap.onlyChildren(expr);function explodeViaTempVar(tempVar,childPath,ignoreChildResult){assert.ok(childPath instanceof types.NodePath);assert.ok(!ignoreChildResult||!tempVar,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var result=self.explodeExpression(childPath,ignoreChildResult);if(ignoreChildResult){}else if(tempVar||hasLeapingChildren&&(self.isVolatileContextProperty(result)||meta.hasSideEffects(result))){result=self.emitAssign(tempVar||self.makeTempVar(),result)}return result}var fn=explodeExpressions[expr.type];if(fn){return fn.call(this,expr,path,explodeViaTempVar,finish,ignoreResult)}else{throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"../../../../types":72,"../leap":50,"../meta":51,"../util":52,"./explode-expressions":45,"./explode-statements":46,assert:90,"ast-types":88,lodash:105}],48:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var t=require("../../../types");var _=require("lodash");exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);t.assertFunction(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){t.assertVariableDeclaration(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(t.assignmentExpression("=",dec.id,dec.init))}else if(includeIdentifiers){exprs.push(dec.id)}});if(exprs.length===0)return null;if(exprs.length===1)return exprs[0];return t.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return t.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(t.isVariableDeclaration(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(t.isVariableDeclaration(left)){path.get("left").replace(varDeclToExpr(left,true))}this.traverse(path)},visitFunctionDeclaration:function(path){var node=path.value;vars[node.id.name]=node.id;var assignment=t.expressionStatement(t.assignmentExpression("=",node.id,t.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(t.isBlockStatement(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(t.isIdentifier(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!_.has(paramNames,name)){declarations.push(t.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return t.variableDeclaration("var",declarations)}},{"../../../types":72,assert:90,"ast-types":88,lodash:105}],49:[function(require,module,exports){module.exports=require("./visit").transform},{"./visit":53}],50:[function(require,module,exports){exports.FunctionEntry=FunctionEntry;exports.FinallyEntry=FinallyEntry;exports.SwitchEntry=SwitchEntry;exports.LeapManager=LeapManager;exports.CatchEntry=CatchEntry;exports.LoopEntry=LoopEntry;exports.TryEntry=TryEntry;var assert=require("assert");var util=require("util");var t=require("../../../types");var inherits=util.inherits;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);t.assertLiteral(returnLoc);this.returnLoc=returnLoc}inherits(FunctionEntry,Entry);function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);t.assertLiteral(breakLoc);t.assertLiteral(continueLoc);if(label){t.assertIdentifier(label)}else{label=null}this.breakLoc=breakLoc;this.continueLoc=continueLoc;this.label=label}inherits(LoopEntry,Entry);function SwitchEntry(breakLoc){Entry.call(this);t.assertLiteral(breakLoc);this.breakLoc=breakLoc}inherits(SwitchEntry,Entry);function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);t.assertLiteral(firstLoc);if(catchEntry){assert.ok(catchEntry instanceof CatchEntry)}else{catchEntry=null}if(finallyEntry){assert.ok(finallyEntry instanceof FinallyEntry)}else{finallyEntry=null}assert.ok(catchEntry||finallyEntry);this.firstLoc=firstLoc;this.catchEntry=catchEntry;this.finallyEntry=finallyEntry}inherits(TryEntry,Entry);function CatchEntry(firstLoc,paramId){Entry.call(this);t.assertLiteral(firstLoc);t.assertIdentifier(paramId);this.firstLoc=firstLoc;this.paramId=paramId}inherits(CatchEntry,Entry);function FinallyEntry(firstLoc){Entry.call(this);t.assertLiteral(firstLoc);this.firstLoc=firstLoc}inherits(FinallyEntry,Entry);function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);this.emitter=emitter;this.entryStack=[new FunctionEntry(emitter.finalLoc)]}LeapManager.prototype.withEntry=function(entry,callback){assert.ok(entry instanceof Entry);this.entryStack.push(entry);try{callback.call(this.emitter)}finally{var popped=this.entryStack.pop();assert.strictEqual(popped,entry)}};LeapManager.prototype._findLeapLocation=function(property,label){for(var i=this.entryStack.length-1;i>=0;--i){var entry=this.entryStack[i];var loc=entry[property];if(loc){if(label){if(entry.label&&entry.label.name===label.name){return loc}}else{return loc}}}return null};LeapManager.prototype.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LeapManager.prototype.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"../../../types":72,"./emit":47,assert:90,util:99}],51:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var m=require("private").makeAccessor();var _=require("lodash");var isArray=types.builtInTypes.array;var n=types.namedTypes;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.check(node);var result=false;function check(child){if(result){}else if(isArray.check(child)){child.some(check)}else if(n.Node.check(child)){assert.strictEqual(result,false);result=predicate(child)}return result}types.eachField(node,function(name,child){check(child)});return result}function predicate(node){n.Node.check(node);var meta=m(node);if(_.has(meta,propertyName))return meta[propertyName];if(_.has(opaqueTypes,node.type))return meta[propertyName]=false;if(_.has(knownTypes,node.type))return meta[propertyName]=true;return meta[propertyName]=onlyChildren(node)}predicate.onlyChildren=onlyChildren;return predicate}var opaqueTypes={FunctionExpression:true};var sideEffectTypes={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var leapTypes={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var type in leapTypes){if(_.has(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:90,"ast-types":88,lodash:105,"private":106}],52:[function(require,module,exports){var t=require("../../../types");exports.runtimeProperty=function(name){return t.memberExpression(t.identifier("regeneratorRuntime"),t.identifier(name))};exports.loc=function(){return t.literal(-1)}},{"../../../types":72}],53:[function(require,module,exports){var runtimeProperty=require("./util").runtimeProperty;var Emitter=require("./emit").Emitter;var hoist=require("./hoist").hoist;var types=require("ast-types");var t=require("../../../types");var runtimeAsyncMethod=runtimeProperty("async");var runtimeWrapMethod=runtimeProperty("wrap");var runtimeMarkMethod=runtimeProperty("mark");exports.transform=function transform(node,file){return types.visit(node,{visitFunction:function(path){return visitor.call(this,path,file)}})};var visitor=function(path,file){this.traverse(path);var node=path.value;var scope;if(!node.generator&&!node.async){return}node.generator=false;if(node.expression){node.expression=false;node.body=t.blockStatement([t.returnStatement(node.body)])}if(node.async){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=file.generateUidIdentifier("callee",scope));var innerFnId=t.identifier(node.id.name+"$");var contextId=file.generateUidIdentifier("context",scope);var vars=hoist(path);var emitter=new Emitter(contextId);emitter.explode(path.get("body"));var outerBody=[];if(vars&&vars.declarations.length>0){outerBody.push(vars)}var wrapArgs=[emitter.getContextFunction(innerFnId),node.async?t.literal(null):outerFnId,t.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=t.callExpression(node.async?runtimeAsyncMethod:runtimeWrapMethod,wrapArgs);outerBody.push(t.returnStatement(wrapCall));node.body=t.blockStatement(outerBody);if(node.async){node.async=false;return}if(t.isFunctionDeclaration(node)){var pp=path.parent;while(pp&&!(t.isBlockStatement(pp.value)||t.isProgram(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=t.variableDeclaration("var",[t.variableDeclarator(node.id,t.callExpression(runtimeMarkMethod,[node]))]);t.inheritsComments(varDecl,node);t.removeComments(node);varDecl._blockHoist=true;var bodyPath=pp.get("body");var bodyLen=bodyPath.value.length;for(var i=0;i<bodyLen;++i){var firstStmtPath=bodyPath.get(i);if(!shouldNotHoistAbove(firstStmtPath)){firstStmtPath.insertBefore(varDecl);return}}bodyPath.push(varDecl)}else{t.assertFunctionExpression(node);return t.callExpression(runtimeMarkMethod,[node])}};function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;t.assertStatement(value);if(t.isExpressionStatement(value)&&t.isLiteral(value.expression)&&value.expression.value==="use strict"){return true}if(t.isVariableDeclaration(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(t.isCallExpression(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeMarkMethod)){return true}}}return false}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(){return false},visitAwaitExpression:function(path){return t.yieldExpression(path.value.argument,false) }})},{"../../../types":72,"./emit":47,"./hoist":48,"./util":52,"ast-types":88}],54:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");var isLet=function(node){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;node._let=true;node.kind="var";return true};var isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node)};var standardiseLets=function(declars){_.each(declars,function(declar){delete declar._let})};exports.VariableDeclaration=function(node){isLet(node)};exports.For=function(node,parent,file,scope){var init=node.left||node.init;if(isLet(init)){t.ensureBlock(node);node.body._letDeclars=[init]}if(t.isLabeledStatement(parent)){node.label=parent.label}var letScoping=new LetScoping(node,node.body,parent,file,scope);letScoping.run();if(node.label&&!t.isLabeledStatement(parent)){return t.labeledStatement(node.label,node)}};exports.BlockStatement=function(block,parent,file,scope){if(!t.isFor(parent)){var letScoping=new LetScoping(false,block,parent,file,scope);letScoping.run()}};function LetScoping(forParent,block,parent,file,scope){this.forParent=forParent;this.parent=parent;this.scope=scope;this.block=block;this.file=file;this.letReferences={};this.body=[]}LetScoping.prototype.run=function(){var block=this.block;if(block._letDone)return;block._letDone=true;this.info=this.getInfo();this.remap();if(t.isFunction(this.parent))return this.noClosure();if(!this.info.keys.length)return this.noClosure();var referencesInClosure=this.getLetReferences();if(!referencesInClosure)return this.noClosure();this.has=this.checkFor();this.hoistVarDeclarations();standardiseLets(this.info.declarators);var letReferences=_.values(this.letReferences);var fn=t.functionExpression(null,letReferences,t.blockStatement(block.body));fn._aliasFunction=true;block.body=this.body;var params=this.getParams(letReferences);var call=t.callExpression(fn,params);var ret=this.file.generateUidIdentifier("ret",this.scope);var hasYield=traverse.hasType(fn.body,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}this.build(ret,call)};LetScoping.prototype.noClosure=function(){standardiseLets(this.info.declarators)};LetScoping.prototype.remap=function(){var replacements=this.info.duplicates;var block=this.block;if(_.isEmpty(replacements))return;var replace=function(node,parent,scope){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;if(scope&&scope.hasOwn(node.name))return;node.name=replacements[node.name]||node.name};var traverseReplace=function(node,parent){replace(node,parent);traverse(node,replace)};var forParent=this.forParent;if(forParent){traverseReplace(forParent.right,forParent);traverseReplace(forParent.test,forParent);traverseReplace(forParent.update,forParent)}traverse(block,replace)};LetScoping.prototype.getInfo=function(){var block=this.block;var scope=this.scope;var file=this.file;var opts={outsideKeys:[],declarators:block._letDeclars||[],duplicates:{},keys:[]};var duplicates=function(id,key){var has=scope.parentGet(key);if(has&&has!==id){opts.duplicates[key]=id.name=file.generateUid(key,scope)}};_.each(opts.declarators,function(declar){opts.declarators.push(declar);var keys=t.getIds(declar,true);_.each(keys,duplicates);keys=_.keys(keys);opts.outsideKeys=opts.outsideKeys.concat(keys);opts.keys=opts.keys.concat(keys)});_.each(block.body,function(declar){if(!isLet(declar))return;_.each(t.getIds(declar,true),function(id,key){duplicates(id,key);opts.keys.push(key)})});return opts};LetScoping.prototype.checkFor=function(){var has={hasContinue:false,hasReturn:false,hasBreak:false};var forParent=this.forParent;traverse(this.block,function(node){var replace;if(t.isFunction(node)||t.isFor(node)){return false}if(forParent&&node&&!node.label){if(t.isBreakStatement(node)){has.hasBreak=true;replace=t.returnStatement(t.literal("break"))}else if(t.isContinueStatement(node)){has.hasContinue=true;replace=t.returnStatement(t.literal("continue"))}}if(t.isReturnStatement(node)){has.hasReturn=true;replace=t.returnStatement(t.objectExpression([t.property("init",t.identifier("v"),node.argument||t.identifier("undefined"))]))}if(replace)return t.inherits(replace,node)});return has};LetScoping.prototype.hoistVarDeclarations=function(){var self=this;traverse(this.block,function(node){if(t.isForStatement(node)){if(isVar(node.init)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left)){node.left=node.left.declarations[0].id}}else if(isVar(node)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return false}})};LetScoping.prototype.getParams=function(params){var info=this.info;params=_.cloneDeep(params);_.each(params,function(param){param.name=info.duplicates[param.name]||param.name});return params};LetScoping.prototype.getLetReferences=function(){var closurify=false;var self=this;traverse(this.block,function(node,parent,scope){if(t.isFunction(node)){traverse(node,function(node,parent){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;if(scope.hasOwn(node.name))return;closurify=true;if(!_.contains(self.info.outsideKeys,node.name))return;self.letReferences[node.name]=node});return false}else if(t.isFor(node)){return false}});return closurify};LetScoping.prototype.pushDeclar=function(node){this.body.push(t.variableDeclaration(node.kind,node.declarations.map(function(declar){return t.variableDeclarator(declar.id)})));var replace=[];_.each(node.declarations,function(declar){if(!declar.init)return;var expr=t.assignmentExpression("=",declar.id,declar.init);replace.push(t.inherits(expr,declar))});return replace};LetScoping.prototype.build=function(ret,call){var has=this.has;if(has.hasReturn||has.hasBreak||has.hasContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};LetScoping.prototype.buildHas=function(ret,call){var body=this.body;body.push(t.variableDeclaration("var",[t.variableDeclarator(ret,call)]));var forParent=this.forParent;var retCheck;var has=this.has;var cases=[];if(has.hasReturn){retCheck=util.template("let-scoping-return",{RETURN:ret})}if(has.hasBreak||has.hasContinue){var label=forParent.label=forParent.label||this.file.generateUidIdentifier("loop",this.scope);if(has.hasBreak){cases.push(t.switchCase(t.literal("break"),[t.breakStatement(label)]))}if(has.hasContinue){cases.push(t.switchCase(t.literal("continue"),[t.continueStatement(label)]))}if(has.hasReturn){cases.push(t.switchCase(null,[retCheck]))}if(cases.length===1){var single=cases[0];body.push(t.ifStatement(t.binaryExpression("===",ret,single.test),single.consequent[0]))}else{body.push(t.switchStatement(ret,cases))}}else{if(has.hasReturn)body.push(retCheck)}}},{"../../traverse":68,"../../types":72,"../../util":74,lodash:105}],55:[function(require,module,exports){var _=require("lodash");exports.ImportDeclaration=function(node,parent,file){var nodes=[];if(node.specifiers.length){_.each(node.specifiers,function(specifier){file.moduleFormatter.importSpecifier(specifier,node,nodes,parent)})}else{file.moduleFormatter.import(node,nodes,parent)}return nodes};exports.ExportDeclaration=function(node,parent,file){var nodes=[];if(node.declaration){file.moduleFormatter.export(node,nodes,parent)}else{_.each(node.specifiers,function(specifier){file.moduleFormatter.exportSpecifier(specifier,node,nodes,parent)})}return nodes}},{lodash:105}],56:[function(require,module,exports){exports.Property=function(node){if(node.shorthand)node.shorthand=false}},{}],57:[function(require,module,exports){var t=require("../../types");exports.Function=function(node,parent,file){if(!node.rest)return;var rest=node.rest;delete node.rest;t.ensureBlock(node);var call=t.callExpression(file.addDeclaration("arguments-to-array"),[t.identifier("arguments")]);if(node.params.length){call=t.callExpression(t.memberExpression(call,t.identifier("slice")),[t.literal(node.params.length)])}call._ignoreAliasFunctions=true;node.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(rest,call)]))}},{"../../types":72}],58:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var getSpreadLiteral=function(spread,file){return file.toArray(spread.argument)};var hasSpread=function(nodes){var has=false;_.each(nodes,function(node){if(t.isSpreadElement(node)){has=true;return false}});return has};var build=function(props,file){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};_.each(props,function(prop){if(t.isSpreadElement(prop)){push();nodes.push(getSpreadLiteral(prop,file))}else{_props.push(prop)}});push();return nodes};exports.ArrayExpression=function(node,parent,file){var elements=node.elements;if(!hasSpread(elements))return;var nodes=build(elements,file);var first=nodes.shift();if(!t.isArrayExpression(first)){nodes.unshift(first);first=t.arrayExpression([])}return t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)};exports.CallExpression=function(node,parent,file){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.literal(null);node.arguments=[];var nodes=build(args,file);var first=nodes.shift();if(nodes.length){node.arguments.push(t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes))}else{node.arguments.push(first)}var callee=node.callee;if(t.isMemberExpression(callee)){contextLiteral=callee.object;if(callee.computed){callee.object=t.memberExpression(callee.object,callee.property,true);callee.property=t.identifier("apply");callee.computed=false}else{callee.property=t.memberExpression(callee.property,t.identifier("apply"))}}else{node.callee=t.memberExpression(node.callee,t.identifier("apply"))}node.arguments.unshift(contextLiteral)};exports.NewExpression=function(node,parent,file){var args=node.arguments;if(!hasSpread(args))return;var nodes=build(args,file);var first=nodes.shift();if(nodes.length){args=t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)}else{args=first}return t.callExpression(file.addDeclaration("apply-constructor"),[node.callee,args])}},{"../../types":72,lodash:105}],59:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildBinaryExpression=function(left,right){return t.binaryExpression("+",left,right)};exports.TaggedTemplateExpression=function(node,parent,file){var args=[];var quasi=node.quasi;var strings=[];var raw=[];_.each(quasi.quasis,function(elem){strings.push(t.literal(elem.value.cooked));raw.push(t.literal(elem.value.raw))});args.push(t.callExpression(file.addDeclaration("tagged-template-literal"),[t.arrayExpression(strings),t.arrayExpression(raw)]));args=args.concat(quasi.expressions);return t.callExpression(node.tag,args)};exports.TemplateLiteral=function(node){var nodes=[];_.each(node.quasis,function(elem){nodes.push(t.literal(elem.value.raw));var expr=node.expressions.shift();if(expr){if(t.isBinary(expr))expr=t.parenthesizedExpression(expr);nodes.push(expr)}});if(nodes.length>1){var last=_.last(nodes);if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());_.each(nodes,function(node){root=buildBinaryExpression(root,node)});return root}else{return nodes[0]}}},{"../../types":72,lodash:105}],60:[function(require,module,exports){var rewritePattern=require("regexpu/rewrite-pattern");var _=require("lodash");exports.Literal=function(node){var regex=node.regex;if(!regex)return;var flags=regex.flags.split("");if(!_.contains(regex.flags,"u"))return;_.pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{lodash:105,"regexpu/rewrite-pattern":112}],61:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var container=function(parent,call,ret){if(t.isExpressionStatement(parent)){return call}else{var exprs=[];if(t.isSequenceExpression(call)){exprs=call.expressions}else{exprs.push(call)}exprs.push(ret);return t.sequenceExpression(exprs)}};exports.AssignmentExpression=function(node,parent,file,scope){var left=node.left;if(!t.isVirtualPropertyExpression(left))return;var value=node.right;var temp;if(!t.isExpressionStatement(parent)){if(t.isDynamic(value)){var tempName=file.generateUid("temp");temp=value=t.identifier(tempName);scope.push(tempName,temp)}}var call=util.template("abstract-expression-set",{PROPERTY:left.property,OBJECT:left.object,VALUE:value});if(temp){call=t.sequenceExpression([t.assignmentExpression("=",temp,node.right),call])}return container(parent,call,value)};exports.UnaryExpression=function(node,parent){var arg=node.argument;if(!t.isVirtualPropertyExpression(arg))return;if(node.operator!=="delete")return;var call=util.template("abstract-expression-delete",{PROPERTY:arg.property,OBJECT:arg.object});return container(parent,call,t.literal(true))};exports.CallExpression=function(node,parent,file,scope){var callee=node.callee;if(!t.isVirtualPropertyExpression(callee))return;var temp;if(t.isDynamic(callee.object)){var tempName=file.generateUid("temp");temp=t.identifier(tempName);scope.push(tempName,temp)}var call=util.template("abstract-expression-call",{PROPERTY:callee.property,OBJECT:temp||callee.object});call.arguments=call.arguments.concat(node.arguments);if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,callee.object),call])}else{return call}};exports.VirtualPropertyExpression=function(node){return util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object})}},{"../../types":72,"../../util":74}],62:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");var single=function(node,file){var block=node.blocks[0];var templateName="array-expression-comprehension-map";if(node.filter)templateName="array-expression-comprehension-filter";var result=util.template(templateName,{STATEMENT:node.body,FILTER:node.filter,ARRAY:file.toArray(block.right),KEY:block.left});_.each([result.callee.object,result],function(call){if(t.isCallExpression(call)){call.arguments[0]._aliasFunction=true}});return result};var multiple=function(node,file){var uid=file.generateUidIdentifier("arr");var container=util.template("array-comprehension-container",{KEY:uid});container.callee.expression._aliasFunction=true;var block=container.callee.expression.body;var body=block.body;var returnStatement=body.pop();body.push(exports._build(node,function(){return util.template("array-push",{STATEMENT:node.body,KEY:uid},true)}));body.push(returnStatement);return container};exports._build=function(node,buildBody){var self=node.blocks.shift();if(!self)return;var child=exports._build(node,buildBody);if(!child){child=buildBody();if(node.filter){child=t.ifStatement(node.filter,t.blockStatement([child]))}}return t.forOfStatement(t.variableDeclaration("var",[t.variableDeclarator(self.left)]),self.right,t.blockStatement([child]))};exports.ComprehensionExpression=function(node,parent,file){if(node.generator)return;if(node.blocks.length===1){return single(node,file)}else{return multiple(node,file)}}},{"../../types":72,"../../util":74,lodash:105}],63:[function(require,module,exports){var t=require("../../types");var pow=t.memberExpression(t.identifier("Math"),t.identifier("pow"));exports.AssignmentExpression=function(node){if(node.operator!=="**=")return;node.operator="=";node.right=t.callExpression(pow,[node.left,node.right])};exports.BinaryExpression=function(node){if(node.operator!=="**")return;return t.callExpression(pow,[node.left,node.right])}},{"../../types":72}],64:[function(require,module,exports){var arrayComprehension=require("./es7-array-comprehension");var t=require("../../types");exports.ComprehensionExpression=function(node){if(!node.generator)return;var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);body.push(arrayComprehension._build(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])}},{"../../types":72,"./es7-array-comprehension":62}],65:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ObjectExpression=function(node){var hasSpread=false;_.each(node.properties,function(prop){if(t.isSpreadProperty(prop)){hasSpread=true;return false}});if(!hasSpread)return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};_.each(node.properties,function(prop){if(t.isSpreadProperty(prop)){push();args.push(prop.argument)}else{props.push(prop)}});push();if(!t.isObjectExpression(args[0])){args.unshift(t.objectExpression([]))}return t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("assign")),args)}},{"../../types":72,lodash:105}],66:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");var _=require("lodash");exports.XJSIdentifier=function(node){if(esutils.keyword.isIdentifierName(node.name)){node.type="Identifier"}else{return t.literal(node.name)}};exports.XJSNamespacedName=function(node,parent,file){throw file.errorWithNode(node,"Namespace tags are not supported. ReactJSX is not XML.")};exports.XJSMemberExpression={exit:function(node){node.computed=t.isLiteral(node.property);node.type="MemberExpression"}};exports.XJSExpressionContainer=function(node){return node.expression};exports.XJSAttribute={exit:function(node){var value=node.value||t.literal(true);return t.property("init",node.name,value)}};exports.XJSOpeningElement={exit:function(node){var tagExpr=node.name;var args=[];var tagName;if(t.isIdentifier(tagExpr)){tagName=tagExpr.name}else if(t.isLiteral(tagExpr)){tagName=tagExpr.value}if(tagName&&(/[a-z]/.exec(tagName[0])||_.contains(tagName,"-"))){args.push(t.literal(tagName))}else{args.push(tagExpr)}var props=node.attributes;if(props.length){var _props=[];var objs=[];var pushProps=function(){if(!_props.length)return;objs.push(t.objectExpression(_props));_props=[]};while(props.length){var prop=props.shift();if(t.isXJSSpreadAttribute(prop)){pushProps();objs.push(prop.argument)}else{_props.push(prop)}}pushProps();if(objs.length===1){props=objs[0]}else{if(!t.isObjectExpression(objs[0])){objs.unshift(t.objectExpression([]))}props=t.callExpression(t.memberExpression(t.identifier("React"),t.identifier("__spread")),objs)}}else{props=t.literal(null)}args.push(props);tagExpr=t.memberExpression(t.identifier("React"),t.identifier("createElement"));return t.callExpression(tagExpr,args)}};exports.XJSElement={exit:function(node){var callExpr=node.openingElement;_.each(node.children,function(child){if(t.isLiteral(child)){var lines=child.value.split(/\r\n|\n|\r/);_.each(lines,function(line,i){var isFirstLine=i===0;var isLastLine=i===lines.length-1;var trimmedLine=line.replace(/\t/g," ");if(!isFirstLine){trimmedLine=trimmedLine.replace(/^[ ]+/,"")}if(!isLastLine){trimmedLine=trimmedLine.replace(/[ ]+$/,"")}if(trimmedLine){callExpr.arguments.push(t.literal(trimmedLine))}});return}else if(t.isXJSEmptyExpression(child)){return}callExpr.arguments.push(child)});return t.inherits(callExpr,node)}};var addDisplayName=function(id,call){if(!call||!t.isCallExpression(call))return;var callee=call.callee;if(!t.isMemberExpression(callee))return;var obj=callee.object;if(!t.isIdentifier(obj,{name:"React"}))return;var prop=callee.property;if(!t.isIdentifier(prop,{name:"createClass"}))return;var args=call.arguments;if(args.length!==1)return;var first=args[0];if(!t.isObjectExpression(first))return;var props=first.properties;var safe=true;_.each(props,function(prop){if(t.isIdentifier(prop.key,{name:"displayName"})){return safe=false}});if(safe){props.unshift(t.property("init",t.identifier("displayName"),t.literal(id)))}};exports.AssignmentExpression=exports.Property=exports.VariableDeclarator=function(node){var left,right;if(t.isAssignmentExpression(node)){left=node.left;right=node.right}else if(t.isProperty(node)){left=node.key;right=node.value}else if(t.isVariableDeclarator(node)){left=node.id;right=node.init}if(t.isMemberExpression(left)){left=left.property}if(t.isIdentifier(left)){addDisplayName(left.name,right)}}},{"../../types":72,esutils:104,lodash:105}],67:[function(require,module,exports){var t=require("../../types");module.exports=function(ast){var body=ast.program.body;var first=body[0];var noStrict=!first||!t.isExpressionStatement(first)||!t.isLiteral(first.expression)||first.expression.value!=="use strict";if(noStrict){body.unshift(t.expressionStatement(t.literal("use strict")))}}},{"../../types":72}],68:[function(require,module,exports){module.exports=traverse;var Scope=require("./scope");var t=require("../types");var _=require("lodash");function traverse(parent,callbacks,opts){if(!parent)return;if(_.isArray(parent)){_.each(parent,function(node){traverse(node,callbacks,opts)});return}var keys=t.VISITOR_KEYS[parent.type];if(!keys)return;opts=opts||{};if(_.isArray(opts))opts={blacklist:opts};var blacklistTypes=opts.blacklist||[];if(_.isFunction(callbacks))callbacks={enter:callbacks};for(var i in keys){var key=keys[i];var nodes=parent[key];if(!nodes)continue;var updated=false;var handle=function(obj,key){var node=obj[key];if(!node)return;if(blacklistTypes.indexOf(node.type)>-1)return;var maybeReplace=function(result){if(result===false)return;if(result!=null){updated=true;node=obj[key]=result}};var opts2={scope:opts.scope,blacklist:opts.blacklist};if(t.isScope(node))opts2.scope=new Scope(node,opts.scope);if(callbacks.enter){var result=callbacks.enter(node,parent,opts2.scope);maybeReplace(result);if(result===false)return}traverse(node,callbacks,opts2);if(callbacks.exit){maybeReplace(callbacks.exit(node,parent,opts2.scope))}};if(_.isArray(nodes)){for(i in nodes){handle(nodes,i)}if(updated)parent[key]=_.flatten(parent[key])}else{handle(parent,key)}}}traverse.removeProperties=function(tree){var clear=function(node){delete node._scopeReferences;delete node._declarations;delete node.extendedRange;delete node._parent;delete node._scope;delete node.tokens;delete node.range;delete node.start;delete node.end;delete node.loc;delete node.raw;clearComments(node.trailingComments);clearComments(node.leadingComments)};var clearComments=function(comments){_.each(comments,clear)};clear(tree);traverse(tree,clear);return tree};traverse.hasType=function(tree,type,blacklistTypes){blacklistTypes=[].concat(blacklistTypes||[]);var has=false;if(_.contains(blacklistTypes,tree.type))return false;if(tree.type===type)return true;traverse(tree,function(node){if(node.type===type){has=true;return false}},{blacklist:blacklistTypes});return has}},{"../types":72,"./scope":69,lodash:105}],69:[function(require,module,exports){module.exports=Scope;var traverse=require("./index");var t=require("../types");var _=require("lodash");var FOR_KEYS=["left","init"];function Scope(block,parent){this.parent=parent;this.block=block;this.references=this.getReferences()}Scope.add=function(node,references){if(!node)return;_.merge(references,t.getIds(node,true))};Scope.prototype.getReferences=function(){var block=this.block;if(block._scopeReferences)return block._scopeReferences;var references=block._scopeReferences={};var add=function(node){Scope.add(node,references)};if(t.isFor(block)){_.each(FOR_KEYS,function(key){var node=block[key];if(t.isLet(node))add(node)});block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){_.each(block.body,function(node){if(t.isLet(node))add(node)})}if(t.isCatchClause(block)){add(block.param)}if(t.isProgram(block)||t.isFunction(block)){traverse(block,function(node,parent,scope){if(t.isFor(node)){_.each(FOR_KEYS,function(key){var declar=node[key];if(t.isVar(declar))add(declar)})}if(t.isFunction(node))return false;if(t.isIdentifier(node)&&t.isReferenced(node,parent)&&!scope.has(node.name)){add(node)}if(t.isDeclaration(node)&&!t.isLet(node)){add(node)}},{scope:this})}if(t.isFunction(block)){add(block.rest);_.each(block.params,function(param){add(param)})}return references};Scope.prototype.push=function(name,id,init){var block=this.block;if(t.isFor(block)||t.isCatchClause(block)||t.isFunction(block)){t.ensureBlock(block);block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){block._declarations=block._declarations||{};block._declarations[name]={id:id,init:init}}else{throw new TypeError("cannot add a declaration here in node type "+block.type)}};Scope.prototype.add=function(node){Scope.add(node,this.references)};Scope.prototype.get=function(id){return id&&(this.getOwn(id)||this.parentGet(id))};Scope.prototype.getOwn=function(id){return _.has(this.references,id)&&this.references[id]};Scope.prototype.parentGet=function(id){return this.parent&&this.parent.get(id)};Scope.prototype.has=function(id){return id&&(this.hasOwn(id)||this.parentHas(id))};Scope.prototype.hasOwn=function(id){return!!this.getOwn(id)};Scope.prototype.parentHas=function(id){return this.parent&&this.parent.has(id)}},{"../types":72,"./index":68,lodash:105}],70:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary"],BinaryExpression:["Binary"],UnaryExpression:["UnaryLike"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class"],ForOfStatement:["Statement","For","Scope"],ForInStatement:["Statement","For","Scope"],ForStatement:["Statement","For","Scope"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],Property:["UserWhitespacable"],XJSElement:["UserWhitespacable"]}},{}],71:[function(require,module,exports){module.exports={ArrayExpression:["elements"],AssignmentExpression:["operator","left","right"],BinaryExpression:["operator","left","right"],BlockStatement:["body"],CallExpression:["callee","arguments"],ConditionalExpression:["test","consequent","alternate"],ExpressionStatement:["expression"],File:["program","comments","tokens"],FunctionExpression:["id","params","body","generator"],Identifier:["name"],IfStatement:["test","consequent","alternate"],Literal:["value"],MemberExpression:["object","property","computed"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ParenthesizedExpression:["expression"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],YieldExpression:["argument","delegate"]}},{}],72:[function(require,module,exports){var _=require("lodash");var t=exports;var addAssert=function(type,is){t["assert"+type]=function(node,opts){opts=opts||{};if(!is(node,opts)){throw new Error("Expected type "+JSON.stringify(type)+" with option "+JSON.stringify(opts))}}};t.VISITOR_KEYS=require("./visitor-keys");_.each(t.VISITOR_KEYS,function(keys,type){var is=t["is"+type]=function(node,opts){return node&&node.type===type&&t.shallowEqual(node,opts)};addAssert(type,is)});t.BUILDER_KEYS=_.defaults(require("./builder-keys"),t.VISITOR_KEYS);_.each(t.BUILDER_KEYS,function(keys,type){t[type[0].toLowerCase()+type.slice(1)]=function(){var args=arguments;var node={type:type};_.each(keys,function(key,i){node[key]=args[i]});return node}});t.ALIAS_KEYS=require("./alias-keys");var _aliases={};_.each(t.ALIAS_KEYS,function(aliases,type){_.each(aliases,function(alias){var types=_aliases[alias]=_aliases[alias]||[];types.push(type)})});_.each(_aliases,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;var is=t["is"+type]=function(node,opts){return node&&_.contains(types,node.type)&&t.shallowEqual(node,opts)};addAssert(type,is)});t.isExpression=function(node){return!t.isStatement(node)};addAssert("Expression",t.isExpression);t.shallowEqual=function(actual,expected){var same=true;if(expected){_.each(expected,function(val,key){if(actual[key]!==val){return same=false}})}return same};t.isDynamic=function(node){if(t.isIdentifier(node)||t.isLiteral(node)||t.isThisExpression(node)){return false}else if(t.isMemberExpression(node)){return t.isDynamic(node.object)||t.isDynamic(node.property)}else{return true}};t.isReferenced=function(node,parent){if(t.isProperty(parent)&&parent.key===node)return false;if(t.isVariableDeclarator(parent)&&parent.id===node)return false;var isMemberExpression=t.isMemberExpression(parent);var isComputedProperty=isMemberExpression&&parent.property===node&&parent.computed;var isObject=isMemberExpression&&parent.object===node;if(!isMemberExpression||isComputedProperty||isObject)return true;return false};t.toIdentifier=function(name){if(t.isIdentifier(name))return name.name;name=name.replace(/[^a-zA-Z0-9]/g,"-");name=name.replace(/^[-0-9]+/,"");name=name.replace(/[-_\s]+(.)?/g,function(match,c){return c?c.toUpperCase():""});return name};t.ensureBlock=function(node){node.body=t.toBlock(node.body,node)};t.toStatement=function(node,ignore){if(t.isStatement(node)){return node}var mustHaveId=false;var newType;if(t.isClass(node)){mustHaveId=true;newType="ClassDeclaration"}else if(t.isFunction(node)){mustHaveId=true;newType="FunctionDeclaration"}if(mustHaveId&&!node.id){newType=false}if(!newType){if(ignore){return false}else{throw new Error("cannot turn "+node.type+" to a statement")}}node.type=newType;return node};t.toBlock=function(node,parent){if(t.isBlockStatement(node)){return node}if(!_.isArray(node)){if(!t.isStatement(node)){if(t.isFunction(parent)){node=t.returnStatement(node)}else{node=t.expressionStatement(node)}}node=[node]}return t.blockStatement(node)};t.getIds=function(node,map,ignoreTypes){ignoreTypes=ignoreTypes||[];var search=[].concat(node);var ids={};while(search.length){var id=search.shift();if(!id)continue;if(_.contains(ignoreTypes,id.type))continue;var nodeKey=t.getIds.nodes[id.type];var arrKey=t.getIds.arrays[id.type];if(t.isIdentifier(id)){ids[id.name]=id}else if(nodeKey){if(id[nodeKey])search.push(id[nodeKey])}else if(arrKey){search=search.concat(id[arrKey]||[])}}if(!map)ids=_.keys(ids);return ids};t.getIds.nodes={AssignmentExpression:"left",ImportSpecifier:"id",ExportSpecifier:"id",VariableDeclarator:"id",FunctionDeclaration:"id",ClassDeclaration:"id",ParenthesizedExpression:"expression",MemeberExpression:"object",SpreadElement:"argument",Property:"value"};t.getIds.arrays={ExportDeclaration:"specifiers",ImportDeclaration:"specifiers",VariableDeclaration:"declarations",ArrayPattern:"elements",ObjectPattern:"properties"};t.isLet=function(node){return t.isVariableDeclaration(node)&&(node.kind!=="var"||node._let)};t.isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!node._let};t.removeComments=function(child){delete child.leadingComments;delete child.trailingComments;return child};t.inheritsComments=function(child,parent){child.leadingComments=_.compact([].concat(child.leadingComments,parent.leadingComments));child.trailingComments=_.compact([].concat(child.trailingComments,parent.trailingComments));return child};t.removeComments=function(node){delete node.leadingComments;delete node.trailingComments};t.inherits=function(child,parent){child.loc=parent.loc;child.end=parent.end; child.range=parent.range;child.start=parent.start;t.inheritsComments(child,parent);return child};t.getSpecifierName=function(specifier){return specifier.name||specifier.id}},{"./alias-keys":70,"./builder-keys":71,"./visitor-keys":73,lodash:105}],73:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],ParenthesizedExpression:["expression"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],XJSAttribute:["name","value"],XJSClosingElement:["name"],XJSElement:["openingElement","closingElement","children"],XJSEmptyExpression:[],XJSExpressionContainer:["expression"],XJSIdentifier:[],XJSMemberExpression:["object","property"],XJSNamespacedName:["namespace","name"],XJSOpeningElement:["name","attributes"],XJSSpreadAttribute:["argument"],YieldExpression:["argument"]}},{}],74:[function(require,module,exports){(function(Buffer,__dirname){require("./patch");var estraverse=require("estraverse");var traverse=require("./traverse");var acorn=require("acorn-6to5");var path=require("path");var util=require("util");var fs=require("fs");var t=require("./types");var _=require("lodash");exports.inherits=util.inherits;exports.canCompile=function(filename,altExts){var exts=altExts||[".js",".jsx",".es6"];var ext=path.extname(filename);return _.contains(exts,ext)};exports.isInteger=function(i){return _.isNumber(i)&&i%1===0};exports.resolve=function(loc){try{return require.resolve(loc)}catch(err){return null}};exports.trimRight=function(str){return str.replace(/[\n\s]+$/g,"")};exports.list=function(val){return val?val.split(","):[]};exports.regexify=function(val){if(!val)return new RegExp(/.^/);if(_.isArray(val))val=val.join("|");if(_.isString(val))return new RegExp(val);if(_.isRegExp(val))return val;throw new TypeError("illegal type for regexify")};exports.arrayify=function(val){if(!val)return[];if(_.isString(val))return exports.list(val);if(_.isArray(val))return val;throw new TypeError("illegal type for arrayify")};exports.getUid=function(parent,file){var node;if(t.isAssignmentExpression(parent)){node=parent.left}else if(t.isVariableDeclarator(parent)){node=parent.id}var id="ref";if(t.isIdentifier(node))id=node.name;return file.generateUidIdentifier(id)};exports.isAbsolute=function(loc){if(!loc)return false;if(loc[0]==="/")return true;if(loc[1]===":"&&loc[2]==="\\")return true;return false};exports.sourceMapToComment=function(map){var json=JSON.stringify(map);var base64=new Buffer(json).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+base64};exports.pushMutatorMap=function(mutatorMap,key,kind,method){var alias;if(t.isIdentifier(key)){alias=key.name;if(method.computed)alias="computed:"+alias}else if(t.isLiteral(key)){alias=String(key.value)}else{alias=JSON.stringify(traverse.removeProperties(_.cloneDeep(key)))}var map;if(_.has(mutatorMap,alias)){map=mutatorMap[alias]}else{map={}}mutatorMap[alias]=map;map._key=key;if(method.computed){map._computed=true}map[kind]=method};exports.buildDefineProperties=function(mutatorMap){var objExpr=t.objectExpression([]);_.each(mutatorMap,function(map){var mapNode=t.objectExpression([]);var propNode=t.property("init",map._key,mapNode,map._computed);_.each(map,function(node,key){if(key[0]==="_")return;node=_.clone(node);var inheritNode=node;if(t.isMethodDefinition(node))node=node.value;var prop=t.property("init",t.identifier(key),node);t.inheritsComments(prop,inheritNode);t.removeComments(inheritNode);mapNode.properties.push(prop)});objExpr.properties.push(propNode)});return objExpr};exports.template=function(name,nodes,keepExpression){var template=exports.templates[name];if(!template)throw new ReferenceError("unknown template "+name);if(nodes===true){keepExpression=true;nodes=null}template=_.cloneDeep(template);if(!_.isEmpty(nodes)){traverse(template,function(node){if(t.isIdentifier(node)&&_.has(nodes,node.name)){var newNode=nodes[node.name];if(_.isString(newNode)){node.name=newNode}else{return newNode}}})}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(node)){node=node.expression;if(t.isParenthesizedExpression(node))node=node.expression}return node};exports.codeFrame=function(lines,lineNumber,colNumber){colNumber=Math.max(colNumber,0);lines=lines.split("\n");var start=Math.max(lineNumber-3,0);var end=Math.min(lines.length,lineNumber+3);var width=(end+"").length;if(!lineNumber&&!colNumber){start=0;end=lines.length}return"\n"+lines.slice(start,end).map(function(line,i){var curr=i+start+1;var gutter=curr===lineNumber?"> ":" ";var sep=curr+exports.repeat(width+1);gutter+=sep+"| ";var str=gutter+line;if(colNumber&&curr===lineNumber){str+="\n";str+=exports.repeat(gutter.length-2);str+="|"+exports.repeat(colNumber)+"^"}return str}).join("\n")};exports.repeat=function(width,cha){cha=cha||" ";return new Array(width+1).join(cha)};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowReturnOutsideFunction:true,preserveParens:true,ecmaVersion:opts.experimental?7:6,strictMode:true,onComment:comments,locations:true,onToken:tokens,ranges:true});estraverse.attachComments(ast,comments,tokens);ast=t.file(ast,comments,tokens);traverse(ast,function(node,parent){node._parent=parent});if(callback){return callback(ast)}else{return ast}}catch(err){if(!err._6to5){err._6to5=true;var message=opts.filename+": "+err.message;var loc=err.loc;if(loc){var frame=exports.codeFrame(code,loc.line,loc.column);message+=frame}if(err.stack)err.stack=err.stack.replace(err.message,message);err.message=message}throw err}};exports.parseTemplate=function(loc,code){var ast=exports.parse({filename:loc},code).program;return traverse.removeProperties(ast)};var loadTemplates=function(){var templates={};var templatesLoc=__dirname+"/templates";if(!fs.existsSync(templatesLoc)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://githut.com/6to5/6to5/issues")}_.each(fs.readdirSync(templatesLoc),function(name){if(name[0]===".")return;var key=path.basename(name,path.extname(name));var loc=templatesLoc+"/"+name;var code=fs.readFileSync(loc,"utf8");templates[key]=exports.parseTemplate(loc,code)});return templates};try{exports.templates=require("../../templates.json")}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err;exports.templates=loadTemplates()}}).call(this,require("buffer").Buffer,"/lib/6to5")},{"../../templates.json":123,"./patch":22,"./traverse":68,"./types":72,"acorn-6to5":1,buffer:91,estraverse:100,fs:89,lodash:105,path:96,util:99}],75:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var def=Type.def;var or=Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isNumber=builtin.number;var isBoolean=builtin.boolean;var isRegExp=builtin.RegExp;var shared=require("../lib/shared");var defaults=shared.defaults;var geq=shared.geq;def("Node").field("type",isString).field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("SourceLocation").build("start","end","source").field("start",def("Position")).field("end",def("Position")).field("source",or(isString,null),defaults["null"]);def("Position").build("line","column").field("line",geq(1)).field("column",geq(0));def("Program").bases("Node").build("body").field("body",[def("Statement")]);def("Function").bases("Node").field("id",or(def("Identifier"),null),defaults["null"]).field("params",[def("Pattern")]).field("body",or(def("BlockStatement"),def("Expression")));def("Statement").bases("Node");def("EmptyStatement").bases("Statement").build();def("BlockStatement").bases("Statement").build("body").field("body",[def("Statement")]);def("ExpressionStatement").bases("Statement").build("expression").field("expression",def("Expression"));def("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Statement")).field("alternate",or(def("Statement"),null),defaults["null"]);def("LabeledStatement").bases("Statement").build("label","body").field("label",def("Identifier")).field("body",def("Statement"));def("BreakStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("ContinueStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("WithStatement").bases("Statement").build("object","body").field("object",def("Expression")).field("body",def("Statement"));def("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",def("Expression")).field("cases",[def("SwitchCase")]).field("lexical",isBoolean,defaults["false"]);def("ReturnStatement").bases("Statement").build("argument").field("argument",or(def("Expression"),null));def("ThrowStatement").bases("Statement").build("argument").field("argument",def("Expression"));def("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",def("BlockStatement")).field("handler",or(def("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[def("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[def("CatchClause")],defaults.emptyArray).field("finalizer",or(def("BlockStatement"),null),defaults["null"]);def("CatchClause").bases("Node").build("param","guard","body").field("param",def("Pattern")).field("guard",or(def("Expression"),null),defaults["null"]).field("body",def("BlockStatement"));def("WhileStatement").bases("Statement").build("test","body").field("test",def("Expression")).field("body",def("Statement"));def("DoWhileStatement").bases("Statement").build("body","test").field("body",def("Statement")).field("test",def("Expression"));def("ForStatement").bases("Statement").build("init","test","update","body").field("init",or(def("VariableDeclaration"),def("Expression"),null)).field("test",or(def("Expression"),null)).field("update",or(def("Expression"),null)).field("body",def("Statement"));def("ForInStatement").bases("Statement").build("left","right","body","each").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement")).field("each",isBoolean);def("DebuggerStatement").bases("Statement").build();def("Declaration").bases("Statement");def("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",def("Identifier"));def("FunctionExpression").bases("Function","Expression").build("id","params","body");def("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",or("var","let","const")).field("declarations",[or(def("VariableDeclarator"),def("Identifier"))]);def("VariableDeclarator").bases("Node").build("id","init").field("id",def("Pattern")).field("init",or(def("Expression"),null));def("Expression").bases("Node","Pattern");def("ThisExpression").bases("Expression").build();def("ArrayExpression").bases("Expression").build("elements").field("elements",[or(def("Expression"),null)]);def("ObjectExpression").bases("Expression").build("properties").field("properties",[def("Property")]);def("Property").bases("Node").build("kind","key","value").field("kind",or("init","get","set")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Expression"));def("SequenceExpression").bases("Expression").build("expressions").field("expressions",[def("Expression")]);var UnaryOperator=or("-","+","!","~","typeof","void","delete");def("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",UnaryOperator).field("argument",def("Expression")).field("prefix",isBoolean,defaults["true"]);var BinaryOperator=or("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");def("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",BinaryOperator).field("left",def("Expression")).field("right",def("Expression"));var AssignmentOperator=or("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");def("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",AssignmentOperator).field("left",def("Pattern")).field("right",def("Expression"));var UpdateOperator=or("++","--");def("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",UpdateOperator).field("argument",def("Expression")).field("prefix",isBoolean);var LogicalOperator=or("||","&&");def("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",LogicalOperator).field("left",def("Expression")).field("right",def("Expression"));def("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Expression")).field("alternate",def("Expression"));def("NewExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("CallExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("MemberExpression").bases("Expression").build("object","property","computed").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("Pattern").bases("Node");def("ObjectPattern").bases("Pattern").build("properties").field("properties",[def("PropertyPattern")]);def("PropertyPattern").bases("Pattern").build("key","pattern").field("key",or(def("Literal"),def("Identifier"))).field("pattern",def("Pattern"));def("ArrayPattern").bases("Pattern").build("elements").field("elements",[or(def("Pattern"),null)]);def("SwitchCase").bases("Node").build("test","consequent").field("test",or(def("Expression"),null)).field("consequent",[def("Statement")]);def("Identifier").bases("Node","Expression","Pattern").build("name").field("name",isString);def("Literal").bases("Node","Expression").build("value").field("value",or(isString,isBoolean,null,isNumber,isRegExp))},{"../lib/shared":86,"../lib/types":87}],76:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;def("XMLDefaultDeclaration").bases("Declaration").field("namespace",def("Expression"));def("XMLAnyName").bases("Expression");def("XMLQualifiedIdentifier").bases("Expression").field("left",or(def("Identifier"),def("XMLAnyName"))).field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLAttributeSelector").bases("Expression").field("attribute",def("Expression"));def("XMLFilterExpression").bases("Expression").field("left",def("Expression")).field("right",def("Expression"));def("XMLElement").bases("XML","Expression").field("contents",[def("XML")]);def("XMLList").bases("XML","Expression").field("contents",[def("XML")]);def("XML").bases("Node");def("XMLEscape").bases("XML").field("expression",def("Expression"));def("XMLText").bases("XML").field("text",isString);def("XMLStartTag").bases("XML").field("contents",[def("XML")]);def("XMLEndTag").bases("XML").field("contents",[def("XML")]);def("XMLPointTag").bases("XML").field("contents",[def("XML")]);def("XMLName").bases("XML").field("contents",or(isString,[def("XML")]));def("XMLAttribute").bases("XML").field("value",isString);def("XMLCdata").bases("XML").field("contents",isString);def("XMLComment").bases("XML").field("contents",isString);def("XMLProcessingInstruction").bases("XML").field("target",isString).field("contents",or(isString,null))},{"../lib/types":87,"./core":75}],77:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var isObject=builtin.object;var isString=builtin.string;var defaults=require("../lib/shared").defaults;def("Function").field("generator",isBoolean,defaults["false"]).field("expression",isBoolean,defaults["false"]).field("defaults",[or(def("Expression"),null)],defaults.emptyArray).field("rest",or(def("Identifier"),null),defaults["null"]);def("FunctionDeclaration").build("id","params","body","generator","expression");def("FunctionExpression").build("id","params","body","generator","expression");def("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,defaults["null"]).field("generator",false);def("YieldExpression").bases("Expression").build("argument","delegate").field("argument",or(def("Expression"),null)).field("delegate",isBoolean,defaults["false"]);def("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionBlock").bases("Node").build("left","right","each").field("left",def("Pattern")).field("right",def("Expression")).field("each",isBoolean);def("ModuleSpecifier").bases("Literal").build("value").field("value",isString);def("Property").field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",or("init","get","set","")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Function"));def("SpreadElement").bases("Node").build("argument").field("argument",def("Expression"));def("ArrayExpression").field("elements",[or(def("Expression"),def("SpreadElement"),null)]);def("NewExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("CallExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("SpreadElementPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));var ClassBodyElement=or(def("MethodDefinition"),def("VariableDeclarator"),def("ClassPropertyDefinition"),def("ClassProperty"));def("ClassProperty").bases("Declaration").build("id").field("id",def("Identifier"));def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",ClassBodyElement);def("ClassBody").bases("Declaration").build("body").field("body",[ClassBodyElement]);def("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",def("Identifier")).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("ClassExpression").bases("Expression").build("id","body","superClass").field("id",or(def("Identifier"),null),defaults["null"]).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("Specifier").bases("Node");def("NamedSpecifier").bases("Specifier").field("id",def("Identifier")).field("name",or(def("Identifier"),null),defaults["null"]);def("ExportSpecifier").bases("NamedSpecifier").build("id","name");def("ExportBatchSpecifier").bases("Specifier").build();def("ImportSpecifier").bases("NamedSpecifier").build("id","name");def("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",isBoolean).field("declaration",or(def("Declaration"),def("Expression"),null)).field("specifiers",[or(def("ExportSpecifier"),def("ExportBatchSpecifier"))],defaults.emptyArray).field("source",or(def("ModuleSpecifier"),null),defaults["null"]);def("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[or(def("ImportSpecifier"),def("ImportNamespaceSpecifier"),def("ImportDefaultSpecifier"))],defaults.emptyArray).field("source",def("ModuleSpecifier"));def("TaggedTemplateExpression").bases("Expression").field("tag",def("Expression")).field("quasi",def("TemplateLiteral"));def("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[def("TemplateElement")]).field("expressions",[def("Expression")]);def("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:isString,raw:isString}).field("tail",isBoolean)},{"../lib/shared":86,"../lib/types":87,"./core":75}],78:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("Function").field("async",isBoolean,defaults["false"]);def("SpreadProperty").bases("Node").build("argument").field("argument",def("Expression"));def("ObjectExpression").field("properties",[or(def("Property"),def("SpreadProperty"))]);def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));def("ObjectPattern").field("properties",[or(def("PropertyPattern"),def("SpreadPropertyPattern"))]);def("AwaitExpression").bases("Expression").build("argument","all").field("argument",or(def("Expression"),null)).field("all",isBoolean,defaults["false"])},{"../lib/shared":86,"../lib/types":87,"./core":75}],79:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("XJSAttribute").bases("Node").build("name","value").field("name",or(def("XJSIdentifier"),def("XJSNamespacedName"))).field("value",or(def("Literal"),def("XJSExpressionContainer"),null),defaults["null"]);def("XJSIdentifier").bases("Node").build("name").field("name",isString);def("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",def("XJSIdentifier")).field("name",def("XJSIdentifier"));def("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",or(def("XJSIdentifier"),def("XJSMemberExpression"))).field("property",def("XJSIdentifier")).field("computed",isBoolean,defaults.false);var XJSElementName=or(def("XJSIdentifier"),def("XJSNamespacedName"),def("XJSMemberExpression"));def("XJSSpreadAttribute").bases("Node").build("argument").field("argument",def("Expression"));var XJSAttributes=[or(def("XJSAttribute"),def("XJSSpreadAttribute"))];def("XJSExpressionContainer").bases("Expression").build("expression").field("expression",def("Expression"));def("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",def("XJSOpeningElement")).field("closingElement",or(def("XJSClosingElement"),null),defaults["null"]).field("children",[or(def("XJSElement"),def("XJSExpressionContainer"),def("XJSText"),def("Literal"))],defaults.emptyArray).field("name",XJSElementName,function(){return this.openingElement.name}).field("selfClosing",isBoolean,function(){return this.openingElement.selfClosing}).field("attributes",XJSAttributes,function(){return this.openingElement.attributes});def("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",XJSElementName).field("attributes",XJSAttributes,defaults.emptyArray).field("selfClosing",isBoolean,defaults["false"]);def("XJSClosingElement").bases("Node").build("name").field("name",XJSElementName);def("XJSText").bases("Literal").build("value").field("value",isString);def("XJSEmptyExpression").bases("Expression").build();def("TypeAnnotatedIdentifier").bases("Pattern").build("annotation","identifier").field("annotation",def("TypeAnnotation")).field("identifier",def("Identifier"));def("TypeAnnotation").bases("Pattern").build("annotatedType","templateTypes","paramTypes","returnType","unionType","nullable").field("annotatedType",def("Identifier")).field("templateTypes",or([def("TypeAnnotation")],null)).field("paramTypes",or([def("TypeAnnotation")],null)).field("returnType",or(def("TypeAnnotation"),null)).field("unionType",or(def("TypeAnnotation"),null)).field("nullable",isBoolean);def("ObjectTypeAnnotation").bases("Pattern").build("properties","nullable").field("properties",[def("Property")]).field("nullable",isBoolean);def("VoidTypeAnnotation").bases("Pattern");def("ParametricTypeAnnotation").bases("Pattern").build("params").field("params",[def("Identifier")]);def("OptionalParameter").bases("Pattern").build("identifier").field("identifier",def("Identifier"));def("Identifier").field("annotation",or(def("TypeAnnotation"),def("VoidTypeAnnotation"),def("ObjectTypeAnnotation"),null),defaults["null"]);def("Function").field("returnType",or(def("TypeAnnotation"),def("VoidTypeAnnotation"),def("ObjectTypeAnnotation"),null),defaults["null"]).field("parametricType",or(def("ParametricTypeAnnotation"),null),defaults["null"]);def("ClassProperty").field("id",or(def("Identifier"),def("TypeAnnotatedIdentifier")));def("ClassDeclaration").field("parametricType",or(def("ParametricTypeAnnotation"),null),defaults["null"])},{"../lib/shared":86,"../lib/types":87,"./core":75}],80:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var geq=require("../lib/shared").geq;def("ForOfStatement").bases("Statement").build("left","right","body").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement"));def("LetStatement").bases("Statement").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Statement"));def("LetExpression").bases("Expression").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Expression"));def("GraphExpression").bases("Expression").build("index","expression").field("index",geq(0)).field("expression",def("Literal"));def("GraphIndexExpression").bases("Expression").build("index").field("index",geq(0))},{"../lib/shared":86,"../lib/types":87,"./core":75}],81:[function(require,module,exports){var assert=require("assert");var types=require("../main");var getFieldNames=types.getFieldNames;var getFieldValue=types.getFieldValue;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isDate=types.builtInTypes.Date;var isRegExp=types.builtInTypes.RegExp;var hasOwn=Object.prototype.hasOwnProperty;function astNodesAreEquivalent(a,b,problemPath){if(isArray.check(problemPath)){problemPath.length=0}else{problemPath=null}return areEquivalent(a,b,problemPath)}astNodesAreEquivalent.assert=function(a,b){var problemPath=[];if(!astNodesAreEquivalent(a,b,problemPath)){if(problemPath.length===0){assert.strictEqual(a,b)}else{assert.ok(false,"Nodes differ in the following path: "+problemPath.map(subscriptForProperty).join(""))}}};function subscriptForProperty(property){if(/[_$a-z][_$a-z0-9]*/i.test(property)){return"."+property}return"["+JSON.stringify(property)+"]"}function areEquivalent(a,b,problemPath){if(a===b){return true}if(isArray.check(a)){return arraysAreEquivalent(a,b,problemPath)}if(isObject.check(a)){return objectsAreEquivalent(a,b,problemPath)}if(isDate.check(a)){return isDate.check(b)&&+a===+b}if(isRegExp.check(a)){return isRegExp.check(b)&&(a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.ignoreCase===b.ignoreCase)}return a==b}function arraysAreEquivalent(a,b,problemPath){isArray.assert(a);var aLength=a.length;if(!isArray.check(b)||b.length!==aLength){if(problemPath){problemPath.push("length")}return false}for(var i=0;i<aLength;++i){if(problemPath){problemPath.push(i)}if(i in a!==i in b){return false}if(!areEquivalent(a[i],b[i],problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),i)}}return true}function objectsAreEquivalent(a,b,problemPath){isObject.assert(a);if(!isObject.check(b)){return false}if(a.type!==b.type){if(problemPath){problemPath.push("type")}return false}var aNames=getFieldNames(a);var aNameCount=aNames.length;var bNames=getFieldNames(b);var bNameCount=bNames.length;if(aNameCount===bNameCount){for(var i=0;i<aNameCount;++i){var name=aNames[i];var aChild=getFieldValue(a,name);var bChild=getFieldValue(b,name);if(problemPath){problemPath.push(name)}if(!areEquivalent(aChild,bChild,problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),name)}}return true}if(!problemPath){return false}var seenNames=Object.create(null);for(i=0;i<aNameCount;++i){seenNames[aNames[i]]=true}for(i=0;i<bNameCount;++i){name=bNames[i];if(!hasOwn.call(seenNames,name)){problemPath.push(name);return false}delete seenNames[name]}for(name in seenNames){problemPath.push(name);break}return false}module.exports=astNodesAreEquivalent},{"../main":88,assert:90}],82:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isNumber=types.builtInTypes.number;var isArray=types.builtInTypes.array;var Path=require("./path");var Scope=require("./scope");function NodePath(value,parentPath,name){assert.ok(this instanceof NodePath);Path.call(this,value,parentPath,name)}require("util").inherits(NodePath,Path);var NPp=NodePath.prototype;Object.defineProperties(NPp,{node:{get:function(){Object.defineProperty(this,"node",{configurable:true,value:this._computeNode()});return this.node}},parent:{get:function(){Object.defineProperty(this,"parent",{configurable:true,value:this._computeParent()});return this.parent}},scope:{get:function(){Object.defineProperty(this,"scope",{configurable:true,value:this._computeScope()}); return this.scope}}});NPp.replace=function(){delete this.node;delete this.parent;delete this.scope;return Path.prototype.replace.apply(this,arguments)};NPp.prune=function(){var remainingNodePath=this.parent;this.replace();return cleanUpNodesAfterPrune(remainingNodePath)};NPp._computeNode=function(){var value=this.value;if(n.Node.check(value)){return value}var pp=this.parentPath;return pp&&pp.node||null};NPp._computeParent=function(){var value=this.value;var pp=this.parentPath;if(!n.Node.check(value)){while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}if(pp){pp=pp.parentPath}}while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}return pp||null};NPp._computeScope=function(){var value=this.value;var pp=this.parentPath;var scope=pp&&pp.scope;if(n.Node.check(value)&&Scope.isEstablishedBy(value)){scope=new Scope(this,scope)}return scope||null};NPp.getValueProperty=function(name){return types.getFieldValue(this.value,name)};NPp.needsParens=function(assumeExpressionContext){var pp=this.parentPath;if(!pp){return false}var node=this.value;if(!n.Expression.check(node)){return false}if(node.type==="Identifier"){return false}while(!n.Node.check(pp.value)){pp=pp.parentPath;if(!pp){return false}}var parent=pp.value;switch(node.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return parent.type==="MemberExpression"&&this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":switch(parent.type){case"CallExpression":return this.name==="callee"&&parent.callee===node;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":var po=parent.operator;var pp=PRECEDENCE[po];var no=node.operator;var np=PRECEDENCE[no];if(pp>np){return true}if(pp===np&&this.name==="right"){assert.strictEqual(parent.right,node);return true}default:return false}case"SequenceExpression":switch(parent.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(parent.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return true;default:return false}case"Literal":return parent.type==="MemberExpression"&&isNumber.check(node.value)&&this.name==="object"&&parent.object===node;case"AssignmentExpression":case"ConditionalExpression":switch(parent.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&parent.callee===node;case"ConditionalExpression":return this.name==="test"&&parent.test===node;case"MemberExpression":return this.name==="object"&&parent.object===node;default:return false}default:if(parent.type==="NewExpression"&&this.name==="callee"&&parent.callee===node){return containsCallExpression(node)}}if(assumeExpressionContext!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function isBinary(node){return n.BinaryExpression.check(node)||n.LogicalExpression.check(node)}function isUnaryLike(node){return n.UnaryExpression.check(node)||n.SpreadElement&&n.SpreadElement.check(node)||n.SpreadProperty&&n.SpreadProperty.check(node)}var PRECEDENCE={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(tier,i){tier.forEach(function(op){PRECEDENCE[op]=i})});function containsCallExpression(node){if(n.CallExpression.check(node)){return true}if(isArray.check(node)){return node.some(containsCallExpression)}if(n.Node.check(node)){return types.someField(node,function(name,child){return containsCallExpression(child)})}return false}NPp.canBeFirstInStatement=function(){var node=this.node;return!n.FunctionExpression.check(node)&&!n.ObjectExpression.check(node)};NPp.firstInStatement=function(){return firstInStatement(this)};function firstInStatement(path){for(var node,parent;path.parent;path=path.parent){node=path.node;parent=path.parent.node;if(n.BlockStatement.check(parent)&&path.parent.name==="body"&&path.name===0){assert.strictEqual(parent.body[0],node);return true}if(n.ExpressionStatement.check(parent)&&path.name==="expression"){assert.strictEqual(parent.expression,node);return true}if(n.SequenceExpression.check(parent)&&path.parent.name==="expressions"&&path.name===0){assert.strictEqual(parent.expressions[0],node);continue}if(n.CallExpression.check(parent)&&path.name==="callee"){assert.strictEqual(parent.callee,node);continue}if(n.MemberExpression.check(parent)&&path.name==="object"){assert.strictEqual(parent.object,node);continue}if(n.ConditionalExpression.check(parent)&&path.name==="test"){assert.strictEqual(parent.test,node);continue}if(isBinary(parent)&&path.name==="left"){assert.strictEqual(parent.left,node);continue}if(n.UnaryExpression.check(parent)&&!parent.prefix&&path.name==="argument"){assert.strictEqual(parent.argument,node);continue}return false}return true}function cleanUpNodesAfterPrune(remainingNodePath){if(n.VariableDeclaration.check(remainingNodePath.node)){var declarations=remainingNodePath.get("declarations").value;if(!declarations||declarations.length===0){return remainingNodePath.prune()}}else if(n.ExpressionStatement.check(remainingNodePath.node)){if(!remainingNodePath.get("expression").value){return remainingNodePath.prune()}}else if(n.IfStatement.check(remainingNodePath.node)){cleanUpIfStatementAfterPrune(remainingNodePath)}return remainingNodePath}function cleanUpIfStatementAfterPrune(ifStatement){var testExpression=ifStatement.get("test").value;var alternate=ifStatement.get("alternate").value;var consequent=ifStatement.get("consequent").value;if(!consequent&&!alternate){var testExpressionStatement=b.expressionStatement(testExpression);ifStatement.replace(testExpressionStatement)}else if(!consequent&&alternate){var negatedTestExpression=b.unaryExpression("!",testExpression,true);if(n.UnaryExpression.check(testExpression)&&testExpression.operator==="!"){negatedTestExpression=testExpression.argument}ifStatement.get("test").replace(negatedTestExpression);ifStatement.get("consequent").replace(alternate);ifStatement.get("alternate").replace()}}module.exports=NodePath},{"./path":84,"./scope":85,"./types":87,assert:90,util:99}],83:[function(require,module,exports){var assert=require("assert");var types=require("./types");var NodePath=require("./node-path");var Node=types.namedTypes.Node;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isFunction=types.builtInTypes.function;var hasOwn=Object.prototype.hasOwnProperty;var undefined;function PathVisitor(){assert.ok(this instanceof PathVisitor);this._reusableContextStack=[];this._methodNameTable=computeMethodNameTable(this);this.Context=makeContextConstructor(this)}function computeMethodNameTable(visitor){var typeNames=Object.create(null);for(var methodName in visitor){if(/^visit[A-Z]/.test(methodName)){typeNames[methodName.slice("visit".length)]=true}}var supertypeTable=types.computeSupertypeLookupTable(typeNames);var methodNameTable=Object.create(null);var typeNames=Object.keys(supertypeTable);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];methodName="visit"+supertypeTable[typeName];if(isFunction.check(visitor[methodName])){methodNameTable[typeName]=methodName}}return methodNameTable}PathVisitor.fromMethodsObject=function fromMethodsObject(methods){if(methods instanceof PathVisitor){return methods}if(!isObject.check(methods)){return new PathVisitor}function Visitor(){assert.ok(this instanceof Visitor);PathVisitor.call(this)}var Vp=Visitor.prototype=Object.create(PVp);Vp.constructor=Visitor;extend(Vp,methods);extend(Visitor,PathVisitor);isFunction.assert(Visitor.fromMethodsObject);isFunction.assert(Visitor.visit);return new Visitor};function extend(target,source){for(var property in source){if(hasOwn.call(source,property)){target[property]=source[property]}}return target}PathVisitor.visit=function visit(node,methods){var visitor=PathVisitor.fromMethodsObject(methods);if(node instanceof NodePath){visitor.visit(node);return node.value}var rootPath=new NodePath({root:node});visitor.visit(rootPath.get("root"));return rootPath.value.root};var PVp=PathVisitor.prototype;PVp.visit=function(path){if(this instanceof this.Context){return this.visitor.visit(path)}assert.ok(path instanceof NodePath);var value=path.value;var methodName=Node.check(value)&&this._methodNameTable[value.type];if(methodName){var context=this.acquireContext(path);try{context.invokeVisitorMethod(methodName)}finally{this.releaseContext(context)}}else{visitChildren(path,this)}};function visitChildren(path,visitor){assert.ok(path instanceof NodePath);assert.ok(visitor instanceof PathVisitor);var value=path.value;if(isArray.check(value)){path.each(visitor.visit,visitor)}else if(!isObject.check(value)){}else{var childNames=types.getFieldNames(value);var childCount=childNames.length;var childPaths=[];for(var i=0;i<childCount;++i){var childName=childNames[i];if(!hasOwn.call(value,childName)){value[childName]=types.getFieldValue(value,childName)}childPaths.push(path.get(childName))}for(var i=0;i<childCount;++i){visitor.visit(childPaths[i])}}}PVp.acquireContext=function(path){if(this._reusableContextStack.length===0){return new this.Context(path)}return this._reusableContextStack.pop().reset(path)};PVp.releaseContext=function(context){assert.ok(context instanceof this.Context);this._reusableContextStack.push(context);context.currentPath=null};function makeContextConstructor(visitor){function Context(path){assert.ok(this instanceof Context);assert.ok(this instanceof PathVisitor);assert.ok(path instanceof NodePath);Object.defineProperty(this,"visitor",{value:visitor,writable:false,enumerable:true,configurable:false});this.currentPath=path;this.needToCallTraverse=true;Object.seal(this)}assert.ok(visitor instanceof PathVisitor);var Cp=Context.prototype=Object.create(visitor);Cp.constructor=Context;extend(Cp,sharedContextProtoMethods);return Context}var sharedContextProtoMethods=Object.create(null);sharedContextProtoMethods.reset=function reset(path){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);this.currentPath=path;this.needToCallTraverse=true;return this};sharedContextProtoMethods.invokeVisitorMethod=function invokeVisitorMethod(methodName){assert.ok(this instanceof this.Context);assert.ok(this.currentPath instanceof NodePath);var result=this.visitor[methodName].call(this,this.currentPath);if(result===false){this.needToCallTraverse=false}else if(result!==undefined){this.currentPath=this.currentPath.replace(result)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}assert.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+methodName)};sharedContextProtoMethods.traverse=function traverse(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;visitChildren(path,PathVisitor.fromMethodsObject(newVisitor||this.visitor))};module.exports=PathVisitor},{"./node-path":82,"./types":87,assert:90}],84:[function(require,module,exports){var assert=require("assert");var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var types=require("./types");var isArray=types.builtInTypes.array;var isNumber=types.builtInTypes.number;var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;function Path(value,parentPath,name){assert.ok(this instanceof Path);if(parentPath){assert.ok(parentPath instanceof Path)}else{parentPath=null;name=null}this.value=value;this.parentPath=parentPath;this.name=name;this.__childCache=null}var Pp=Path.prototype;function getChildCache(path){return path.__childCache||(path.__childCache=Object.create(null))}function getChildPath(path,name){var cache=getChildCache(path);var actualChildValue=path.getValueProperty(name);var childPath=cache[name];if(!hasOwn.call(cache,name)||childPath.value!==actualChildValue){childPath=cache[name]=new path.constructor(actualChildValue,path,name)}return childPath}Pp.getValueProperty=function getValueProperty(name){return this.value[name]};Pp.get=function get(name){var path=this;var names=arguments;var count=names.length;for(var i=0;i<count;++i){path=getChildPath(path,names[i])}return path};Pp.each=function each(callback,context){var childPaths=[];var len=this.value.length;var i=0;for(var i=0;i<len;++i){if(hasOwn.call(this.value,i)){childPaths[i]=this.get(i)}}context=context||this;for(i=0;i<len;++i){if(hasOwn.call(childPaths,i)){callback.call(context,childPaths[i])}}};Pp.map=function map(callback,context){var result=[];this.each(function(childPath){result.push(callback.call(this,childPath))},context);return result};Pp.filter=function filter(callback,context){var result=[];this.each(function(childPath){if(callback.call(this,childPath)){result.push(childPath)}},context);return result};function emptyMoves(){}function getMoves(path,offset,start,end){isArray.assert(path.value);if(offset===0){return emptyMoves}var length=path.value.length;if(length<1){return emptyMoves}var argc=arguments.length;if(argc===2){start=0;end=length}else if(argc===3){start=Math.max(start,0);end=length}else{start=Math.max(start,0);end=Math.min(end,length)}isNumber.assert(start);isNumber.assert(end);var moves=Object.create(null);var cache=getChildCache(path);for(var i=start;i<end;++i){if(hasOwn.call(path.value,i)){var childPath=path.get(i);assert.strictEqual(childPath.name,i);var newIndex=i+offset;childPath.name=newIndex;moves[newIndex]=childPath;delete cache[i]}}delete cache.length;return function(){for(var newIndex in moves){var childPath=moves[newIndex];assert.strictEqual(childPath.name,+newIndex);cache[newIndex]=childPath;path.value[newIndex]=childPath.value}}}Pp.shift=function shift(){var move=getMoves(this,-1);var result=this.value.shift();move();return result};Pp.unshift=function unshift(node){var move=getMoves(this,arguments.length);var result=this.value.unshift.apply(this.value,arguments);move();return result};Pp.push=function push(node){isArray.assert(this.value);delete getChildCache(this).length;return this.value.push.apply(this.value,arguments)};Pp.pop=function pop(){isArray.assert(this.value);var cache=getChildCache(this);delete cache[this.value.length-1];delete cache.length;return this.value.pop()};Pp.insertAt=function insertAt(index,node){var argc=arguments.length;var move=getMoves(this,argc-1,index);if(move===emptyMoves){return this}index=Math.max(index,0);for(var i=1;i<argc;++i){this.value[index+i-1]=arguments[i]}move();return this};Pp.insertBefore=function insertBefore(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};Pp.insertAfter=function insertAfter(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name+1];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};function repairRelationshipWithParent(path){assert.ok(path instanceof Path);var pp=path.parentPath;if(!pp){return path}var parentValue=pp.value;var parentCache=getChildCache(pp);if(parentValue[path.name]===path.value){parentCache[path.name]=path}else if(isArray.check(parentValue)){var i=parentValue.indexOf(path.value);if(i>=0){parentCache[path.name=i]=path}}else{parentValue[path.name]=path.value;parentCache[path.name]=path}assert.strictEqual(parentValue[path.name],path.value);assert.strictEqual(path.parentPath.get(path.name),path);return path}Pp.replace=function replace(replacement){var results=[];var parentValue=this.parentPath.value;var parentCache=getChildCache(this.parentPath);var count=arguments.length;repairRelationshipWithParent(this);if(isArray.check(parentValue)){var originalLength=parentValue.length;var move=getMoves(this.parentPath,count-1,this.name+1);var spliceArgs=[this.name,1];for(var i=0;i<count;++i){spliceArgs.push(arguments[i])}var splicedOut=parentValue.splice.apply(parentValue,spliceArgs);assert.strictEqual(splicedOut[0],this.value);assert.strictEqual(parentValue.length,originalLength-1+count);move();if(count===0){delete this.value;delete parentCache[this.name];this.__childCache=null}else{assert.strictEqual(parentValue[this.name],replacement);if(this.value!==replacement){this.value=replacement;this.__childCache=null}for(i=0;i<count;++i){results.push(this.parentPath.get(this.name+i))}assert.strictEqual(results[0],this)}}else if(count===1){if(this.value!==replacement){this.__childCache=null}this.value=parentValue[this.name]=replacement;results.push(this)}else if(count===0){delete parentValue[this.name];delete this.value;this.__childCache=null}else{assert.ok(false,"Could not replace path")}return results};module.exports=Path},{"./types":87,assert:90}],85:[function(require,module,exports){var assert=require("assert");var types=require("./types");var Type=types.Type;var namedTypes=types.namedTypes;var Node=namedTypes.Node;var Expression=namedTypes.Expression;var isArray=types.builtInTypes.array;var hasOwn=Object.prototype.hasOwnProperty;var b=types.builders;function Scope(path,parentScope){assert.ok(this instanceof Scope);assert.ok(path instanceof require("./node-path"));ScopeType.assert(path.value);var depth;if(parentScope){assert.ok(parentScope instanceof Scope);depth=parentScope.depth+1}else{parentScope=null;depth=0}Object.defineProperties(this,{path:{value:path},node:{value:path.value},isGlobal:{value:!parentScope,enumerable:true},depth:{value:depth},parent:{value:parentScope},bindings:{value:{}}})}var scopeTypes=[namedTypes.Program,namedTypes.Function,namedTypes.CatchClause];var ScopeType=Type.or.apply(Type,scopeTypes);Scope.isEstablishedBy=function(node){return ScopeType.check(node)};var Sp=Scope.prototype;Sp.didScan=false;Sp.declares=function(name){this.scan();return hasOwn.call(this.bindings,name)};Sp.declareTemporary=function(prefix){if(prefix){assert.ok(/^[a-z$_]/i.test(prefix),prefix)}else{prefix="t$"}prefix+=this.depth.toString(36)+"$";this.scan();var index=0;while(this.declares(prefix+index)){++index}var name=prefix+index;return this.bindings[name]=types.builders.identifier(name)};Sp.injectTemporary=function(identifier,init){identifier||(identifier=this.declareTemporary());var bodyPath=this.path.get("body");if(namedTypes.BlockStatement.check(bodyPath.value)){bodyPath=bodyPath.get("body")}bodyPath.unshift(b.variableDeclaration("var",[b.variableDeclarator(identifier,init||null)]));return identifier};Sp.scan=function(force){if(force||!this.didScan){for(var name in this.bindings){delete this.bindings[name]}scanScope(this.path,this.bindings);this.didScan=true}};Sp.getBindings=function(){this.scan();return this.bindings};function scanScope(path,bindings){var node=path.value;ScopeType.assert(node);if(namedTypes.CatchClause.check(node)){addPattern(path.get("param"),bindings)}else{recursiveScanScope(path,bindings)}}function recursiveScanScope(path,bindings){var node=path.value;if(path.parent&&namedTypes.FunctionExpression.check(path.parent.node)&&path.parent.node.id){addPattern(path.parent.get("id"),bindings)}if(!node){}else if(isArray.check(node)){path.each(function(childPath){recursiveScanChild(childPath,bindings)})}else if(namedTypes.Function.check(node)){path.get("params").each(function(paramPath){addPattern(paramPath,bindings)});recursiveScanChild(path.get("body"),bindings)}else if(namedTypes.VariableDeclarator.check(node)){addPattern(path.get("id"),bindings);recursiveScanChild(path.get("init"),bindings)}else if(node.type==="ImportSpecifier"||node.type==="ImportNamespaceSpecifier"||node.type==="ImportDefaultSpecifier"){addPattern(node.name?path.get("name"):path.get("id"),bindings)}else if(Node.check(node)&&!Expression.check(node)){types.eachField(node,function(name,child){var childPath=path.get(name);assert.strictEqual(childPath.value,child);recursiveScanChild(childPath,bindings)})}}function recursiveScanChild(path,bindings){var node=path.value;if(!node||Expression.check(node)){}else if(namedTypes.FunctionDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(namedTypes.ClassDeclaration&&namedTypes.ClassDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(ScopeType.check(node)){if(namedTypes.CatchClause.check(node)){var catchParamName=node.param.name;var hadBinding=hasOwn.call(bindings,catchParamName);recursiveScanScope(path.get("body"),bindings);if(!hadBinding){delete bindings[catchParamName]}}}else{recursiveScanScope(path,bindings)}}function addPattern(patternPath,bindings){var pattern=patternPath.value;namedTypes.Pattern.assert(pattern);if(namedTypes.Identifier.check(pattern)){if(hasOwn.call(bindings,pattern.name)){bindings[pattern.name].push(patternPath)}else{bindings[pattern.name]=[patternPath]}}else if(namedTypes.SpreadElement&&namedTypes.SpreadElement.check(pattern)){addPattern(patternPath.get("argument"),bindings)}}Sp.lookup=function(name){for(var scope=this;scope;scope=scope.parent)if(scope.declares(name))break;return scope};Sp.getGlobalScope=function(){var scope=this;while(!scope.isGlobal)scope=scope.parent;return scope};module.exports=Scope},{"./node-path":82,"./types":87,assert:90}],86:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var builtin=types.builtInTypes;var isNumber=builtin.number;exports.geq=function(than){return new Type(function(value){return isNumber.check(value)&&value>=than},isNumber+" >= "+than)};exports.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var naiveIsPrimitive=Type.or(builtin.string,builtin.number,builtin.boolean,builtin.null,builtin.undefined);exports.isPrimitive=new Type(function(value){if(value===null)return true;var type=typeof value;return!(type==="object"||type==="function")},naiveIsPrimitive.toString())},{"../lib/types":87}],87:[function(require,module,exports){var assert=require("assert");var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;var each=Ap.forEach;var Op=Object.prototype;var objToStr=Op.toString;var funObjStr=objToStr.call(function(){});var strObjStr=objToStr.call("");var hasOwn=Op.hasOwnProperty;function Type(check,name){var self=this;assert.ok(self instanceof Type,self);assert.strictEqual(objToStr.call(check),funObjStr,check+" is not a function");var nameObjStr=objToStr.call(name);assert.ok(nameObjStr===funObjStr||nameObjStr===strObjStr,name+" is neither a function nor a string");Object.defineProperties(self,{name:{value:name},check:{value:function(value,deep){var result=check.call(self,value,deep);if(!result&&deep&&objToStr.call(deep)===funObjStr)deep(self,value);return result}}})}var Tp=Type.prototype;exports.Type=Type;Tp.assert=function(value,deep){if(!this.check(value,deep)){var str=shallowStringify(value);assert.ok(false,str+" does not match type "+this);return false}return true};function shallowStringify(value){if(isObject.check(value))return"{"+Object.keys(value).map(function(key){return key+": "+value[key]}).join(", ")+"}";if(isArray.check(value))return"["+value.map(shallowStringify).join(", ")+"]";return JSON.stringify(value)}Tp.toString=function(){var name=this.name;if(isString.check(name))return name;if(isFunction.check(name))return name.call(this)+"";return name+" type"};var builtInTypes={};exports.builtInTypes=builtInTypes;function defBuiltInType(example,name){var objStr=objToStr.call(example);Object.defineProperty(builtInTypes,name,{enumerable:true,value:new Type(function(value){return objToStr.call(value)===objStr},name)});return builtInTypes[name]}var isString=defBuiltInType("","string");var isFunction=defBuiltInType(function(){},"function");var isArray=defBuiltInType([],"array");var isObject=defBuiltInType({},"object");var isRegExp=defBuiltInType(/./,"RegExp");var isDate=defBuiltInType(new Date,"Date");var isNumber=defBuiltInType(3,"number");var isBoolean=defBuiltInType(true,"boolean");var isNull=defBuiltInType(null,"null");var isUndefined=defBuiltInType(void 0,"undefined");function toType(from,name){if(from instanceof Type)return from;if(from instanceof Def)return from.type;if(isArray.check(from))return Type.fromArray(from);if(isObject.check(from))return Type.fromObject(from);if(isFunction.check(from))return new Type(from,name);return new Type(function(value){return value===from},isUndefined.check(name)?function(){return from+""}:name)}Type.or=function(){var types=[];var len=arguments.length;for(var i=0;i<len;++i)types.push(toType(arguments[i]));return new Type(function(value,deep){for(var i=0;i<len;++i)if(types[i].check(value,deep))return true;return false},function(){return types.join(" | ")})};Type.fromArray=function(arr){assert.ok(isArray.check(arr));assert.strictEqual(arr.length,1,"only one element type is permitted for typed arrays");return toType(arr[0]).arrayOf()};Tp.arrayOf=function(){var elemType=this;return new Type(function(value,deep){return isArray.check(value)&&value.every(function(elem){return elemType.check(elem,deep)})},function(){return"["+elemType+"]"})};Type.fromObject=function(obj){var fields=Object.keys(obj).map(function(name){return new Field(name,obj[name])});return new Type(function(value,deep){return isObject.check(value)&&fields.every(function(field){return field.type.check(value[field.name],deep)})},function(){return"{ "+fields.join(", ")+" }"})};function Field(name,type,defaultFn,hidden){var self=this;assert.ok(self instanceof Field);isString.assert(name);type=toType(type);var properties={name:{value:name},type:{value:type},hidden:{value:!!hidden}};if(isFunction.check(defaultFn)){properties.defaultFn={value:defaultFn}}Object.defineProperties(self,properties)}var Fp=Field.prototype;Fp.toString=function(){return JSON.stringify(this.name)+": "+this.type};Fp.getValue=function(obj){var value=obj[this.name];if(!isUndefined.check(value))return value;if(this.defaultFn)value=this.defaultFn.call(obj);return value};Type.def=function(typeName){isString.assert(typeName);return hasOwn.call(defCache,typeName)?defCache[typeName]:defCache[typeName]=new Def(typeName)};var defCache=Object.create(null);function Def(typeName){var self=this;assert.ok(self instanceof Def);Object.defineProperties(self,{typeName:{value:typeName},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new Type(function(value,deep){return self.check(value,deep)},typeName)}})}Def.fromValue=function(value){if(value&&typeof value==="object"){var type=value.type;if(typeof type==="string"&&hasOwn.call(defCache,type)){var d=defCache[type];if(d.finalized){return d}}}return null};var Dp=Def.prototype;Dp.isSupertypeOf=function(that){if(that instanceof Def){assert.strictEqual(this.finalized,true);assert.strictEqual(that.finalized,true);return hasOwn.call(that.allSupertypes,this.typeName)}else{assert.ok(false,that+" is not a Def")}};exports.getSupertypeNames=function(typeName){assert.ok(hasOwn.call(defCache,typeName));var d=defCache[typeName];assert.strictEqual(d.finalized,true);return d.supertypeList.slice(1)};exports.computeSupertypeLookupTable=function(candidates){var table={};var typeNames=Object.keys(defCache);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];var d=defCache[typeName];assert.strictEqual(d.finalized,true);for(var j=0;j<d.supertypeList.length;++j){var superTypeName=d.supertypeList[j];if(hasOwn.call(candidates,superTypeName)){table[typeName]=superTypeName;break}}}return table};Dp.checkAllFields=function(value,deep){var allFields=this.allFields;assert.strictEqual(this.finalized,true);function checkFieldByName(name){var field=allFields[name];var type=field.type;var child=field.getValue(value);return type.check(child,deep)}return isObject.check(value)&&Object.keys(allFields).every(checkFieldByName)};Dp.check=function(value,deep){assert.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!isObject.check(value))return false;var vDef=Def.fromValue(value);if(!vDef){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(value,deep)}return false}if(deep&&vDef===this)return this.checkAllFields(value,deep);if(!this.isSupertypeOf(vDef))return false;if(!deep)return true;return vDef.checkAllFields(value,deep)&&this.checkAllFields(value,false)};Dp.bases=function(){var bases=this.baseNames;assert.strictEqual(this.finalized,false);each.call(arguments,function(baseName){isString.assert(baseName);if(bases.indexOf(baseName)<0)bases.push(baseName)});return this};Object.defineProperty(Dp,"buildable",{value:false});var builders={};exports.builders=builders;var nodePrototype={};exports.defineMethod=function(name,func){var old=nodePrototype[name];if(isUndefined.check(func)){delete nodePrototype[name]}else{isFunction.assert(func);Object.defineProperty(nodePrototype,name,{enumerable:true,configurable:true,value:func})}return old};Dp.build=function(){var self=this;Object.defineProperty(self,"buildParams",{value:slice.call(arguments),writable:false,enumerable:false,configurable:true});assert.strictEqual(self.finalized,false);isString.arrayOf().assert(self.buildParams);if(self.buildable){return self}self.field("type",self.typeName,function(){return self.typeName});Object.defineProperty(self,"buildable",{value:true});Object.defineProperty(builders,getBuilderName(self.typeName),{enumerable:true,value:function(){var args=arguments;var argc=args.length;var built=Object.create(nodePrototype);assert.ok(self.finalized,"attempting to instantiate unfinalized type "+self.typeName);function add(param,i){if(hasOwn.call(built,param))return;var all=self.allFields;assert.ok(hasOwn.call(all,param),param);var field=all[param];var type=field.type;var value;if(isNumber.check(i)&&i<argc){value=args[i]}else if(field.defaultFn){value=field.defaultFn.call(built)}else{var message="no value or default function given for field "+JSON.stringify(param)+" of "+self.typeName+"("+self.buildParams.map(function(name){return all[name]}).join(", ")+")";assert.ok(false,message)}if(!type.check(value)){assert.ok(false,shallowStringify(value)+" does not match field "+field+" of type "+self.typeName)}built[param]=value}self.buildParams.forEach(function(param,i){add(param,i)});Object.keys(self.allFields).forEach(function(param){add(param)});assert.strictEqual(built.type,self.typeName);return built}});return self};function getBuilderName(typeName){return typeName.replace(/^[A-Z]+/,function(upperCasePrefix){var len=upperCasePrefix.length;switch(len){case 0:return"";case 1:return upperCasePrefix.toLowerCase();default:return upperCasePrefix.slice(0,len-1).toLowerCase()+upperCasePrefix.charAt(len-1)}})}Dp.field=function(name,type,defaultFn,hidden){assert.strictEqual(this.finalized,false);this.ownFields[name]=new Field(name,type,defaultFn,hidden);return this};var namedTypes={};exports.namedTypes=namedTypes;function getFieldNames(object){var d=Def.fromValue(object);if(d){return d.fieldNames.slice(0)}if("type"in object){assert.ok(false,"did not recognize object of type "+JSON.stringify(object.type))}return Object.keys(object)}exports.getFieldNames=getFieldNames;function getFieldValue(object,fieldName){var d=Def.fromValue(object);if(d){var field=d.allFields[fieldName];if(field){return field.getValue(object)}}return object[fieldName]}exports.getFieldValue=getFieldValue;exports.eachField=function(object,callback,context){getFieldNames(object).forEach(function(name){callback.call(this,name,getFieldValue(object,name))},context)};exports.someField=function(object,callback,context){return getFieldNames(object).some(function(name){return callback.call(this,name,getFieldValue(object,name)) },context)};Object.defineProperty(Dp,"finalized",{value:false});Dp.finalize=function(){if(!this.finalized){var allFields=this.allFields;var allSupertypes=this.allSupertypes;this.baseNames.forEach(function(name){var def=defCache[name];def.finalize();extend(allFields,def.allFields);extend(allSupertypes,def.allSupertypes)});extend(allFields,this.ownFields);allSupertypes[this.typeName]=this;this.fieldNames.length=0;for(var fieldName in allFields){if(hasOwn.call(allFields,fieldName)&&!allFields[fieldName].hidden){this.fieldNames.push(fieldName)}}Object.defineProperty(namedTypes,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});populateSupertypeList(this.typeName,this.supertypeList)}};function populateSupertypeList(typeName,list){list.length=0;list.push(typeName);var lastSeen=Object.create(null);for(var pos=0;pos<list.length;++pos){typeName=list[pos];var d=defCache[typeName];assert.strictEqual(d.finalized,true);if(hasOwn.call(lastSeen,typeName)){delete list[lastSeen[typeName]]}lastSeen[typeName]=pos;list.push.apply(list,d.baseNames)}for(var to=0,from=to,len=list.length;from<len;++from){if(hasOwn.call(list,from)){list[to++]=list[from]}}list.length=to}function extend(into,from){Object.keys(from).forEach(function(name){into[name]=from[name]});return into}exports.finalize=function(){Object.keys(defCache).forEach(function(name){defCache[name].finalize()})}},{assert:90}],88:[function(require,module,exports){var types=require("./lib/types");require("./def/core");require("./def/es6");require("./def/es7");require("./def/mozilla");require("./def/e4x");require("./def/fb-harmony");types.finalize();exports.Type=types.Type;exports.builtInTypes=types.builtInTypes;exports.namedTypes=types.namedTypes;exports.builders=types.builders;exports.defineMethod=types.defineMethod;exports.getFieldNames=types.getFieldNames;exports.getFieldValue=types.getFieldValue;exports.eachField=types.eachField;exports.someField=types.someField;exports.getSupertypeNames=types.getSupertypeNames;exports.astNodesAreEquivalent=require("./lib/equiv");exports.finalize=types.finalize;exports.NodePath=require("./lib/node-path");exports.PathVisitor=require("./lib/path-visitor");exports.visit=exports.PathVisitor.visit},{"./def/core":75,"./def/e4x":76,"./def/es6":77,"./def/es7":78,"./def/fb-harmony":79,"./def/mozilla":80,"./lib/equiv":81,"./lib/node-path":82,"./lib/path-visitor":83,"./lib/types":87}],89:[function(require,module,exports){},{}],90:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&(isNaN(value)||!isFinite(value))){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(isArguments(a)){if(!isArguments(b)){return false}a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}try{var ka=objectKeys(a),kb=objectKeys(b),key,i}catch(e){return false}if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":99}],91:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;Buffer.TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){if(encoding==="base64")subject=base64clean(subject);length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new TypeError("must start with number, buffer, array or string");if(this.length>kMaxLength)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength.toString(16)+" bytes");var buf;if(Buffer.TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!Buffer.TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}return buf}Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function(list,totalLength){if(!isArray(list))throw new TypeError("Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.byteLength=function(str,encoding){var ret;str=str+"";switch(encoding||"utf8"){case"ascii":case"binary":case"raw":ret=str.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;case"hex":ret=str.length>>>1;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"base64":ret=base64ToBytes(str).length;break;default:ret=str.length}return ret};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;Buffer.prototype.toString=function(encoding,start,end){var loweredCase=false;start=start>>>0;end=end===undefined||end===Infinity?this.length:end>>>0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}};Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);if(isNaN(byte))throw new Error("Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string),buf,offset,length);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new TypeError("Unknown encoding: "+encoding)}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function binarySlice(buf,start,end){return asciiSlice(buf,start,end)}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;if(Buffer.TYPED_ARRAY_SUPPORT){return Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;var newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}return newBuf}};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value;return offset+1};Buffer.prototype.writeInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};Buffer.prototype.writeInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(!target_start)target_start=0;if(end===start)return;if(target.length===0||source.length===0)return;if(end<start)throw new TypeError("sourceEnd < sourceStart");if(target_start<0||target_start>=target.length)throw new TypeError("targetStart out of bounds");if(start<0||start>=source.length)throw new TypeError("sourceStart out of bounds");if(end<0||end>source.length)throw new TypeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new TypeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new TypeError("start out of bounds");if(end<0||end>this.length)throw new TypeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){var b=str.charCodeAt(i);if(b<=127){byteArray.push(b)}else{var start=i;if(b>=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j<h.length;j++){byteArray.push(parseInt(h[j],16))}}}return byteArray}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}},{"base64-js":92,ieee754:93,"is-array":94}],92:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],93:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.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)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],94:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],95:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],96:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){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(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};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();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)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};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("/"))};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){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];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}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:97}],97:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];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")}},{}],98:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],99:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":98,_process:97,inherits:95}],100:[function(require,module,exports){(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{factory(root.estraverse={})}})(this,function(exports){"use strict";var Syntax,isArray,VisitorOption,VisitorKeys,objectCreate,objectKeys,BREAK,SKIP,REMOVE;function ignoreJSHintError(){}isArray=Array.isArray;if(!isArray){isArray=function isArray(array){return Object.prototype.toString.call(array)==="[object Array]"}}function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function shallowCopy(obj){var ret={},key;for(key in obj){if(obj.hasOwnProperty(key)){ret[key]=obj[key]}}return ret}ignoreJSHintError(shallowCopy);function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}function lowerBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){i=current+1;len-=diff+1}else{len=diff}}return i}ignoreJSHintError(lowerBound);objectCreate=Object.create||function(){function F(){}return function(o){F.prototype=o;return new F}}();objectKeys=Object.keys||function(o){var keys=[],key;for(key in o){keys.push(key)}return keys};function extend(to,from){objectKeys(from).forEach(function(key){to[key]=from[key]});return to}Syntax={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};VisitorKeys={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=visitor.fallback==="iteration";this.__keys=VisitorKeys;if(visitor.keys){this.__keys=extend(objectCreate(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.version="1.8.0";exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller})},{}],101:[function(require,module,exports){(function(){"use strict";function isExpression(node){if(node==null){return false}switch(node.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return true}return false}function isIterationStatement(node){if(node==null){return false}switch(node.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function isStatement(node){if(node==null){return false}switch(node.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return true}return false}function isSourceElement(node){return isStatement(node)||node!=null&&node.type==="FunctionDeclaration"}function trailingStatement(node){switch(node.type){case"IfStatement":if(node.alternate!=null){return node.alternate}return node.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return node.body}return null}function isProblematicIfStatement(node){var current;if(node.type!=="IfStatement"){return false}if(node.alternate==null){return false}current=node.consequent;do{if(current.type==="IfStatement"){if(current.alternate==null){return true}}current=trailingStatement(current)}while(current);return false}module.exports={isExpression:isExpression,isStatement:isStatement,isIterationStatement:isIterationStatement,isSourceElement:isSourceElement,isProblematicIfStatement:isProblematicIfStatement,trailingStatement:trailingStatement}})()},{}],102:[function(require,module,exports){(function(){"use strict";var Regex;Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")}; function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return isDecimalDigit(ch)||97<=ch&&ch<=102||65<=ch&&ch<=70}function isOctalDigit(ch){return ch>=48&&ch<=55}function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}module.exports={isDecimalDigit:isDecimalDigit,isHexDigit:isHexDigit,isOctalDigit:isOctalDigit,isWhiteSpace:isWhiteSpace,isLineTerminator:isLineTerminator,isIdentifierStart:isIdentifierStart,isIdentifierPart:isIdentifierPart}})()},{}],103:[function(require,module,exports){(function(){"use strict";var code=require("./code");function isStrictModeReservedWordES6(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function isKeywordES5(id,strict){if(!strict&&id==="yield"){return false}return isKeywordES6(id,strict)}function isKeywordES6(id,strict){if(strict&&isStrictModeReservedWordES6(id)){return true}switch(id.length){case 2:return id==="if"||id==="in"||id==="do";case 3:return id==="var"||id==="for"||id==="new"||id==="try";case 4:return id==="this"||id==="else"||id==="case"||id==="void"||id==="with"||id==="enum";case 5:return id==="while"||id==="break"||id==="catch"||id==="throw"||id==="const"||id==="yield"||id==="class"||id==="super";case 6:return id==="return"||id==="typeof"||id==="delete"||id==="switch"||id==="export"||id==="import";case 7:return id==="default"||id==="finally"||id==="extends";case 8:return id==="function"||id==="continue"||id==="debugger";case 10:return id==="instanceof";default:return false}}function isReservedWordES5(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES5(id,strict)}function isReservedWordES6(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES6(id,strict)}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isIdentifierName(id){var i,iz,ch;if(id.length===0){return false}ch=id.charCodeAt(0);if(!code.isIdentifierStart(ch)||ch===92){return false}for(i=1,iz=id.length;i<iz;++i){ch=id.charCodeAt(i);if(!code.isIdentifierPart(ch)||ch===92){return false}}return true}function isIdentifierES5(id,strict){return isIdentifierName(id)&&!isReservedWordES5(id,strict)}function isIdentifierES6(id,strict){return isIdentifierName(id)&&!isReservedWordES6(id,strict)}module.exports={isKeywordES5:isKeywordES5,isKeywordES6:isKeywordES6,isReservedWordES5:isReservedWordES5,isReservedWordES6:isReservedWordES6,isRestrictedWord:isRestrictedWord,isIdentifierName:isIdentifierName,isIdentifierES5:isIdentifierES5,isIdentifierES6:isIdentifierES6}})()},{"./code":102}],104:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":101,"./code":102,"./keyword":103}],105:[function(require,module,exports){(function(global){(function(){var undefined;var arrayPool=[],objectPool=[];var idCounter=0;var keyPrefix=+new Date+"";var largeArraySize=75;var maxPoolSize=40;var whitespace=" \f "+"\n\r\u2028\u2029"+" ᠎              ";var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var reFlags=/\w*$/;var reFuncName=/^\s*function[ \n\r\t]+\w/;var reInterpolate=/<%=([\s\S]+?)%>/g;var reLeadingSpacesAndZeros=RegExp("^["+whitespace+"]*0+(?=.$)");var reNoMatch=/($^)/;var reThis=/\bthis\b/;var reUnescapedString=/['\n\r\t\u2028\u2029\\]/g;var contextProps=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"];var templateCounter=0;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var cloneableClasses={};cloneableClasses[funcClass]=false;cloneableClasses[argsClass]=cloneableClasses[arrayClass]=cloneableClasses[boolClass]=cloneableClasses[dateClass]=cloneableClasses[numberClass]=cloneableClasses[objectClass]=cloneableClasses[regexpClass]=cloneableClasses[stringClass]=true;var debounceOptions={leading:false,maxWait:0,trailing:false};var descriptor={configurable:false,enumerable:false,value:null,writable:false};var objectTypes={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};var root=objectTypes[typeof window]&&window||this;var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports;var freeGlobal=objectTypes[typeof global]&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)){root=freeGlobal}function baseIndexOf(array,value,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0;while(++index<length){if(array[index]===value){return index}}return-1}function cacheIndexOf(cache,value){var type=typeof value;cache=cache.cache;if(type=="boolean"||value==null){return cache[value]?0:-1}if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value;cache=(cache=cache[type])&&cache[key];return type=="object"?cache&&baseIndexOf(cache,value)>-1?0:-1:cache?0:-1}function cachePush(value){var cache=this.cache,type=typeof value;if(type=="boolean"||value==null){cache[value]=true}else{if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value,typeCache=cache[type]||(cache[type]={});if(type=="object"){(typeCache[key]||(typeCache[key]=[])).push(value)}else{typeCache[key]=true}}}function charAtCallback(value){return value.charCodeAt(0)}function compareAscending(a,b){var ac=a.criteria,bc=b.criteria,index=-1,length=ac.length;while(++index<length){var value=ac[index],other=bc[index];if(value!==other){if(value>other||typeof value=="undefined"){return 1}if(value<other||typeof other=="undefined"){return-1}}}return a.index-b.index}function createCache(array){var index=-1,length=array.length,first=array[0],mid=array[length/2|0],last=array[length-1];if(first&&typeof first=="object"&&mid&&typeof mid=="object"&&last&&typeof last=="object"){return false}var cache=getObject();cache["false"]=cache["null"]=cache["true"]=cache["undefined"]=false;var result=getObject();result.array=array;result.cache=cache;result.push=cachePush;while(++index<length){result.push(array[index])}return result}function escapeStringChar(match){return"\\"+stringEscapes[match]}function getArray(){return arrayPool.pop()||[]}function getObject(){return objectPool.pop()||{array:null,cache:null,criteria:null,"false":false,index:0,"null":false,number:null,object:null,push:null,string:null,"true":false,undefined:false,value:null}}function releaseArray(array){array.length=0;if(arrayPool.length<maxPoolSize){arrayPool.push(array)}}function releaseObject(object){var cache=object.cache;if(cache){releaseObject(cache)}object.array=object.cache=object.criteria=object.object=object.number=object.string=object.value=null;if(objectPool.length<maxPoolSize){objectPool.push(object)}}function slice(array,start,end){start||(start=0);if(typeof end=="undefined"){end=array?array.length:0}var index=-1,length=end-start||0,result=Array(length<0?0:length);while(++index<length){result[index]=array[start+index]}return result}function runInContext(context){context=context?_.defaults(root.Object(),context,_.pick(root,contextProps)):root;var Array=context.Array,Boolean=context.Boolean,Date=context.Date,Function=context.Function,Math=context.Math,Number=context.Number,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;var arrayRef=[];var objectProto=Object.prototype;var oldDash=context._;var toString=objectProto.toString;var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var ceil=Math.ceil,clearTimeout=context.clearTimeout,floor=Math.floor,fnToString=Function.prototype.toString,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,hasOwnProperty=objectProto.hasOwnProperty,push=arrayRef.push,setTimeout=context.setTimeout,splice=arrayRef.splice,unshift=arrayRef.unshift;var defineProperty=function(){try{var o={},func=isNative(func=Object.defineProperty)&&func,result=func(o,o,o)&&func}catch(e){}return result}();var nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate,nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeIsFinite=context.isFinite,nativeIsNaN=context.isNaN,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,nativeParseInt=context.parseInt,nativeRandom=Math.random;var ctorByClass={};ctorByClass[arrayClass]=Array;ctorByClass[boolClass]=Boolean;ctorByClass[dateClass]=Date;ctorByClass[funcClass]=Function;ctorByClass[objectClass]=Object;ctorByClass[numberClass]=Number;ctorByClass[regexpClass]=RegExp;ctorByClass[stringClass]=String;function lodash(value){return value&&typeof value=="object"&&!isArray(value)&&hasOwnProperty.call(value,"__wrapped__")?value:new lodashWrapper(value)}function lodashWrapper(value,chainAll){this.__chain__=!!chainAll;this.__wrapped__=value}lodashWrapper.prototype=lodash.prototype;var support=lodash.support={};support.funcDecomp=!isNative(context.WinRTError)&&reThis.test(runInContext);support.funcNames=typeof Function.name=="string";lodash.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:reInterpolate,variable:"",imports:{_:lodash}};function baseBind(bindData){var func=bindData[0],partialArgs=bindData[2],thisArg=bindData[4];function bound(){if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(this instanceof bound){var thisBinding=baseCreate(func.prototype),result=func.apply(thisBinding,args||arguments);return isObject(result)?result:thisBinding}return func.apply(thisArg,args||arguments)}setBindData(bound,bindData);return bound}function baseClone(value,isDeep,callback,stackA,stackB){if(callback){var result=callback(value);if(typeof result!="undefined"){return result}}var isObj=isObject(value);if(isObj){var className=toString.call(value);if(!cloneableClasses[className]){return value}var ctor=ctorByClass[className];switch(className){case boolClass:case dateClass:return new ctor(+value);case numberClass:case stringClass:return new ctor(value);case regexpClass:result=ctor(value.source,reFlags.exec(value));result.lastIndex=value.lastIndex;return result}}else{return value}var isArr=isArray(value);if(isDeep){var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==value){return stackB[length]}}result=isArr?ctor(value.length):{}}else{result=isArr?slice(value):assign({},value)}if(isArr){if(hasOwnProperty.call(value,"index")){result.index=value.index}if(hasOwnProperty.call(value,"input")){result.input=value.input}}if(!isDeep){return result}stackA.push(value);stackB.push(result);(isArr?forEach:forOwn)(value,function(objValue,key){result[key]=baseClone(objValue,isDeep,callback,stackA,stackB)});if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseCreate(prototype,properties){return isObject(prototype)?nativeCreate(prototype):{}}if(!nativeCreate){baseCreate=function(){function Object(){}return function(prototype){if(isObject(prototype)){Object.prototype=prototype;var result=new Object;Object.prototype=null}return result||context.Object()}}()}function baseCreateCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(typeof thisArg=="undefined"||!("prototype"in func)){return func}var bindData=func.__bindData__;if(typeof bindData=="undefined"){if(support.funcNames){bindData=!func.name}bindData=bindData||!support.funcDecomp;if(!bindData){var source=fnToString.call(func);if(!support.funcNames){bindData=!reFuncName.test(source)}if(!bindData){bindData=reThis.test(source);setBindData(func,bindData)}}}if(bindData===false||bindData!==true&&bindData[1]&1){return func}switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 2:return function(a,b){return func.call(thisArg,a,b)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)}}return bind(func,thisArg)}function baseCreateWrapper(bindData){var func=bindData[0],bitmask=bindData[1],partialArgs=bindData[2],partialRightArgs=bindData[3],thisArg=bindData[4],arity=bindData[5];var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,key=func;function bound(){var thisBinding=isBind?thisArg:this;if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(partialRightArgs||isCurry){args||(args=slice(arguments));if(partialRightArgs){push.apply(args,partialRightArgs)}if(isCurry&&args.length<arity){bitmask|=16&~32;return baseCreateWrapper([func,isCurryBound?bitmask:bitmask&~3,args,null,thisArg,arity])}}args||(args=arguments);if(isBindKey){func=thisBinding[key]}if(this instanceof bound){thisBinding=baseCreate(func.prototype);var result=func.apply(thisBinding,args);return isObject(result)?result:thisBinding}return func.apply(thisBinding,args)}setBindData(bound,bindData);return bound}function baseDifference(array,values){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,isLarge=length>=largeArraySize&&indexOf===baseIndexOf,result=[];if(isLarge){var cache=createCache(values);if(cache){indexOf=cacheIndexOf;values=cache}else{isLarge=false}}while(++index<length){var value=array[index];if(indexOf(values,value)<0){result.push(value)}}if(isLarge){releaseObject(values)}return result}function baseFlatten(array,isShallow,isStrict,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value&&typeof value=="object"&&typeof value.length=="number"&&(isArray(value)||isArguments(value))){if(!isShallow){value=baseFlatten(value,isShallow,isStrict)}var valIndex=-1,valLength=value.length,resIndex=result.length;result.length+=valLength;while(++valIndex<valLength){result[resIndex++]=value[valIndex]}}else if(!isStrict){result.push(value)}}return result}function baseIsEqual(a,b,callback,isWhere,stackA,stackB){if(callback){var result=callback(a,b);if(typeof result!="undefined"){return!!result}}if(a===b){return a!==0||1/a==1/b}var type=typeof a,otherType=typeof b;if(a===a&&!(a&&objectTypes[type])&&!(b&&objectTypes[otherType])){return false}if(a==null||b==null){return a===b}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:return+a==+b;case numberClass:return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case regexpClass:case stringClass:return a==String(b)}var isArr=className==arrayClass;if(!isArr){var aWrapped=hasOwnProperty.call(a,"__wrapped__"),bWrapped=hasOwnProperty.call(b,"__wrapped__");if(aWrapped||bWrapped){return baseIsEqual(aWrapped?a.__wrapped__:a,bWrapped?b.__wrapped__:b,callback,isWhere,stackA,stackB)}if(className!=objectClass){return false}var ctorA=a.constructor,ctorB=b.constructor;if(ctorA!=ctorB&&!(isFunction(ctorA)&&ctorA instanceof ctorA&&isFunction(ctorB)&&ctorB instanceof ctorB)&&("constructor"in a&&"constructor"in b)){return false}}var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==a){return stackB[length]==b}}var size=0;result=true;stackA.push(a);stackB.push(b);if(isArr){length=a.length;size=b.length;result=size==length;if(result||isWhere){while(size--){var index=length,value=b[size];if(isWhere){while(index--){if(result=baseIsEqual(a[index],value,callback,isWhere,stackA,stackB)){break}}}else if(!(result=baseIsEqual(a[size],value,callback,isWhere,stackA,stackB))){break}}}}else{forIn(b,function(value,key,b){if(hasOwnProperty.call(b,key)){size++;return result=hasOwnProperty.call(a,key)&&baseIsEqual(a[key],value,callback,isWhere,stackA,stackB)}});if(result&&!isWhere){forIn(a,function(value,key,a){if(hasOwnProperty.call(a,key)){return result=--size>-1}})}}stackA.pop();stackB.pop();if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseMerge(object,source,callback,stackA,stackB){(isArray(source)?forEach:forOwn)(source,function(source,key){var found,isArr,result=source,value=object[key];if(source&&((isArr=isArray(source))||isPlainObject(source))){var stackLength=stackA.length;while(stackLength--){if(found=stackA[stackLength]==source){value=stackB[stackLength];break}}if(!found){var isShallow;if(callback){result=callback(value,source);if(isShallow=typeof result!="undefined"){value=result}}if(!isShallow){value=isArr?isArray(value)?value:[]:isPlainObject(value)?value:{}}stackA.push(source);stackB.push(value);if(!isShallow){baseMerge(value,source,callback,stackA,stackB)}}}else{if(callback){result=callback(value,source);if(typeof result=="undefined"){result=source}}if(typeof result!="undefined"){value=result}}object[key]=value})}function baseRandom(min,max){return min+floor(nativeRandom()*(max-min+1))}function baseUniq(array,isSorted,callback){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,result=[];var isLarge=!isSorted&&length>=largeArraySize&&indexOf===baseIndexOf,seen=callback||isLarge?getArray():result;if(isLarge){var cache=createCache(seen);indexOf=cacheIndexOf;seen=cache}while(++index<length){var value=array[index],computed=callback?callback(value,index,array):value;if(isSorted?!index||seen[seen.length-1]!==computed:indexOf(seen,computed)<0){if(callback||isLarge){seen.push(computed)}result.push(value)}}if(isLarge){releaseArray(seen.array);releaseObject(seen)}else if(callback){releaseArray(seen)}return result}function createAggregator(setter){return function(collection,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];setter(result,value,callback(value,index,collection),collection)}}else{forOwn(collection,function(value,key,collection){setter(result,value,callback(value,key,collection),collection)})}return result}}function createWrapper(func,bitmask,partialArgs,partialRightArgs,thisArg,arity){var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,isPartial=bitmask&16,isPartialRight=bitmask&32;if(!isBindKey&&!isFunction(func)){throw new TypeError}if(isPartial&&!partialArgs.length){bitmask&=~16;isPartial=partialArgs=false}if(isPartialRight&&!partialRightArgs.length){bitmask&=~32;isPartialRight=partialRightArgs=false}var bindData=func&&func.__bindData__;if(bindData&&bindData!==true){bindData=slice(bindData);if(bindData[2]){bindData[2]=slice(bindData[2])}if(bindData[3]){bindData[3]=slice(bindData[3])}if(isBind&&!(bindData[1]&1)){bindData[4]=thisArg}if(!isBind&&bindData[1]&1){bitmask|=8}if(isCurry&&!(bindData[1]&4)){bindData[5]=arity}if(isPartial){push.apply(bindData[2]||(bindData[2]=[]),partialArgs)}if(isPartialRight){unshift.apply(bindData[3]||(bindData[3]=[]),partialRightArgs)}bindData[1]|=bitmask;return createWrapper.apply(null,bindData)}var creater=bitmask==1||bitmask===17?baseBind:baseCreateWrapper;return creater([func,bitmask,partialArgs,partialRightArgs,thisArg,arity])}function escapeHtmlChar(match){return htmlEscapes[match]}function getIndexOf(){var result=(result=lodash.indexOf)===indexOf?baseIndexOf:result;return result}function isNative(value){return typeof value=="function"&&reNative.test(value)}var setBindData=!defineProperty?noop:function(func,value){descriptor.value=value;defineProperty(func,"__bindData__",descriptor)};function shimIsPlainObject(value){var ctor,result;if(!(value&&toString.call(value)==objectClass)||(ctor=value.constructor,isFunction(ctor)&&!(ctor instanceof ctor))){return false}forIn(value,function(value,key){result=key});return typeof result=="undefined"||hasOwnProperty.call(value,result)}function unescapeHtmlChar(match){return htmlUnescapes[match]}function isArguments(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==argsClass||false}var isArray=nativeIsArray||function(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==arrayClass||false};var shimKeys=function(object){var index,iterable=object,result=[];if(!iterable)return result;if(!objectTypes[typeof object])return result;for(index in iterable){if(hasOwnProperty.call(iterable,index)){result.push(index)}}return result};var keys=!nativeKeys?shimKeys:function(object){if(!isObject(object)){return[]}return nativeKeys(object)};var htmlEscapes={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};var htmlUnescapes=invert(htmlEscapes);var reEscapedHtml=RegExp("("+keys(htmlUnescapes).join("|")+")","g"),reUnescapedHtml=RegExp("["+keys(htmlEscapes).join("")+"]","g");var assign=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;if(argsLength>3&&typeof args[argsLength-2]=="function"){var callback=baseCreateCallback(args[--argsLength-1],args[argsLength--],2)}else if(argsLength>2&&typeof args[argsLength-1]=="function"){callback=args[--argsLength]}while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];result[index]=callback?callback(result[index],iterable[index]):iterable[index]}}}return result};function clone(value,isDeep,callback,thisArg){if(typeof isDeep!="boolean"&&isDeep!=null){thisArg=callback;callback=isDeep;isDeep=false}return baseClone(value,isDeep,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function cloneDeep(value,callback,thisArg){return baseClone(value,true,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function create(prototype,properties){var result=baseCreate(prototype);return properties?assign(result,properties):result}var defaults=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(typeof result[index]=="undefined")result[index]=iterable[index]}}}return result};function findKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}function findLastKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwnRight(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}var forIn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);for(index in iterable){if(callback(iterable[index],index,collection)===false)return result}return result};function forInRight(object,callback,thisArg){var pairs=[];forIn(object,function(value,key){pairs.push(key,value)});var length=pairs.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){if(callback(pairs[length--],pairs[length],object)===false){break}}return object}var forOwn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(callback(iterable[index],index,collection)===false)return result}return result};function forOwnRight(object,callback,thisArg){var props=keys(object),length=props.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){var key=props[length];if(callback(object[key],key,object)===false){break}}return object}function functions(object){var result=[];forIn(object,function(value,key){if(isFunction(value)){result.push(key)}});return result.sort()}function has(object,key){return object?hasOwnProperty.call(object,key):false}function invert(object){var index=-1,props=keys(object),length=props.length,result={};while(++index<length){var key=props[index];result[object[key]]=key}return result}function isBoolean(value){return value===true||value===false||value&&typeof value=="object"&&toString.call(value)==boolClass||false}function isDate(value){return value&&typeof value=="object"&&toString.call(value)==dateClass||false}function isElement(value){return value&&value.nodeType===1||false}function isEmpty(value){var result=true;if(!value){return result}var className=toString.call(value),length=value.length;if(className==arrayClass||className==stringClass||className==argsClass||className==objectClass&&typeof length=="number"&&isFunction(value.splice)){return!length}forOwn(value,function(){return result=false});return result}function isEqual(a,b,callback,thisArg){return baseIsEqual(a,b,typeof callback=="function"&&baseCreateCallback(callback,thisArg,2))}function isFinite(value){return nativeIsFinite(value)&&!nativeIsNaN(parseFloat(value))}function isFunction(value){return typeof value=="function"}function isObject(value){return!!(value&&objectTypes[typeof value])}function isNaN(value){return isNumber(value)&&value!=+value}function isNull(value){return value===null}function isNumber(value){return typeof value=="number"||value&&typeof value=="object"&&toString.call(value)==numberClass||false}var isPlainObject=!getPrototypeOf?shimIsPlainObject:function(value){if(!(value&&toString.call(value)==objectClass)){return false}var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)};function isRegExp(value){return value&&typeof value=="object"&&toString.call(value)==regexpClass||false}function isString(value){return typeof value=="string"||value&&typeof value=="object"&&toString.call(value)==stringClass||false}function isUndefined(value){return typeof value=="undefined"}function mapValues(object,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){result[key]=callback(value,key,object)});return result}function merge(object){var args=arguments,length=2;if(!isObject(object)){return object}if(typeof args[2]!="number"){length=args.length}if(length>3&&typeof args[length-2]=="function"){var callback=baseCreateCallback(args[--length-1],args[length--],2)}else if(length>2&&typeof args[length-1]=="function"){callback=args[--length]}var sources=slice(arguments,1,length),index=-1,stackA=getArray(),stackB=getArray();while(++index<length){baseMerge(object,sources[index],callback,stackA,stackB)}releaseArray(stackA);releaseArray(stackB);return object}function omit(object,callback,thisArg){var result={};if(typeof callback!="function"){var props=[];forIn(object,function(value,key){props.push(key)});props=baseDifference(props,baseFlatten(arguments,true,false,1));var index=-1,length=props.length;while(++index<length){var key=props[index];result[key]=object[key]}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(!callback(value,key,object)){result[key]=value}})}return result}function pairs(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){var key=props[index];result[index]=[key,object[key]]}return result}function pick(object,callback,thisArg){var result={};if(typeof callback!="function"){var index=-1,props=baseFlatten(arguments,true,false,1),length=isObject(object)?props.length:0;while(++index<length){var key=props[index];if(key in object){result[key]=object[key]}}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(callback(value,key,object)){result[key]=value}})}return result}function transform(object,callback,accumulator,thisArg){var isArr=isArray(object);if(accumulator==null){if(isArr){accumulator=[]}else{var ctor=object&&object.constructor,proto=ctor&&ctor.prototype;accumulator=baseCreate(proto)}}if(callback){callback=lodash.createCallback(callback,thisArg,4);(isArr?forEach:forOwn)(object,function(value,index,object){return callback(accumulator,value,index,object)})}return accumulator}function values(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}function at(collection){var args=arguments,index=-1,props=baseFlatten(args,true,false,1),length=args[2]&&args[2][args[1]]===collection?1:props.length,result=Array(length);while(++index<length){result[index]=collection[props[index]]}return result}function contains(collection,target,fromIndex){var index=-1,indexOf=getIndexOf(),length=collection?collection.length:0,result=false;fromIndex=(fromIndex<0?nativeMax(0,length+fromIndex):fromIndex)||0;if(isArray(collection)){result=indexOf(collection,target,fromIndex)>-1}else if(typeof length=="number"){result=(isString(collection)?collection.indexOf(target,fromIndex):indexOf(collection,target,fromIndex))>-1}else{forOwn(collection,function(value){if(++index>=fromIndex){return!(result=value===target)}})}return result}var countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key]++:result[key]=1});function every(collection,callback,thisArg){var result=true;callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(!(result=!!callback(collection[index],index,collection))){break}}}else{forOwn(collection,function(value,index,collection){return result=!!callback(value,index,collection)})}return result}function filter(collection,callback,thisArg){var result=[];callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){result.push(value)}}}else{forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result.push(value)}})}return result}function find(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3); var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){return value}}}else{var result;forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}}function findLast(collection,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forEachRight(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}function forEach(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(++index<length){if(callback(collection[index],index,collection)===false){break}}}else{forOwn(collection,callback)}return collection}function forEachRight(collection,callback,thisArg){var length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(length--){if(callback(collection[length],length,collection)===false){break}}}else{var props=keys(collection);length=props.length;forOwn(collection,function(value,key,collection){key=props?props[--length]:--length;return callback(collection[key],key,collection)})}return collection}var groupBy=createAggregator(function(result,value,key){(hasOwnProperty.call(result,key)?result[key]:result[key]=[]).push(value)});var indexBy=createAggregator(function(result,value,key){result[key]=value});function invoke(collection,methodName){var args=slice(arguments,2),index=-1,isFunc=typeof methodName=="function",length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){result[++index]=(isFunc?methodName:value[methodName]).apply(value,args)});return result}function map(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=lodash.createCallback(callback,thisArg,3);if(typeof length=="number"){var result=Array(length);while(++index<length){result[index]=callback(collection[index],index,collection)}}else{result=[];forOwn(collection,function(value,key,collection){result[++index]=callback(value,key,collection)})}return result}function max(collection,callback,thisArg){var computed=-Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value>result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current>computed){computed=current;result=value}})}return result}function min(collection,callback,thisArg){var computed=Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value<result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current<computed){computed=current;result=value}})}return result}var pluck=map;function reduce(collection,callback,accumulator,thisArg){if(!collection)return accumulator;var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);var index=-1,length=collection.length;if(typeof length=="number"){if(noaccum){accumulator=collection[++index]}while(++index<length){accumulator=callback(accumulator,collection[index],index,collection)}}else{forOwn(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)})}return accumulator}function reduceRight(collection,callback,accumulator,thisArg){var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);forEachRight(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)});return accumulator}function reject(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3);return filter(collection,function(value,index,collection){return!callback(value,index,collection)})}function sample(collection,n,guard){if(collection&&typeof collection.length!="number"){collection=values(collection)}if(n==null||guard){return collection?collection[baseRandom(0,collection.length-1)]:undefined}var result=shuffle(collection);result.length=nativeMin(nativeMax(0,n),result.length);return result}function shuffle(collection){var index=-1,length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){var rand=baseRandom(0,++index);result[index]=result[rand];result[rand]=value});return result}function size(collection){var length=collection?collection.length:0;return typeof length=="number"?length:keys(collection).length}function some(collection,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(result=callback(collection[index],index,collection)){break}}}else{forOwn(collection,function(value,index,collection){return!(result=callback(value,index,collection))})}return!!result}function sortBy(collection,callback,thisArg){var index=-1,isArr=isArray(callback),length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);if(!isArr){callback=lodash.createCallback(callback,thisArg,3)}forEach(collection,function(value,key,collection){var object=result[++index]=getObject();if(isArr){object.criteria=map(callback,function(key){return value[key]})}else{(object.criteria=getArray())[0]=callback(value,key,collection)}object.index=index;object.value=value});length=result.length;result.sort(compareAscending);while(length--){var object=result[length];result[length]=object.value;if(!isArr){releaseArray(object.criteria)}releaseObject(object)}return result}function toArray(collection){if(collection&&typeof collection.length=="number"){return slice(collection)}return values(collection)}var where=filter;function compact(array){var index=-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value){result.push(value)}}return result}function difference(array){return baseDifference(array,baseFlatten(arguments,true,true,1))}function findIndex(array,callback,thisArg){var index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length){if(callback(array[index],index,array)){return index}}return-1}function findLastIndex(array,callback,thisArg){var length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(length--){if(callback(array[length],length,array)){return length}}return-1}function first(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=-1;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[0]:undefined}}return slice(array,0,nativeMin(nativeMax(0,n),length))}function flatten(array,isShallow,callback,thisArg){if(typeof isShallow!="boolean"&&isShallow!=null){thisArg=callback;callback=typeof isShallow!="function"&&thisArg&&thisArg[isShallow]===array?null:isShallow;isShallow=false}if(callback!=null){array=map(array,callback,thisArg)}return baseFlatten(array,isShallow)}function indexOf(array,value,fromIndex){if(typeof fromIndex=="number"){var length=array?array.length:0;fromIndex=fromIndex<0?nativeMax(0,length+fromIndex):fromIndex||0}else if(fromIndex){var index=sortedIndex(array,value);return array[index]===value?index:-1}return baseIndexOf(array,value,fromIndex)}function initial(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:callback||n}return slice(array,0,nativeMin(nativeMax(0,length-n),length))}function intersection(){var args=[],argsIndex=-1,argsLength=arguments.length,caches=getArray(),indexOf=getIndexOf(),trustIndexOf=indexOf===baseIndexOf,seen=getArray();while(++argsIndex<argsLength){var value=arguments[argsIndex];if(isArray(value)||isArguments(value)){args.push(value);caches.push(trustIndexOf&&value.length>=largeArraySize&&createCache(argsIndex?args[argsIndex]:seen))}}var array=args[0],index=-1,length=array?array.length:0,result=[];outer:while(++index<length){var cache=caches[0];value=array[index];if((cache?cacheIndexOf(cache,value):indexOf(seen,value))<0){argsIndex=argsLength;(cache||seen).push(value);while(--argsIndex){cache=caches[argsIndex];if((cache?cacheIndexOf(cache,value):indexOf(args[argsIndex],value))<0){continue outer}}result.push(value)}}while(argsLength--){cache=caches[argsLength];if(cache){releaseObject(cache)}}releaseArray(caches);releaseArray(seen);return result}function last(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[length-1]:undefined}}return slice(array,nativeMax(0,length-n))}function lastIndexOf(array,value,fromIndex){var index=array?array.length:0;if(typeof fromIndex=="number"){index=(fromIndex<0?nativeMax(0,index+fromIndex):nativeMin(fromIndex,index-1))+1}while(index--){if(array[index]===value){return index}}return-1}function pull(array){var args=arguments,argsIndex=0,argsLength=args.length,length=array?array.length:0;while(++argsIndex<argsLength){var index=-1,value=args[argsIndex];while(++index<length){if(array[index]===value){splice.call(array,index--,1);length--}}}return array}function range(start,end,step){start=+start||0;step=typeof step=="number"?step:+step||1;if(end==null){end=start;start=0}var index=-1,length=nativeMax(0,ceil((end-start)/(step||1))),result=Array(length);while(++index<length){result[index]=start;start+=step}return result}function remove(array,callback,thisArg){var index=-1,length=array?array.length:0,result=[];callback=lodash.createCallback(callback,thisArg,3);while(++index<length){var value=array[index];if(callback(value,index,array)){result.push(value);splice.call(array,index--,1);length--}}return result}function rest(array,callback,thisArg){if(typeof callback!="number"&&callback!=null){var n=0,index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:nativeMax(0,callback)}return slice(array,n)}function sortedIndex(array,value,callback,thisArg){var low=0,high=array?array.length:low;callback=callback?lodash.createCallback(callback,thisArg,1):identity;value=callback(value);while(low<high){var mid=low+high>>>1;callback(array[mid])<value?low=mid+1:high=mid}return low}function union(){return baseUniq(baseFlatten(arguments,true,true))}function uniq(array,isSorted,callback,thisArg){if(typeof isSorted!="boolean"&&isSorted!=null){thisArg=callback;callback=typeof isSorted!="function"&&thisArg&&thisArg[isSorted]===array?null:isSorted;isSorted=false}if(callback!=null){callback=lodash.createCallback(callback,thisArg,3)}return baseUniq(array,isSorted,callback)}function without(array){return baseDifference(array,slice(arguments,1))}function xor(){var index=-1,length=arguments.length;while(++index<length){var array=arguments[index];if(isArray(array)||isArguments(array)){var result=result?baseUniq(baseDifference(result,array).concat(baseDifference(array,result))):array}}return result||[]}function zip(){var array=arguments.length>1?arguments:arguments[0],index=-1,length=array?max(pluck(array,"length")):0,result=Array(length<0?0:length);while(++index<length){result[index]=pluck(array,index)}return result}function zipObject(keys,values){var index=-1,length=keys?keys.length:0,result={};if(!values&&length&&!isArray(keys[0])){values=[]}while(++index<length){var key=keys[index];if(values){result[key]=values[index]}else if(key){result[key[0]]=key[1]}}return result}function after(n,func){if(!isFunction(func)){throw new TypeError}return function(){if(--n<1){return func.apply(this,arguments)}}}function bind(func,thisArg){return arguments.length>2?createWrapper(func,17,slice(arguments,2),null,thisArg):createWrapper(func,1,null,null,thisArg)}function bindAll(object){var funcs=arguments.length>1?baseFlatten(arguments,true,false,1):functions(object),index=-1,length=funcs.length;while(++index<length){var key=funcs[index];object[key]=createWrapper(object[key],1,null,null,object)}return object}function bindKey(object,key){return arguments.length>2?createWrapper(key,19,slice(arguments,2),null,object):createWrapper(key,3,null,null,object)}function compose(){var funcs=arguments,length=funcs.length;while(length--){if(!isFunction(funcs[length])){throw new TypeError}}return function(){var args=arguments,length=funcs.length;while(length--){args=[funcs[length].apply(this,args)]}return args[0]}}function curry(func,arity){arity=typeof arity=="number"?arity:+arity||func.length;return createWrapper(func,4,null,null,null,arity)}function debounce(func,wait,options){var args,maxTimeoutId,result,stamp,thisArg,timeoutId,trailingCall,lastCalled=0,maxWait=false,trailing=true;if(!isFunction(func)){throw new TypeError}wait=nativeMax(0,wait)||0;if(options===true){var leading=true;trailing=false}else if(isObject(options)){leading=options.leading;maxWait="maxWait"in options&&(nativeMax(wait,options.maxWait)||0);trailing="trailing"in options?options.trailing:trailing}var delayed=function(){var remaining=wait-(now()-stamp);if(remaining<=0){if(maxTimeoutId){clearTimeout(maxTimeoutId)}var isCalled=trailingCall;maxTimeoutId=timeoutId=trailingCall=undefined;if(isCalled){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}}else{timeoutId=setTimeout(delayed,remaining)}};var maxDelayed=function(){if(timeoutId){clearTimeout(timeoutId)}maxTimeoutId=timeoutId=trailingCall=undefined;if(trailing||maxWait!==wait){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}};return function(){args=arguments;stamp=now();thisArg=this;trailingCall=trailing&&(timeoutId||!leading);if(maxWait===false){var leadingCall=leading&&!timeoutId}else{if(!maxTimeoutId&&!leading){lastCalled=stamp}var remaining=maxWait-(stamp-lastCalled),isCalled=remaining<=0;if(isCalled){if(maxTimeoutId){maxTimeoutId=clearTimeout(maxTimeoutId)}lastCalled=stamp;result=func.apply(thisArg,args)}else if(!maxTimeoutId){maxTimeoutId=setTimeout(maxDelayed,remaining)}}if(isCalled&&timeoutId){timeoutId=clearTimeout(timeoutId)}else if(!timeoutId&&wait!==maxWait){timeoutId=setTimeout(delayed,wait)}if(leadingCall){isCalled=true;result=func.apply(thisArg,args)}if(isCalled&&!timeoutId&&!maxTimeoutId){args=thisArg=null}return result}}function defer(func){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,1);return setTimeout(function(){func.apply(undefined,args)},1)}function delay(func,wait){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,2);return setTimeout(function(){func.apply(undefined,args)},wait)}function memoize(func,resolver){if(!isFunction(func)){throw new TypeError}var memoized=function(){var cache=memoized.cache,key=resolver?resolver.apply(this,arguments):keyPrefix+arguments[0];return hasOwnProperty.call(cache,key)?cache[key]:cache[key]=func.apply(this,arguments)};memoized.cache={};return memoized}function once(func){var ran,result;if(!isFunction(func)){throw new TypeError}return function(){if(ran){return result}ran=true;result=func.apply(this,arguments);func=null;return result}}function partial(func){return createWrapper(func,16,slice(arguments,1))}function partialRight(func){return createWrapper(func,32,null,slice(arguments,1))}function throttle(func,wait,options){var leading=true,trailing=true;if(!isFunction(func)){throw new TypeError}if(options===false){leading=false}else if(isObject(options)){leading="leading"in options?options.leading:leading;trailing="trailing"in options?options.trailing:trailing}debounceOptions.leading=leading;debounceOptions.maxWait=wait;debounceOptions.trailing=trailing;return debounce(func,wait,debounceOptions)}function wrap(value,wrapper){return createWrapper(wrapper,16,[value])}function constant(value){return function(){return value}}function createCallback(func,thisArg,argCount){var type=typeof func;if(func==null||type=="function"){return baseCreateCallback(func,thisArg,argCount)}if(type!="object"){return property(func)}var props=keys(func),key=props[0],a=func[key];if(props.length==1&&a===a&&!isObject(a)){return function(object){var b=object[key];return a===b&&(a!==0||1/a==1/b)}}return function(object){var length=props.length,result=false;while(length--){if(!(result=baseIsEqual(object[props[length]],func[props[length]],null,true))){break}}return result}}function escape(string){return string==null?"":String(string).replace(reUnescapedHtml,escapeHtmlChar)}function identity(value){return value}function mixin(object,source,options){var chain=true,methodNames=source&&functions(source);if(!source||!options&&!methodNames.length){if(options==null){options=source}ctor=lodashWrapper;source=object;object=lodash;methodNames=functions(source)}if(options===false){chain=false}else if(isObject(options)&&"chain"in options){chain=options.chain}var ctor=object,isFunc=isFunction(ctor);forEach(methodNames,function(methodName){var func=object[methodName]=source[methodName];if(isFunc){ctor.prototype[methodName]=function(){var chainAll=this.__chain__,value=this.__wrapped__,args=[value];push.apply(args,arguments);var result=func.apply(object,args);if(chain||chainAll){if(value===result&&isObject(result)){return this}result=new ctor(result);result.__chain__=chainAll}return result}}})}function noConflict(){context._=oldDash;return this}function noop(){}var now=isNative(now=Date.now)&&now||function(){return(new Date).getTime()};var parseInt=nativeParseInt(whitespace+"08")==8?nativeParseInt:function(value,radix){return nativeParseInt(isString(value)?value.replace(reLeadingSpacesAndZeros,""):value,radix||0)};function property(key){return function(object){return object[key]}}function random(min,max,floating){var noMin=min==null,noMax=max==null;if(floating==null){if(typeof min=="boolean"&&noMax){floating=min;min=1}else if(!noMax&&typeof max=="boolean"){floating=max;noMax=true}}if(noMin&&noMax){max=1}min=+min||0;if(noMax){max=min;min=0}else{max=+max||0}if(floating||min%1||max%1){var rand=nativeRandom();return nativeMin(min+rand*(max-min+parseFloat("1e-"+((rand+"").length-1))),max)}return baseRandom(min,max)}function result(object,key){if(object){var value=object[key];return isFunction(value)?object[key]():value}}function template(text,data,options){var settings=lodash.templateSettings;text=String(text||"");options=defaults({},options,settings);var imports=defaults({},options.imports,settings.imports),importsKeys=keys(imports),importsValues=values(imports);var isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";var reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g");text.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);source+=text.slice(index,offset).replace(reUnescapedString,escapeStringChar);if(escapeValue){source+="' +\n__e("+escapeValue+") +\n'"}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '"}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"}index=offset+match.length;return match});source+="';\n";var variable=options.variable,hasVariable=variable;if(!hasVariable){variable="obj";source="with ("+variable+") {\n"+source+"\n}\n"}source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;");source="function("+variable+") {\n"+(hasVariable?"":variable+" || ("+variable+" = {});\n")+"var __t, __p = '', __e = _.escape"+(isEvaluating?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var sourceURL="\n/*\n//# sourceURL="+(options.sourceURL||"/lodash/template/source["+templateCounter++ +"]")+"\n*/";try{var result=Function(importsKeys,"return "+source+sourceURL).apply(undefined,importsValues)}catch(e){e.source=source;throw e}if(data){return result(data)}result.source=source;return result}function times(n,callback,thisArg){n=(n=+n)>-1?n:0;var index=-1,result=Array(n);callback=baseCreateCallback(callback,thisArg,1);while(++index<n){result[index]=callback(index)}return result}function unescape(string){return string==null?"":String(string).replace(reEscapedHtml,unescapeHtmlChar)}function uniqueId(prefix){var id=++idCounter;return String(prefix==null?"":prefix)+id}function chain(value){value=new lodashWrapper(value);value.__chain__=true;return value}function tap(value,interceptor){interceptor(value);return value}function wrapperChain(){this.__chain__=true;return this}function wrapperToString(){return String(this.__wrapped__)}function wrapperValueOf(){return this.__wrapped__}lodash.after=after;lodash.assign=assign;lodash.at=at;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.chain=chain;lodash.compact=compact;lodash.compose=compose;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.createCallback=createCallback;lodash.curry=curry;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.filter=filter;lodash.flatten=flatten;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.functions=functions;lodash.groupBy=groupBy;lodash.indexBy=indexBy;lodash.initial=initial;lodash.intersection=intersection;lodash.invert=invert;lodash.invoke=invoke;lodash.keys=keys;lodash.map=map;lodash.mapValues=mapValues;lodash.max=max;lodash.memoize=memoize;lodash.merge=merge;lodash.min=min;lodash.omit=omit;lodash.once=once;lodash.pairs=pairs;lodash.partial=partial;lodash.partialRight=partialRight;lodash.pick=pick;lodash.pluck=pluck;lodash.property=property;lodash.pull=pull;lodash.range=range;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.shuffle=shuffle;lodash.sortBy=sortBy;lodash.tap=tap;lodash.throttle=throttle;lodash.times=times;lodash.toArray=toArray;lodash.transform=transform;lodash.union=union;lodash.uniq=uniq;lodash.values=values;lodash.where=where;lodash.without=without;lodash.wrap=wrap;lodash.xor=xor;lodash.zip=zip;lodash.zipObject=zipObject;lodash.collect=map;lodash.drop=rest;lodash.each=forEach;lodash.eachRight=forEachRight;lodash.extend=assign;lodash.methods=functions;lodash.object=zipObject;lodash.select=filter;lodash.tail=rest;lodash.unique=uniq;lodash.unzip=zip;mixin(lodash);lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.contains=contains;lodash.escape=escape;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.has=has;lodash.identity=identity;lodash.indexOf=indexOf;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isBoolean=isBoolean;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isNaN=isNaN;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isString=isString;lodash.isUndefined=isUndefined;lodash.lastIndexOf=lastIndexOf;lodash.mixin=mixin;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.result=result;lodash.runInContext=runInContext;lodash.size=size;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.template=template;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.all=every;lodash.any=some;lodash.detect=find;lodash.findWhere=find;lodash.foldl=reduce;lodash.foldr=reduceRight;lodash.include=contains;lodash.inject=reduce;mixin(function(){var source={};forOwn(lodash,function(func,methodName){if(!lodash.prototype[methodName]){source[methodName]=func}});return source}(),false);lodash.first=first;lodash.last=last;lodash.sample=sample;lodash.take=first;lodash.head=first;forOwn(lodash,function(func,methodName){var callbackable=methodName!=="sample";if(!lodash.prototype[methodName]){lodash.prototype[methodName]=function(n,guard){var chainAll=this.__chain__,result=func(this.__wrapped__,n,guard);return!chainAll&&(n==null||guard&&!(callbackable&&typeof n=="function"))?result:new lodashWrapper(result,chainAll)}}});lodash.VERSION="2.4.1";lodash.prototype.chain=wrapperChain;lodash.prototype.toString=wrapperToString;lodash.prototype.value=wrapperValueOf;lodash.prototype.valueOf=wrapperValueOf;forEach(["join","pop","shift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){var chainAll=this.__chain__,result=func.apply(this.__wrapped__,arguments);return chainAll?new lodashWrapper(result,chainAll):result}});forEach(["push","reverse","sort","unshift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){func.apply(this.__wrapped__,arguments);return this}});forEach(["concat","slice","splice"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){return new lodashWrapper(func.apply(this.__wrapped__,arguments),this.__chain__)}});return lodash}var _=runInContext();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root._=_;define(function(){return _})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=_)._=_}else{freeExports._=_}}else{root._=_}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],106:[function(require,module,exports){"use strict";var originalObject=Object;var originalDefProp=Object.defineProperty;var originalCreate=Object.create;function defProp(obj,name,value){if(originalDefProp)try{originalDefProp.call(originalObject,obj,name,{value:value})}catch(definePropertyIsBrokenInIE8){obj[name]=value}else{obj[name]=value}}function makeSafeToCall(fun){if(fun){defProp(fun,"call",fun.call);defProp(fun,"apply",fun.apply)}return fun}makeSafeToCall(originalDefProp);makeSafeToCall(originalCreate);var hasOwn=makeSafeToCall(Object.prototype.hasOwnProperty);var numToStr=makeSafeToCall(Number.prototype.toString);var strSlice=makeSafeToCall(String.prototype.slice);var cloner=function(){};function create(prototype){if(originalCreate){return originalCreate.call(originalObject,prototype)}cloner.prototype=prototype||null;return new cloner}var rand=Math.random;var uniqueKeys=create(null);function makeUniqueKey(){do var uniqueKey=internString(strSlice.call(numToStr.call(rand(),36),2));while(hasOwn.call(uniqueKeys,uniqueKey));return uniqueKeys[uniqueKey]=uniqueKey}function internString(str){var obj={};obj[str]=true;return Object.keys(obj)[0]}defProp(exports,"makeUniqueKey",makeUniqueKey);var originalGetOPNs=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function getOwnPropertyNames(object){for(var names=originalGetOPNs(object),src=0,dst=0,len=names.length;src<len;++src){if(!hasOwn.call(uniqueKeys,names[src])){if(src>dst){names[dst]=names[src]}++dst}}names.length=dst;return names};function defaultCreatorFn(object){return create(null)}function makeAccessor(secretCreatorFn){var brand=makeUniqueKey();var passkey=create(null);secretCreatorFn=secretCreatorFn||defaultCreatorFn;function register(object){var secret;function vault(key,forget){if(key===passkey){return forget?secret=null:secret||(secret=secretCreatorFn(object))}}defProp(object,brand,vault)}function accessor(object){if(!hasOwn.call(object,brand))register(object);return object[brand](passkey)}accessor.forget=function(object){if(hasOwn.call(object,brand))object[brand](passkey,true)};return accessor}defProp(exports,"makeAccessor",makeAccessor)},{}],107:[function(require,module,exports){var regenerate=require("regenerate");exports.REGULAR={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,65535),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};exports.UNICODE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};exports.UNICODE_IGNORE_CASE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:109}],108:[function(require,module,exports){module.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871} },{}],109:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var ERRORS={rangeOrder:"A range’s `stop` value must be greater than or equal "+"to the `start` value.",codePointRange:"Invalid code point value. Code points range from "+"U+000000 to U+10FFFF."};var HIGH_SURROGATE_MIN=55296;var HIGH_SURROGATE_MAX=56319;var LOW_SURROGATE_MIN=56320;var LOW_SURROGATE_MAX=57343;var regexNull=/\\x00([^0123456789]|$)/g;var object={};var hasOwnProperty=object.hasOwnProperty;var extend=function(destination,source){var key;for(key in source){if(hasOwnProperty.call(source,key)){destination[key]=source[key]}}return destination};var forEach=function(array,callback){var index=-1;var length=array.length;while(++index<length){callback(array[index],index)}};var toString=object.toString;var isArray=function(value){return toString.call(value)=="[object Array]"};var isNumber=function(value){return typeof value=="number"||toString.call(value)=="[object Number]"};var zeroes="0000";var pad=function(number,totalCharacters){var string=String(number);return string.length<totalCharacters?(zeroes+string).slice(-totalCharacters):string};var hex=function(number){return Number(number).toString(16).toUpperCase()};var slice=[].slice;var dataFromCodePoints=function(codePoints){var index=-1;var length=codePoints.length;var max=length-1;var result=[];var isStart=true;var tmp;var previous=0;while(++index<length){tmp=codePoints[index];if(isStart){result.push(tmp);previous=tmp;isStart=false}else{if(tmp==previous+1){if(index!=max){previous=tmp;continue}else{isStart=true;result.push(tmp+1)}}else{result.push(previous+1,tmp);previous=tmp}}}if(!isStart){result.push(tmp+1)}return result};var dataRemove=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){if(codePoint==start){if(end==start+1){data.splice(index,2);return data}else{data[index]=codePoint+1;return data}}else if(codePoint==end-1){data[index+1]=codePoint;return data}else{data.splice(index,2,start,codePoint,codePoint+1,end);return data}}index+=2}return data};var dataRemoveRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}var index=0;var start;var end;while(index<data.length){start=data[index];end=data[index+1]-1;if(start>rangeEnd){return data}if(rangeStart<=start&&rangeEnd>=end){data.splice(index,2);continue}if(rangeStart>=start&&rangeEnd<end){if(rangeStart==start){data[index]=rangeEnd+1;data[index+1]=end+1;return data}data.splice(index,2,start,rangeStart,rangeEnd+1,end+1);return data}if(rangeStart>=start&&rangeStart<=end){data[index+1]=rangeStart}else if(rangeEnd>=start&&rangeEnd<=end){data[index]=rangeEnd+1;return data}index+=2}return data};var dataAdd=function(data,codePoint){var index=0;var start;var end;var lastIndex=null;var length=data.length;if(codePoint<0||codePoint>1114111){throw RangeError(ERRORS.codePointRange)}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return data}if(codePoint==start-1){data[index]=codePoint;return data}if(start>codePoint){data.splice(lastIndex!=null?lastIndex+2:0,0,codePoint,codePoint+1);return data}if(codePoint==end){if(codePoint+1==data[index+2]){data.splice(index,4,start,data[index+3]);return data}data[index+1]=codePoint+1;return data}lastIndex=index;index+=2}data.push(codePoint,codePoint+1);return data};var dataAddData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataAdd(data,start)}else{data=dataAddRange(data,start,end)}index+=2}return data};var dataRemoveData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataRemove(data,start)}else{data=dataRemoveRange(data,start,end)}index+=2}return data};var dataAddRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}if(rangeStart<0||rangeStart>1114111||rangeEnd<0||rangeEnd>1114111){throw RangeError(ERRORS.codePointRange)}var index=0;var start;var end;var added=false;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(added){if(start==rangeEnd+1){data.splice(index-1,2);return data}if(start>rangeEnd){return data}if(start>=rangeStart&&start<=rangeEnd){if(end>rangeStart&&end-1<=rangeEnd){data.splice(index,2);index-=2}else{data.splice(index-1,2);index-=2}}}else if(start==rangeEnd+1){data[index]=rangeStart;return data}else if(start>rangeEnd){data.splice(index,0,rangeStart,rangeEnd+1);return data}else if(rangeStart>=start&&rangeStart<end&&rangeEnd+1<=end){return data}else if(rangeStart>=start&&rangeStart<end||end==rangeStart){data[index+1]=rangeEnd+1;added=true}else if(rangeStart<=start&&rangeEnd+1>=end){data[index]=rangeStart;data[index+1]=rangeEnd+1;added=true}index+=2}if(!added){data.push(rangeStart,rangeEnd+1)}return data};var dataContains=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return true}index+=2}return false};var dataIntersection=function(data,codePoints){var index=0;var length=codePoints.length;var codePoint;var result=[];while(index<length){codePoint=codePoints[index];if(dataContains(data,codePoint)){result.push(codePoint)}++index}return dataFromCodePoints(result)};var dataIsEmpty=function(data){return!data.length};var dataIsSingleton=function(data){return data.length==2&&data[0]+1==data[1]};var dataToArray=function(data){var index=0;var start;var end;var result=[];var length=data.length;while(index<length){start=data[index];end=data[index+1];while(start<end){result.push(start);++start}index+=2}return result};var floor=Math.floor;var highSurrogate=function(codePoint){return parseInt(floor((codePoint-65536)/1024)+HIGH_SURROGATE_MIN,10)};var lowSurrogate=function(codePoint){return parseInt((codePoint-65536)%1024+LOW_SURROGATE_MIN,10)};var stringFromCharCode=String.fromCharCode;var codePointToString=function(codePoint){var string;if(codePoint==9){string="\\t"}else if(codePoint==10){string="\\n"}else if(codePoint==12){string="\\f"}else if(codePoint==13){string="\\r"}else if(codePoint==92){string="\\\\"}else if(codePoint==36||codePoint>=40&&codePoint<=43||codePoint==45||codePoint==46||codePoint==63||codePoint>=91&&codePoint<=94||codePoint>=123&&codePoint<=125){string="\\"+stringFromCharCode(codePoint)}else if(codePoint>=32&&codePoint<=126){string=stringFromCharCode(codePoint)}else if(codePoint<=255){string="\\x"+pad(hex(codePoint),2)}else{string="\\u"+pad(hex(codePoint),4)}return string};var symbolToCodePoint=function(symbol){var length=symbol.length;var first=symbol.charCodeAt(0);var second;if(first>=HIGH_SURROGATE_MIN&&first<=HIGH_SURROGATE_MAX&&length>1){second=symbol.charCodeAt(1);return(first-HIGH_SURROGATE_MIN)*1024+second-LOW_SURROGATE_MIN+65536}return first};var createBMPCharacterClasses=function(data){var result="";var index=0;var start;var end;var length=data.length;if(dataIsSingleton(data)){return codePointToString(data[0])}while(index<length){start=data[index];end=data[index+1]-1;if(start==end){result+=codePointToString(start)}else if(start+1==end){result+=codePointToString(start)+codePointToString(end)}else{result+=codePointToString(start)+"-"+codePointToString(end)}index+=2}return"["+result+"]"};var splitAtBMP=function(data){var loneHighSurrogates=[];var bmp=[];var astral=[];var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1]-1;if(start<=65535&&end<=65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){if(end<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,end+1)}else{loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,end+1)}}else if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,end+1)}else if(start<HIGH_SURROGATE_MIN&&end>HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,end+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,end+1)}}else if(start<=65535&&end>65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,65535+1)}else if(start<HIGH_SURROGATE_MIN){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,65535+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,65535+1)}astral.push(65535+1,end+1)}else{astral.push(start,end+1)}index+=2}return{loneHighSurrogates:loneHighSurrogates,bmp:bmp,astral:astral}};var optimizeSurrogateMappings=function(surrogateMappings){var result=[];var tmpLow=[];var addLow=false;var mapping;var nextMapping;var highSurrogates;var lowSurrogates;var nextHighSurrogates;var nextLowSurrogates;var index=-1;var length=surrogateMappings.length;while(++index<length){mapping=surrogateMappings[index];nextMapping=surrogateMappings[index+1];if(!nextMapping){result.push(mapping);continue}highSurrogates=mapping[0];lowSurrogates=mapping[1];nextHighSurrogates=nextMapping[0];nextLowSurrogates=nextMapping[1];tmpLow=lowSurrogates;while(nextHighSurrogates&&highSurrogates[0]==nextHighSurrogates[0]&&highSurrogates[1]==nextHighSurrogates[1]){if(dataIsSingleton(nextLowSurrogates)){tmpLow=dataAdd(tmpLow,nextLowSurrogates[0])}else{tmpLow=dataAddRange(tmpLow,nextLowSurrogates[0],nextLowSurrogates[1]-1)}++index;mapping=surrogateMappings[index];highSurrogates=mapping[0];lowSurrogates=mapping[1];nextMapping=surrogateMappings[index+1];nextHighSurrogates=nextMapping&&nextMapping[0];nextLowSurrogates=nextMapping&&nextMapping[1];addLow=true}result.push([highSurrogates,addLow?tmpLow:lowSurrogates]);addLow=false}return optimizeByLowSurrogates(result)};var optimizeByLowSurrogates=function(surrogateMappings){if(surrogateMappings.length==1){return surrogateMappings}var index=-1;var innerIndex=-1;while(++index<surrogateMappings.length){var mapping=surrogateMappings[index];var lowSurrogates=mapping[1];var lowSurrogateStart=lowSurrogates[0];var lowSurrogateEnd=lowSurrogates[1];innerIndex=index;while(++innerIndex<surrogateMappings.length){var otherMapping=surrogateMappings[innerIndex];var otherLowSurrogates=otherMapping[1];var otherLowSurrogateStart=otherLowSurrogates[0];var otherLowSurrogateEnd=otherLowSurrogates[1];if(lowSurrogateStart==otherLowSurrogateStart&&lowSurrogateEnd==otherLowSurrogateEnd){if(dataIsSingleton(otherMapping[0])){mapping[0]=dataAdd(mapping[0],otherMapping[0][0])}else{mapping[0]=dataAddRange(mapping[0],otherMapping[0][0],otherMapping[0][1]-1)}surrogateMappings.splice(innerIndex,1);--innerIndex}}}return surrogateMappings};var surrogateSet=function(data){if(!data.length){return[]}var index=0;var start;var end;var startHigh;var startLow;var prevStartHigh=0;var prevEndHigh=0;var tmpLow=[];var endHigh;var endLow;var surrogateMappings=[];var length=data.length;var dataHigh=[];while(index<length){start=data[index];end=data[index+1]-1;startHigh=highSurrogate(start);startLow=lowSurrogate(start);endHigh=highSurrogate(end);endLow=lowSurrogate(end);var startsWithLowestLowSurrogate=startLow==LOW_SURROGATE_MIN;var endsWithHighestLowSurrogate=endLow==LOW_SURROGATE_MAX;var complete=false;if(startHigh==endHigh||startsWithLowestLowSurrogate&&endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh,endHigh+1],[startLow,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh,startHigh+1],[startLow,LOW_SURROGATE_MAX+1]])}if(!complete&&startHigh+1<endHigh){if(endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh+1,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh+1,endHigh],[LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1]])}}if(!complete){surrogateMappings.push([[endHigh,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]])}prevStartHigh=startHigh;prevEndHigh=endHigh;index+=2}return optimizeSurrogateMappings(surrogateMappings)};var createSurrogateCharacterClasses=function(surrogateMappings){var result=[];forEach(surrogateMappings,function(surrogateMapping){var highSurrogates=surrogateMapping[0];var lowSurrogates=surrogateMapping[1];result.push(createBMPCharacterClasses(highSurrogates)+createBMPCharacterClasses(lowSurrogates))});return result.join("|")};var createCharacterClassesFromData=function(data){var result=[];var parts=splitAtBMP(data);var loneHighSurrogates=parts.loneHighSurrogates;var bmp=parts.bmp;var astral=parts.astral;var hasAstral=!dataIsEmpty(parts.astral);var hasLoneSurrogates=!dataIsEmpty(loneHighSurrogates);var surrogateMappings=surrogateSet(astral);if(!hasAstral&&hasLoneSurrogates){bmp=dataAddData(bmp,loneHighSurrogates)}if(!dataIsEmpty(bmp)){result.push(createBMPCharacterClasses(bmp))}if(surrogateMappings.length){result.push(createSurrogateCharacterClasses(surrogateMappings))}if(hasAstral&&hasLoneSurrogates){result.push(createBMPCharacterClasses(loneHighSurrogates))}return result.join("|")};var regenerate=function(value){if(arguments.length>1){value=slice.call(arguments)}if(this instanceof regenerate){this.data=[];return value?this.add(value):this}return(new regenerate).add(value)};regenerate.version="1.0.1";var proto=regenerate.prototype;extend(proto,{add:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataAddData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.add(item)});return $this}$this.data=dataAdd($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},remove:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataRemoveData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.remove(item)});return $this}$this.data=dataRemove($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},addRange:function(start,end){var $this=this;$this.data=dataAddRange($this.data,isNumber(start)?start:symbolToCodePoint(start),isNumber(end)?end:symbolToCodePoint(end));return $this},removeRange:function(start,end){var $this=this;var startCodePoint=isNumber(start)?start:symbolToCodePoint(start);var endCodePoint=isNumber(end)?end:symbolToCodePoint(end);$this.data=dataRemoveRange($this.data,startCodePoint,endCodePoint);return $this},intersection:function(argument){var $this=this;var array=argument instanceof regenerate?dataToArray(argument.data):argument;$this.data=dataIntersection($this.data,array);return $this},contains:function(codePoint){return dataContains(this.data,isNumber(codePoint)?codePoint:symbolToCodePoint(codePoint))},clone:function(){var set=new regenerate;set.data=this.data.slice(0);return set},toString:function(){var result=createCharacterClassesFromData(this.data);return result.replace(regexNull,"\\0$1")},toRegExp:function(flags){return RegExp(this.toString(),flags||"")},valueOf:function(){return dataToArray(this.data)}});proto.toArray=proto.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return regenerate})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=regenerate}else{freeExports.regenerate=regenerate}}else{root.regenerate=regenerate}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],110:[function(require,module,exports){(function(global){(function(){"use strict";var objectTypes={"function":true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var stringFromCharCode=String.fromCharCode;var floor=Math.floor;function fromCodePoint(){var MAX_SIZE=16384;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return""}var result="";while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>1114111||floor(codePoint)!=codePoint){throw RangeError("Invalid code point: "+codePoint)}if(codePoint<=65535){codeUnits.push(codePoint)}else{codePoint-=65536;highSurrogate=(codePoint>>10)+55296;lowSurrogate=codePoint%1024+56320;codeUnits.push(highSurrogate,lowSurrogate)}if(index+1==length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0}}return result}function assertType(type,expected){if(expected.indexOf("|")==-1){if(type==expected){return}throw Error("Invalid node type: "+type)}expected=assertType.hasOwnProperty(expected)?assertType[expected]:assertType[expected]=RegExp("^(?:"+expected+")$");if(expected.test(type)){return}throw Error("Invalid node type: "+type)}function generate(node){var type=node.type;if(generate.hasOwnProperty(type)&&typeof generate[type]=="function"){return generate[type](node)}throw Error("Invalid node type: "+type)}function generateAlternative(node){assertType(node.type,"alternative");var terms=node.body,length=terms?terms.length:0;if(length==1){return generateTerm(terms[0])}else{var i=-1,result="";while(++i<length){result+=generateTerm(terms[i])}return result}}function generateAnchor(node){assertType(node.type,"anchor");switch(node.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function generateAtom(node){assertType(node.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return generate(node)}function generateCharacterClass(node){assertType(node.type,"characterClass");var classRanges=node.body,length=classRanges?classRanges.length:0;var i=-1,result="[";if(node.negative){result+="^"}while(++i<length){result+=generateClassAtom(classRanges[i])}result+="]";return result}function generateCharacterClassEscape(node){assertType(node.type,"characterClassEscape");return"\\"+node.value}function generateCharacterClassRange(node){assertType(node.type,"characterClassRange");var min=node.min,max=node.max;if(min.type=="characterClassRange"||max.type=="characterClassRange"){throw Error("Invalid character class range")}return generateClassAtom(min)+"-"+generateClassAtom(max)}function generateClassAtom(node){assertType(node.type,"anchor|characterClassEscape|characterClassRange|dot|value");return generate(node)}function generateDisjunction(node){assertType(node.type,"disjunction");var body=node.body,length=body?body.length:0;if(length==0){throw Error("No body")}else if(length==1){return generate(body[0])}else{var i=-1,result="";while(++i<length){if(i!=0){result+="|"}result+=generate(body[i])}return result}}function generateDot(node){assertType(node.type,"dot");return"."}function generateGroup(node){assertType(node.type,"group");var result="(";switch(node.behavior){case"normal":break;case"ignore":result+="?:";break;case"lookahead":result+="?=";break;case"negativeLookahead":result+="?!";break;default:throw Error("Invalid behaviour: "+node.behaviour)}var body=node.body,length=body?body.length:0;if(length==1){result+=generate(body[0])}else{var i=-1;while(++i<length){result+=generate(body[i])}}result+=")";return result}function generateQuantifier(node){assertType(node.type,"quantifier");var quantifier="",min=node.min,max=node.max;switch(max){case undefined:case null:switch(min){case 0:quantifier="*";break;case 1:quantifier="+";break;default:quantifier="{"+min+",}";break}break;default:if(min==max){quantifier="{"+min+"}"}else if(min==0&&max==1){quantifier="?"}else{quantifier="{"+min+","+max+"}"}break}if(!node.greedy){quantifier+="?"}return generateAtom(node.body[0])+quantifier}function generateReference(node){assertType(node.type,"reference");return"\\"+node.matchIndex}function generateTerm(node){assertType(node.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return generate(node)}function generateValue(node){assertType(node.type,"value");var kind=node.kind,codePoint=node.codePoint;switch(kind){case"controlLetter":return"\\c"+fromCodePoint(codePoint+64);case"hexadecimalEscape":return"\\x"+("00"+codePoint.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+fromCodePoint(codePoint);case"null":return"\\"+codePoint;case"octal":return"\\"+codePoint.toString(8);case"singleEscape":switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+codePoint)}case"symbol":return fromCodePoint(codePoint);case"unicodeEscape":return"\\u"+("0000"+codePoint.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+codePoint.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+kind)}}generate.alternative=generateAlternative;generate.anchor=generateAnchor;generate.characterClass=generateCharacterClass;generate.characterClassEscape=generateCharacterClassEscape;generate.characterClassRange=generateCharacterClassRange;generate.disjunction=generateDisjunction;generate.dot=generateDot;generate.group=generateGroup;generate.quantifier=generateQuantifier;generate.reference=generateReference;generate.value=generateValue;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:generate}})}else if(freeExports&&freeModule){freeExports.generate=generate}else{root.regjsgen={generate:generate}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],111:[function(require,module,exports){(function(){function parse(str,flags){var hasUnicodeFlag=(flags||"").indexOf("u")!==-1;var pos=0;var closedCaptureCounter=0;function addRaw(node){node.raw=str.substring(node.range[0],node.range[1]);return node}function updateRawStart(node,start){node.range[0]=start;return addRaw(node)}function createAnchor(kind,rawLength){return addRaw({type:"anchor",kind:kind,range:[pos-rawLength,pos]})}function createValue(kind,codePoint,from,to){return addRaw({type:"value",kind:kind,codePoint:codePoint,range:[from,to]})}function createEscaped(kind,codePoint,value,fromOffset){fromOffset=fromOffset||0;return createValue(kind,codePoint,pos-(value.length+fromOffset),pos)}function createCharacter(matches){var _char=matches[0];var first=_char.charCodeAt(0);if(hasUnicodeFlag){var second;if(_char.length===1&&first>=55296&&first<=56319){second=lookahead().charCodeAt(0);if(second>=56320&&second<=57343){pos++;return createValue("symbol",(first-55296)*1024+second-56320+65536,pos-2,pos)}}}return createValue("symbol",first,pos-1,pos)}function createDisjunction(alternatives,from,to){return addRaw({type:"disjunction",body:alternatives,range:[from,to]})}function createDot(){return addRaw({type:"dot",range:[pos-1,pos]})}function createCharacterClassEscape(value){return addRaw({type:"characterClassEscape",value:value,range:[pos-2,pos]})}function createReference(matchIndex){return addRaw({type:"reference",matchIndex:parseInt(matchIndex,10),range:[pos-1-matchIndex.length,pos]})}function createGroup(behavior,disjunction,from,to){return addRaw({type:"group",behavior:behavior,body:disjunction,range:[from,to]})}function createQuantifier(min,max,from,to){if(to==null){from=pos-1;to=pos}return addRaw({type:"quantifier",min:min,max:max,greedy:true,body:null,range:[from,to]})}function createAlternative(terms,from,to){return addRaw({type:"alternative",body:terms,range:[from,to]})}function createCharacterClass(classRanges,negative,from,to){return addRaw({type:"characterClass",body:classRanges,negative:negative,range:[from,to]})}function createClassRange(min,max,from,to){if(min.codePoint>max.codePoint){throw SyntaxError("invalid range in character class")}return addRaw({type:"characterClassRange",min:min,max:max,range:[from,to]})}function flattenBody(body){if(body.type==="alternative"){return body.body}else{return[body]}}function isEmpty(obj){return obj.type==="empty"}function incr(amount){amount=amount||1;var res=str.substring(pos,pos+amount);pos+=amount||1;return res}function skip(value){if(!match(value)){throw SyntaxError("character: "+value)}}function match(value){if(str.indexOf(value,pos)===pos){return incr(value.length)}}function lookahead(){return str[pos]}function current(value){return str.indexOf(value,pos)===pos}function next(value){return str[pos+1]===value}function matchReg(regExp){var subStr=str.substring(pos);var res=subStr.match(regExp);if(res){res.range=[];res.range[0]=pos;incr(res[0].length);res.range[1]=pos}return res}function parseDisjunction(){var res=[],from=pos;res.push(parseAlternative());while(match("|")){res.push(parseAlternative())}if(res.length===1){return res[0]}return createDisjunction(res,from,pos)}function parseAlternative(){var res=[],from=pos;var term;while(term=parseTerm()){res.push(term)}if(res.length===1){return res[0]}return createAlternative(res,from,pos)}function parseTerm(){if(pos>=str.length||current("|")||current(")")){return null}var anchor=parseAnchor();if(anchor){return anchor}var atom=parseAtom();if(!atom){throw SyntaxError("Expected atom")}var quantifier=parseQuantifier()||false;if(quantifier){quantifier.body=flattenBody(atom);updateRawStart(quantifier,atom.range[0]);return quantifier}return atom}function parseGroup(matchA,typeA,matchB,typeB){var type=null,from=pos;if(match(matchA)){type=typeA}else if(match(matchB)){type=typeB}else{return false}var body=parseDisjunction();if(!body){throw SyntaxError("Expected disjunction")}skip(")");var group=createGroup(type,flattenBody(body),from,pos);if(type=="normal"){closedCaptureCounter++}return group}function parseAnchor(){var res,from=pos;if(match("^")){return createAnchor("start",1)}else if(match("$")){return createAnchor("end",1)}else if(match("\\b")){return createAnchor("boundary",2)}else if(match("\\B")){return createAnchor("not-boundary",2)}else{return parseGroup("(?=","lookahead","(?!","negativeLookahead")}}function parseQuantifier(){var res;var quantifier;var min,max;if(match("*")){quantifier=createQuantifier(0)}else if(match("+")){quantifier=createQuantifier(1)}else if(match("?")){quantifier=createQuantifier(0,1)}else if(res=matchReg(/^\{([0-9]+)\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,min,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,undefined,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),([0-9]+)\}/)){min=parseInt(res[1],10);max=parseInt(res[2],10);if(min>max){throw SyntaxError("numbers out of order in {} quantifier")}quantifier=createQuantifier(min,max,res.range[0],res.range[1])}if(quantifier){if(match("?")){quantifier.greedy=false;quantifier.range[1]+=1}}return quantifier}function parseAtom(){var res;if(res=matchReg(/^[^^$\\.*+?(){[|]/)){return createCharacter(res)}else if(match(".")){return createDot()}else if(match("\\")){res=parseAtomEscape();if(!res){throw SyntaxError("atomEscape")}return res}else if(res=parseCharacterClass()){return res}else{return parseGroup("(?:","ignore","(","normal")}}function parseUnicodeSurrogatePairEscape(firstEscape){if(hasUnicodeFlag){var first,second;if(firstEscape.kind=="unicodeEscape"&&(first=firstEscape.codePoint)>=55296&&first<=56319&&current("\\")&&next("u")){var prevPos=pos;pos++;var secondEscape=parseClassEscape();if(secondEscape.kind=="unicodeEscape"&&(second=secondEscape.codePoint)>=56320&&second<=57343){firstEscape.range[1]=secondEscape.range[1];firstEscape.codePoint=(first-55296)*1024+second-56320+65536;firstEscape.type="value";firstEscape.kind="unicodeCodePointEscape";addRaw(firstEscape)}else{pos=prevPos}}}return firstEscape}function parseClassEscape(){return parseAtomEscape(true)}function parseAtomEscape(insideCharacterClass){var res;res=parseDecimalEscape();if(res){return res}if(insideCharacterClass){if(match("b")){return createEscaped("singleEscape",8,"\\b")}else if(match("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}res=parseCharacterEscape();return res}function parseDecimalEscape(){var res,match;if(res=matchReg(/^(?!0)\d+/)){match=res[0];var refIdx=parseInt(res[0],10);if(refIdx<=closedCaptureCounter){return createReference(res[0])}else{incr(-res[0].length);if(res=matchReg(/^[0-7]{1,3}/)){return createEscaped("octal",parseInt(res[0],8),res[0],1)}else{res=createCharacter(matchReg(/^[89]/));return updateRawStart(res,res.range[0]-1)}}}else if(res=matchReg(/^[0-7]{1,3}/)){match=res[0];if(/^0{1,3}$/.test(match)){return createEscaped("null",0,"0",match.length+1)}else{return createEscaped("octal",parseInt(match,8),match,1)}}else if(res=matchReg(/^[dDsSwW]/)){return createCharacterClassEscape(res[0])}return false}function parseCharacterEscape(){var res;if(res=matchReg(/^[fnrtv]/)){var codePoint=0;switch(res[0]){case"t":codePoint=9;break;case"n":codePoint=10;break;case"v":codePoint=11;break;case"f":codePoint=12;break;case"r":codePoint=13;break}return createEscaped("singleEscape",codePoint,"\\"+res[0])}else if(res=matchReg(/^c([a-zA-Z])/)){return createEscaped("controlLetter",res[1].charCodeAt(0)%32,res[1],2)}else if(res=matchReg(/^x([0-9a-fA-F]{2})/)){return createEscaped("hexadecimalEscape",parseInt(res[1],16),res[1],2)}else if(res=matchReg(/^u([0-9a-fA-F]{4})/)){return parseUnicodeSurrogatePairEscape(createEscaped("unicodeEscape",parseInt(res[1],16),res[1],2))}else if(hasUnicodeFlag&&(res=matchReg(/^u\{([0-9a-fA-F]{1,6})\}/))){return createEscaped("unicodeCodePointEscape",parseInt(res[1],16),res[1],4)}else{return parseIdentityEscape()}}function isIdentifierPart(ch){var NonAsciiIdentifierPart=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function parseIdentityEscape(){var ZWJ="‌";var ZWNJ="‍";var res;var tmp;if(!isIdentifierPart(lookahead())){tmp=incr();return createEscaped("identifier",tmp.charCodeAt(0),tmp,1)}if(match(ZWJ)){return createEscaped("identifier",8204,ZWJ)}else if(match(ZWNJ)){return createEscaped("identifier",8205,ZWNJ)}return null}function parseCharacterClass(){var res,from=pos;if(res=matchReg(/^\[\^/)){res=parseClassRanges(); skip("]");return createCharacterClass(res,true,from,pos)}else if(match("[")){res=parseClassRanges();skip("]");return createCharacterClass(res,false,from,pos)}return null}function parseClassRanges(){var res;if(current("]")){return[]}else{res=parseNonemptyClassRanges();if(!res){throw SyntaxError("nonEmptyClassRanges")}return res}}function parseHelperClassRanges(atom){var from,to,res;if(current("-")&&!next("]")){skip("-");res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}to=pos;var classRanges=parseClassRanges();if(!classRanges){throw SyntaxError("classRanges")}from=atom.range[0];if(classRanges.type==="empty"){return[createClassRange(atom,res,from,to)]}return[createClassRange(atom,res,from,to)].concat(classRanges)}res=parseNonemptyClassRangesNoDash();if(!res){throw SyntaxError("nonEmptyClassRangesNoDash")}return[atom].concat(res)}function parseNonemptyClassRanges(){var atom=parseClassAtom();if(!atom){throw SyntaxError("classAtom")}if(current("]")){return[atom]}return parseHelperClassRanges(atom)}function parseNonemptyClassRangesNoDash(){var res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}if(current("]")){return res}return parseHelperClassRanges(res)}function parseClassAtom(){if(match("-")){return createCharacter("-")}else{return parseClassAtomNoDash()}}function parseClassAtomNoDash(){var res;if(res=matchReg(/^[^\\\]-]/)){return createCharacter(res[0])}else if(match("\\")){res=parseClassEscape();if(!res){throw SyntaxError("classEscape")}return parseUnicodeSurrogatePairEscape(res)}}str=String(str);if(str===""){str="(?:)"}var result=parseDisjunction();if(result.range[1]!==str.length){throw SyntaxError("Could not parse entire input - got stuck: "+str)}return result}var regjsparser={parse:parse};if(typeof module!=="undefined"&&module.exports){module.exports=regjsparser}else{window.regjsparser=regjsparser}})()},{}],112:[function(require,module,exports){var generate=require("regjsgen").generate;var parse=require("regjsparser").parse;var regenerate=require("regenerate");var iuMappings=require("./data/iu-mappings.json");var ESCAPE_SETS=require("./data/character-class-escape-sets.js");function getCharacterClassEscapeSet(character){if(unicode){if(ignoreCase){return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]}return ESCAPE_SETS.UNICODE[character]}return ESCAPE_SETS.REGULAR[character]}var object={};var hasOwnProperty=object.hasOwnProperty;function has(object,property){return hasOwnProperty.call(object,property)}var UNICODE_SET=regenerate().addRange(0,1114111);var BMP_SET=regenerate().addRange(0,65535);var DOT_SET_UNICODE=UNICODE_SET.clone().remove(10,13,8232,8233);var DOT_SET=DOT_SET_UNICODE.clone().intersection(BMP_SET);regenerate.prototype.iuAddRange=function(min,max){var $this=this;do{var folded=caseFold(min);if(folded){$this.add(folded)}}while(++min<=max);return $this};function assign(target,source){for(var key in source){target[key]=source[key]}}function update(item,pattern){var tree=parse(pattern,"");switch(tree.type){case"characterClass":case"group":case"value":break;default:tree=wrap(tree,pattern)}assign(item,tree)}function wrap(tree,pattern){return{type:"group",behavior:"ignore",body:[tree],raw:"(?:"+pattern+")"}}function caseFold(codePoint){return has(iuMappings,codePoint)?iuMappings[codePoint]:false}var ignoreCase=false;var unicode=false;function processCharacterClass(characterClassItem){var set=regenerate();var body=characterClassItem.body.forEach(function(item){switch(item.type){case"value":set.add(item.codePoint);if(ignoreCase&&unicode){var folded=caseFold(item.codePoint);if(folded){set.add(folded)}}break;case"characterClassRange":var min=item.min.codePoint;var max=item.max.codePoint;set.addRange(min,max);if(ignoreCase&&unicode){set.iuAddRange(min,max)}break;case"characterClassEscape":set.add(getCharacterClassEscapeSet(item.value));break;default:throw Error("Unknown term type: "+item.type)}});if(characterClassItem.negative){set=(unicode?UNICODE_SET:BMP_SET).clone().remove(set)}update(characterClassItem,set.toString());return characterClassItem}function processTerm(item){switch(item.type){case"dot":update(item,(unicode?DOT_SET_UNICODE:DOT_SET).toString());break;case"characterClass":item=processCharacterClass(item);break;case"characterClassEscape":update(item,getCharacterClassEscapeSet(item.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":item.body=item.body.map(processTerm);break;case"value":var codePoint=item.codePoint;var set=regenerate(codePoint);if(ignoreCase&&unicode){var folded=caseFold(codePoint);if(folded){set.add(folded)}}update(item,set.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+item.type)}return item}module.exports=function(pattern,flags){var tree=parse(pattern,flags);ignoreCase=flags?flags.indexOf("i")>-1:false;unicode=flags?flags.indexOf("u")>-1:false;assign(tree,processTerm(tree));return generate(tree)}},{"./data/character-class-escape-sets.js":107,"./data/iu-mappings.json":108,regenerate:109,regjsgen:110,regjsparser:111}],113:[function(require,module,exports){exports.SourceMapGenerator=require("./source-map/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./source-map/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":118,"./source-map/source-map-generator":119,"./source-map/source-node":120}],114:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function ArraySet(){this._array=[];this._set={}}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var isDuplicate=this.has(aStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){this._set[util.toSetString(aStr)]=idx}};ArraySet.prototype.has=function ArraySet_has(aStr){return Object.prototype.hasOwnProperty.call(this._set,util.toSetString(aStr))};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(this.has(aStr)){return this._set[util.toSetString(aStr)]}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet})},{"./util":121,amdefine:122}],115:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aOutParam){var i=0;var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(i>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charAt(i++));continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aStr.slice(i)}})},{"./base64":116,amdefine:122}],116:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var charToIntMap={};var intToCharMap={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(ch,index){charToIntMap[ch]=index;intToCharMap[index]=ch});exports.encode=function base64_encode(aNumber){if(aNumber in intToCharMap){return intToCharMap[aNumber]}throw new TypeError("Must be between 0 and 63: "+aNumber)};exports.decode=function base64_decode(aChar){if(aChar in charToIntMap){return charToIntMap[aChar]}throw new TypeError("Not a valid base 64 digit: "+aChar)}})},{amdefine:122}],117:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return aHaystack[mid]}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare)}return aHaystack[mid]}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare)}return aLow<0?null:aHaystack[aLow]}}exports.search=function search(aNeedle,aHaystack,aCompare){return aHaystack.length>0?recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare):null}})},{amdefine:122}],118:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}this._names=ArraySet.fromArray(names,true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}SourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(SourceMapConsumer.prototype);smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;smc.__generatedMappings=aSourceMap._mappings.slice().sort(util.compareByGeneratedPositions);smc.__originalMappings=aSourceMap._mappings.slice().sort(util.compareByOriginalPositions);return smc};SourceMapConsumer.prototype._version=3;Object.defineProperty(SourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._nextCharIsMappingSeparator=function SourceMapConsumer_nextCharIsMappingSeparator(aStr){var c=aStr.charAt(0);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var str=aStr;var temp={};var mapping;while(str.length>0){if(str.charAt(0)===";"){generatedLine++;str=str.slice(1);previousGeneratedColumn=0}else if(str.charAt(0)===","){str=str.slice(1)}else{mapping={};mapping.generatedLine=generatedLine;base64VLQ.decode(str,temp);mapping.generatedColumn=previousGeneratedColumn+temp.value;previousGeneratedColumn=mapping.generatedColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.source=this._sources.at(previousSource+temp.value);previousSource+=temp.value;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source, but no line and column")}base64VLQ.decode(str,temp);mapping.originalLine=previousOriginalLine+temp.value;previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source and line, but no column")}base64VLQ.decode(str,temp);mapping.originalColumn=previousOriginalColumn+temp.value;previousOriginalColumn=mapping.originalColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.name=this._names.at(previousName+temp.value);previousName+=temp.value;str=temp.rest}}this.__generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){this.__originalMappings.push(mapping)}}}this.__generatedMappings.sort(util.compareByGeneratedPositions);this.__originalMappings.sort(util.compareByOriginalPositions)};SourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName])}if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator)};SourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var mapping=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositions);if(mapping&&mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!=null&&this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:util.getArg(mapping,"name",null)}}return{source:null,line:null,column:null,name:null}};SourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}throw new Error('"'+aSource+'" is not in the SourceMap.')};SourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var mapping=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(mapping){return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null)}}return{line:null,column:null}};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source;if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name}}).forEach(aCallback,context)};exports.SourceMapConsumer=SourceMapConsumer})},{"./array-set":114,"./base64-vlq":115,"./binary-search":117,"./util":121,amdefine:122}],119:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=[];this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);this._validateMapping(generated,original,source,name);if(source!=null&&!this._sources.has(source)){this._sources.add(source)}if(name!=null&&!this._names.has(name)){this._names.add(name)}this._mappings.push({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.forEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var mapping;this._mappings.sort(util.compareByGeneratedPositions);for(var i=0,len=this._mappings.length;i<len;i++){mapping=this._mappings[i];if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){result+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositions(mapping,this._mappings[i-1])){continue}result+=","}}result+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){result+=base64VLQ.encode(this._sources.indexOf(mapping.source)-previousSource);previousSource=this._sources.indexOf(mapping.source);result+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;result+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){result+=base64VLQ.encode(this._names.indexOf(mapping.name)-previousName);previousName=this._names.indexOf(mapping.name)}}}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null}if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this)};exports.SourceMapGenerator=SourceMapGenerator})},{"./array-set":114,"./base64-vlq":115,"./util":121,amdefine:122}],120:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var REGEX_CHARACTER=/\r\n|[\s\S]/g;function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var shiftNextLine=function(){var lineContents=remainingLines.shift();var newLine=remainingLines.shift()||"";return lineContents+newLine};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){var code="";addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[0];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[0]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[0];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[0]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLines.length>0){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk instanceof SourceNode){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild instanceof SourceNode){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i]instanceof SourceNode){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}chunk.match(REGEX_CHARACTER).forEach(function(ch,idx,array){if(REGEX_NEWLINE.test(ch)){generated.line++;generated.column=0;if(idx+1===array.length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column+=ch.length}})});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode})},{"./source-map-generator":119,"./util":121,amdefine:122}],121:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":" }url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=path.charAt(0)==="/";var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var url=urlParse(aRoot);if(aPath.charAt(0)=="/"&&url&&url.path=="/"){return aPath.slice(1)}return aPath.indexOf(aRoot+"/")===0?aPath.substr(aRoot.length+1):aPath}exports.relative=relative;function toSetString(aStr){return"$"+aStr}exports.toSetString=toSetString;function fromSetString(aStr){return aStr.substr(1)}exports.fromSetString=fromSetString;function strcmp(aStr1,aStr2){var s1=aStr1||"";var s2=aStr2||"";return(s1>s2)-(s1<s2)}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp;cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp||onlyCompareOriginal){return cmp}cmp=strcmp(mappingA.name,mappingB.name);if(cmp){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}return mappingA.generatedColumn-mappingB.generatedColumn}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositions(mappingA,mappingB,onlyCompareGenerated){var cmp;cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp||onlyCompareGenerated){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositions=compareByGeneratedPositions})},{amdefine:122}],122:[function(require,module,exports){(function(process,__filename){"use strict";function amdefine(module,requireFn){"use strict";var defineCache={},loaderCache={},alreadyCalled=false,path=require("path"),makeRequire,stringRequire;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part===".."){if(i===1&&(ary[2]===".."||ary[0]==="..")){break}else if(i>0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName){var baseParts;if(name&&name.charAt(0)==="."){if(baseName){baseParts=baseName.split("/");baseParts=baseParts.slice(0,baseParts.length-1);baseParts=baseParts.concat(name.split("/"));trimDots(baseParts);name=baseParts.join("/")}}return name}function makeNormalize(relName){return function(name){return normalize(name,relName)}}function makeLoad(id){function load(value){loaderCache[id]=value}load.fromText=function(id,text){throw new Error("amdefine does not implement load.fromText")};return load}makeRequire=function(systemRequire,exports,module,relId){function amdRequire(deps,callback){if(typeof deps==="string"){return stringRequire(systemRequire,exports,module,deps,relId)}else{deps=deps.map(function(depName){return stringRequire(systemRequire,exports,module,depName,relId)});process.nextTick(function(){callback.apply(null,deps)})}}amdRequire.toUrl=function(filePath){if(filePath.indexOf(".")===0){return normalize(filePath,path.dirname(module.filename))}else{return filePath}};return amdRequire};requireFn=requireFn||function req(){return module.require.apply(module,arguments)};function runFactory(id,deps,factory){var r,e,m,result;if(id){e=loaderCache[id]={};m={id:id,uri:__filename,exports:e};r=makeRequire(requireFn,e,m,id)}else{if(alreadyCalled){throw new Error("amdefine with no module ID cannot be called more than once per file.")}alreadyCalled=true;e=module.exports;m=module;r=makeRequire(requireFn,e,m,module.id)}if(deps){deps=deps.map(function(depName){return r(depName)})}if(typeof factory==="function"){result=factory.apply(m.exports,deps)}else{result=factory}if(result!==undefined){m.exports=result;if(id){loaderCache[id]=m.exports}}}stringRequire=function(systemRequire,exports,module,id,relId){var index=id.indexOf("!"),originalId=id,prefix,plugin;if(index===-1){id=normalize(id,relId);if(id==="require"){return makeRequire(systemRequire,exports,module,relId)}else if(id==="exports"){return exports}else if(id==="module"){return module}else if(loaderCache.hasOwnProperty(id)){return loaderCache[id]}else if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}else{if(systemRequire){return systemRequire(originalId)}else{throw new Error("No module with ID: "+id)}}}else{prefix=id.substring(0,index);id=id.substring(index+1,id.length);plugin=stringRequire(systemRequire,exports,module,prefix,relId);if(plugin.normalize){id=plugin.normalize(id,makeNormalize(relId))}else{id=normalize(id,relId)}if(loaderCache[id]){return loaderCache[id]}else{plugin.load(id,makeRequire(systemRequire,exports,module,relId),makeLoad(id),{});return loaderCache[id]}}};function define(id,deps,factory){if(Array.isArray(id)){factory=deps;deps=id;id=undefined}else if(typeof id!=="string"){factory=id;id=deps=undefined}if(deps&&!Array.isArray(deps)){factory=deps;deps=undefined}if(!deps){deps=["require","exports","module"]}if(id){defineCache[id]=[id,deps,factory]}else{runFactory(id,deps,factory)}}define.require=function(id){if(loaderCache[id]){return loaderCache[id]}if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}};define.amd={};return define}module.exports=amdefine}).call(this,require("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:97,path:96}],123:[function(require,module,exports){module.exports={"abstract-expression-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-delete":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceDelete"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-get":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-set":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceSet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"VALUE"}]}}]},"apply-constructor":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"Constructor"},{type:"Identifier",name:"args"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"instance"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"prototype"},computed:false}]}}],kind:"var"},{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"result"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"Identifier",name:"instance"},{type:"Identifier",name:"args"}]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"Identifier",name:"result"},operator:"!=",right:{type:"Literal",value:null}},operator:"&&",right:{type:"ParenthesizedExpression",expression:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"object"}},operator:"||",right:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"function"}}}}},consequent:{type:"Identifier",name:"result"},alternate:{type:"Identifier",name:"instance"}}}]},expression:false}}}]},"arguments-to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"args"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"target"},init:{type:"NewExpression",callee:{type:"Identifier",name:"Array"},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"args"},property:{type:"Identifier",name:"length"},computed:false}]}}],kind:"var"},{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:{type:"Literal",value:0}}],kind:"var"},test:{type:"BinaryExpression",left:{type:"Identifier",name:"i"},operator:"<",right:{type:"MemberExpression",object:{type:"Identifier",name:"args"},property:{type:"Identifier",name:"length"},computed:false}},update:{type:"UpdateExpression",operator:"++",prefix:false,argument:{type:"Identifier",name:"i"}},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"target"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"args"},property:{type:"Identifier",name:"i"},computed:true}}}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"target"}}]},expression:false}}}]},"array-comprehension-container":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"KEY"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[]}}]},"array-comprehension-for-each":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"forEach"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}]}}]},"array-expression-comprehension-filter":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"filter"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"FILTER"}}]},expression:false}]},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}]},expression:false}]}}]},"array-expression-comprehension-map":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}]},expression:false}]}}]},"array-from":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"VALUE"}]}}]},"array-push":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"KEY"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"Identifier",name:"STATEMENT"}]}}]},call:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"CONTEXT"}]}}]},"class-props":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"},{type:"Identifier",name:"instanceProps"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"Identifier",name:"staticProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"}]}},alternate:null},{type:"IfStatement",test:{type:"Identifier",name:"instanceProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"Identifier",name:"instanceProps"}]}},alternate:null}]},expression:false}}}]},"class-super-constructor-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SUPER_NAME"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}]},"class":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"CLASS_NAME"},init:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"CLASS_NAME"}}]},expression:false}},arguments:[]}}]},"exports-assign-key":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"VARIABLE_NAME"},computed:false},right:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"KEY"},computed:false}}}]},"exports-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"KEY"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default-module":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"default"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-wildcard":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"extends":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"parent"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"parent"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"constructor"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"child"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"enumerable"},value:{type:"Literal",value:false},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"writable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"configurable"},value:{type:"Literal",value:true},kind:"init"}]},kind:"init"}]}]}}},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"__proto__"},computed:false},right:{type:"Identifier",name:"parent"}}}]},expression:false}}}]},"for-of":{type:"Program",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"ITERATOR_KEY"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"STEP_KEY"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"ParenthesizedExpression",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"STEP_KEY"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ITERATOR_KEY"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[]}}]},"function-return-obj":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"if-undefined-set-to":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"VARIABLE"},operator:"===",right:{type:"Identifier",name:"undefined"}},consequent:{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"VARIABLE"},right:{type:"Identifier",name:"DEFAULT"}}},alternate:null}]},"interop-require":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"LogicalExpression",left:{type:"Identifier",name:"obj"},operator:"&&",right:{type:"ParenthesizedExpression",expression:{type:"LogicalExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Literal",value:"default"},computed:true},operator:"||",right:{type:"Identifier",name:"obj"}}}}}]},expression:false}}}]},"let-scoping-return":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"RETURN"}},operator:"===",right:{type:"Literal",value:"object"}},consequent:{type:"ReturnStatement",argument:{type:"MemberExpression",object:{type:"Identifier",name:"RETURN"},property:{type:"Identifier",name:"v"},computed:false}},alternate:null}]},"object-define-properties-closure":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"Identifier",name:"CONTENT"}},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"object-define-properties":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"PROPS"}]}}]},"object-spread":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"keys"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"target"},init:{type:"ObjectExpression",properties:[]}}],kind:"var"},{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"keys"},property:{type:"Identifier",name:"indexOf"},computed:false},arguments:[{type:"Identifier",name:"i"}]},operator:">=",right:{type:"Literal",value:0}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"hasOwnProperty"},computed:false},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"i"}]}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"target"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"target"}}]},expression:false}}}]},"prototype-identifier":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"Identifier",name:"CLASS_NAME"},property:{type:"Identifier",name:"prototype"},computed:false}}]},register:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"System"},property:{type:"Identifier",name:"register"},computed:false},arguments:[{type:"Identifier",name:"MODULE_NAME"},{type:"Identifier",name:"MODULE_DEPENDENCIES"},{type:"Identifier",name:"MODULE_BODY"}]}}]},"require-assign-key":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]},property:{type:"Identifier",name:"KEY"},computed:false}}],kind:"var"}]},"require-assign":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}],kind:"var"}]},require:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}]},"self-global":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ConditionalExpression",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"global"}},operator:"===",right:{type:"Literal",value:"undefined"}},consequent:{type:"Identifier",name:"self"},alternate:{type:"Identifier",name:"global"}}}]},"tagged-template-literal":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"strings"},{type:"Identifier",name:"raw"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"strings"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"raw"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"raw"},kind:"init"}]},kind:"init"}]}]}}]},expression:false}}}]},"to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"arr"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"isArray"},computed:false},arguments:[{type:"Identifier",name:"arr"}]},consequent:{type:"Identifier",name:"arr"},alternate:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"arr"}]}}}]},expression:false}}}]},"umd-runner-body":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"factory"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"define"}},operator:"===",right:{type:"Literal",value:"function"}},operator:"&&",right:{type:"MemberExpression",object:{type:"Identifier",name:"define"},property:{type:"Identifier",name:"amd"},computed:false}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"define"},arguments:[{type:"Identifier",name:"AMD_ARGUMENTS"},{type:"Identifier",name:"factory"}]}}]},alternate:{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"exports"}},operator:"!==",right:{type:"Literal",value:"undefined"}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"factory"},arguments:[{type:"Identifier",name:"exports"},{type:"Identifier",name:"COMMON_ARGUMENTS"}]}}]},alternate:null}}]},expression:false}}}]}} },{}]},{},[2])(2)});
examples/todos-with-undo/src/containers/AddTodo.js
lifeiscontent/redux
import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../actions' let AddTodo = ({ dispatch }) => { let input return ( <div> <form onSubmit={e => { e.preventDefault() if (!input.value.trim()) { return } dispatch(addTodo(input.value)) input.value = '' }}> <input ref={node => { input = node }} /> <button type="submit"> Add Todo </button> </form> </div> ) } AddTodo = connect()(AddTodo) export default AddTodo
src/svg-icons/editor/text-fields.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorTextFields = (props) => ( <SvgIcon {...props}> <path d="M2.5 4v3h5v12h3V7h5V4h-13zm19 5h-9v3h3v7h3v-7h3V9z"/> </SvgIcon> ); EditorTextFields = pure(EditorTextFields); EditorTextFields.displayName = 'EditorTextFields'; EditorTextFields.muiName = 'SvgIcon'; export default EditorTextFields;
ajax/libs/polymer/0.5.3-rc/polymer.js
noraesae/cdnjs
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // @version 0.5.3 window.PolymerGestures = {}; (function(scope) { var hasFullPath = false; // test for full event path support var pathTest = document.createElement('meta'); if (pathTest.createShadowRoot) { var sr = pathTest.createShadowRoot(); var s = document.createElement('span'); sr.appendChild(s); pathTest.addEventListener('testpath', function(ev) { if (ev.path) { // if the span is in the event path, then path[0] is the real source for all events hasFullPath = ev.path[0] === s; } ev.stopPropagation(); }); var ev = new CustomEvent('testpath', {bubbles: true}); // must add node to DOM to trigger event listener document.head.appendChild(pathTest); s.dispatchEvent(ev); pathTest.parentNode.removeChild(pathTest); sr = s = null; } pathTest = null; var target = { shadow: function(inEl) { if (inEl) { return inEl.shadowRoot || inEl.webkitShadowRoot; } }, canTarget: function(shadow) { return shadow && Boolean(shadow.elementFromPoint); }, targetingShadow: function(inEl) { var s = this.shadow(inEl); if (this.canTarget(s)) { return s; } }, olderShadow: function(shadow) { var os = shadow.olderShadowRoot; if (!os) { var se = shadow.querySelector('shadow'); if (se) { os = se.olderShadowRoot; } } return os; }, allShadows: function(element) { var shadows = [], s = this.shadow(element); while(s) { shadows.push(s); s = this.olderShadow(s); } return shadows; }, searchRoot: function(inRoot, x, y) { var t, st, sr, os; if (inRoot) { t = inRoot.elementFromPoint(x, y); if (t) { // found element, check if it has a ShadowRoot sr = this.targetingShadow(t); } else if (inRoot !== document) { // check for sibling roots sr = this.olderShadow(inRoot); } // search other roots, fall back to light dom element return this.searchRoot(sr, x, y) || t; } }, owner: function(element) { if (!element) { return document; } var s = element; // walk up until you hit the shadow root or document while (s.parentNode) { s = s.parentNode; } // the owner element is expected to be a Document or ShadowRoot if (s.nodeType != Node.DOCUMENT_NODE && s.nodeType != Node.DOCUMENT_FRAGMENT_NODE) { s = document; } return s; }, findTarget: function(inEvent) { if (hasFullPath && inEvent.path && inEvent.path.length) { return inEvent.path[0]; } var x = inEvent.clientX, y = inEvent.clientY; // if the listener is in the shadow root, it is much faster to start there var s = this.owner(inEvent.target); // if x, y is not in this root, fall back to document search if (!s.elementFromPoint(x, y)) { s = document; } return this.searchRoot(s, x, y); }, findTouchAction: function(inEvent) { var n; if (hasFullPath && inEvent.path && inEvent.path.length) { var path = inEvent.path; for (var i = 0; i < path.length; i++) { n = path[i]; if (n.nodeType === Node.ELEMENT_NODE && n.hasAttribute('touch-action')) { return n.getAttribute('touch-action'); } } } else { n = inEvent.target; while(n) { if (n.nodeType === Node.ELEMENT_NODE && n.hasAttribute('touch-action')) { return n.getAttribute('touch-action'); } n = n.parentNode || n.host; } } // auto is default return "auto"; }, LCA: function(a, b) { if (a === b) { return a; } if (a && !b) { return a; } if (b && !a) { return b; } if (!b && !a) { return document; } // fast case, a is a direct descendant of b or vice versa if (a.contains && a.contains(b)) { return a; } if (b.contains && b.contains(a)) { return b; } var adepth = this.depth(a); var bdepth = this.depth(b); var d = adepth - bdepth; if (d >= 0) { a = this.walk(a, d); } else { b = this.walk(b, -d); } while (a && b && a !== b) { a = a.parentNode || a.host; b = b.parentNode || b.host; } return a; }, walk: function(n, u) { for (var i = 0; n && (i < u); i++) { n = n.parentNode || n.host; } return n; }, depth: function(n) { var d = 0; while(n) { d++; n = n.parentNode || n.host; } return d; }, deepContains: function(a, b) { var common = this.LCA(a, b); // if a is the common ancestor, it must "deeply" contain b return common === a; }, insideNode: function(node, x, y) { var rect = node.getBoundingClientRect(); return (rect.left <= x) && (x <= rect.right) && (rect.top <= y) && (y <= rect.bottom); }, path: function(event) { var p; if (hasFullPath && event.path && event.path.length) { p = event.path; } else { p = []; var n = this.findTarget(event); while (n) { p.push(n); n = n.parentNode || n.host; } } return p; } }; scope.targetFinding = target; /** * Given an event, finds the "deepest" node that could have been the original target before ShadowDOM retargetting * * @param {Event} Event An event object with clientX and clientY properties * @return {Element} The probable event origninator */ scope.findTarget = target.findTarget.bind(target); /** * Determines if the "container" node deeply contains the "containee" node, including situations where the "containee" is contained by one or more ShadowDOM * roots. * * @param {Node} container * @param {Node} containee * @return {Boolean} */ scope.deepContains = target.deepContains.bind(target); /** * Determines if the x/y position is inside the given node. * * Example: * * function upHandler(event) { * var innode = PolymerGestures.insideNode(event.target, event.clientX, event.clientY); * if (innode) { * // wait for tap? * } else { * // tap will never happen * } * } * * @param {Node} node * @param {Number} x Screen X position * @param {Number} y screen Y position * @return {Boolean} */ scope.insideNode = target.insideNode; })(window.PolymerGestures); (function() { function shadowSelector(v) { return 'html /deep/ ' + selector(v); } function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + ';}'; } var attrib2css = [ 'none', 'auto', 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'pan-x pan-y', 'pan-y pan-x' ] }, 'manipulation' ]; var styles = ''; // only install stylesheet if the browser has touch action support var hasTouchAction = typeof document.head.style.touchAction === 'string'; // only add shadow selectors if shadowdom is supported var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot; if (hasTouchAction) { attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r) + '\n'; if (hasShadowRoot) { styles += shadowSelector(r) + rule(r) + '\n'; } } else { styles += r.selectors.map(selector) + rule(r.rule) + '\n'; if (hasShadowRoot) { styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n'; } } }); var el = document.createElement('style'); el.textContent = styles; document.head.appendChild(el); } })(); /** * This is the constructor for new PointerEvents. * * New Pointer Events must be given a type, and an optional dictionary of * initialization properties. * * Due to certain platform requirements, events returned from the constructor * identify as MouseEvents. * * @constructor * @param {String} inType The type of the event to create. * @param {Object} [inDict] An optional dictionary of initial event properties. * @return {Event} A new PointerEvent of type `inType` and initialized with properties from `inDict`. */ (function(scope) { var MOUSE_PROPS = [ 'bubbles', 'cancelable', 'view', 'detail', 'screenX', 'screenY', 'clientX', 'clientY', 'ctrlKey', 'altKey', 'shiftKey', 'metaKey', 'button', 'relatedTarget', 'pageX', 'pageY' ]; var MOUSE_DEFAULTS = [ false, false, null, null, 0, 0, 0, 0, false, false, false, false, 0, null, 0, 0 ]; var NOP_FACTORY = function(){ return function(){}; }; var eventFactory = { // TODO(dfreedm): this is overridden by tap recognizer, needs review preventTap: NOP_FACTORY, makeBaseEvent: function(inType, inDict) { var e = document.createEvent('Event'); e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false); e.preventTap = eventFactory.preventTap(e); return e; }, makeGestureEvent: function(inType, inDict) { inDict = inDict || Object.create(null); var e = this.makeBaseEvent(inType, inDict); for (var i = 0, keys = Object.keys(inDict), k; i < keys.length; i++) { k = keys[i]; e[k] = inDict[k]; } return e; }, makePointerEvent: function(inType, inDict) { inDict = inDict || Object.create(null); var e = this.makeBaseEvent(inType, inDict); // define inherited MouseEvent properties for(var i = 0, p; i < MOUSE_PROPS.length; i++) { p = MOUSE_PROPS[i]; e[p] = inDict[p] || MOUSE_DEFAULTS[i]; } e.buttons = inDict.buttons || 0; // Spec requires that pointers without pressure specified use 0.5 for down // state and 0 for up state. var pressure = 0; if (inDict.pressure) { pressure = inDict.pressure; } else { pressure = e.buttons ? 0.5 : 0; } // add x/y properties aliased to clientX/Y e.x = e.clientX; e.y = e.clientY; // define the properties of the PointerEvent interface e.pointerId = inDict.pointerId || 0; e.width = inDict.width || 0; e.height = inDict.height || 0; e.pressure = pressure; e.tiltX = inDict.tiltX || 0; e.tiltY = inDict.tiltY || 0; e.pointerType = inDict.pointerType || ''; e.hwTimestamp = inDict.hwTimestamp || 0; e.isPrimary = inDict.isPrimary || false; e._source = inDict._source || ''; return e; } }; scope.eventFactory = eventFactory; })(window.PolymerGestures); /** * This module implements an map of pointer states */ (function(scope) { var USE_MAP = window.Map && window.Map.prototype.forEach; var POINTERS_FN = function(){ return this.size; }; function PointerMap() { if (USE_MAP) { var m = new Map(); m.pointers = POINTERS_FN; return m; } else { this.keys = []; this.values = []; } } PointerMap.prototype = { set: function(inId, inEvent) { var i = this.keys.indexOf(inId); if (i > -1) { this.values[i] = inEvent; } else { this.keys.push(inId); this.values.push(inEvent); } }, has: function(inId) { return this.keys.indexOf(inId) > -1; }, 'delete': function(inId) { var i = this.keys.indexOf(inId); if (i > -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } }, get: function(inId) { var i = this.keys.indexOf(inId); return this.values[i]; }, clear: function() { this.keys.length = 0; this.values.length = 0; }, // return value, key, map forEach: function(callback, thisArg) { this.values.forEach(function(v, i) { callback.call(thisArg, v, this.keys[i], this); }, this); }, pointers: function() { return this.keys.length; } }; scope.PointerMap = PointerMap; })(window.PolymerGestures); (function(scope) { var CLONE_PROPS = [ // MouseEvent 'bubbles', 'cancelable', 'view', 'detail', 'screenX', 'screenY', 'clientX', 'clientY', 'ctrlKey', 'altKey', 'shiftKey', 'metaKey', 'button', 'relatedTarget', // DOM Level 3 'buttons', // PointerEvent 'pointerId', 'width', 'height', 'pressure', 'tiltX', 'tiltY', 'pointerType', 'hwTimestamp', 'isPrimary', // event instance 'type', 'target', 'currentTarget', 'which', 'pageX', 'pageY', 'timeStamp', // gesture addons 'preventTap', 'tapPrevented', '_source' ]; var CLONE_DEFAULTS = [ // MouseEvent false, false, null, null, 0, 0, 0, 0, false, false, false, false, 0, null, // DOM Level 3 0, // PointerEvent 0, 0, 0, 0, 0, 0, '', 0, false, // event instance '', null, null, 0, 0, 0, 0, function(){}, false ]; var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined'); var eventFactory = scope.eventFactory; // set of recognizers to run for the currently handled event var currentGestures; /** * This module is for normalizing events. Mouse and Touch events will be * collected here, and fire PointerEvents that have the same semantics, no * matter the source. * Events fired: * - pointerdown: a pointing is added * - pointerup: a pointer is removed * - pointermove: a pointer is moved * - pointerover: a pointer crosses into an element * - pointerout: a pointer leaves an element * - pointercancel: a pointer will no longer generate events */ var dispatcher = { IS_IOS: false, pointermap: new scope.PointerMap(), requiredGestures: new scope.PointerMap(), eventMap: Object.create(null), // Scope objects for native events. // This exists for ease of testing. eventSources: Object.create(null), eventSourceList: [], gestures: [], // map gesture event -> {listeners: int, index: gestures[int]} dependencyMap: { // make sure down and up are in the map to trigger "register" down: {listeners: 0, index: -1}, up: {listeners: 0, index: -1} }, gestureQueue: [], /** * Add a new event source that will generate pointer events. * * `inSource` must contain an array of event names named `events`, and * functions with the names specified in the `events` array. * @param {string} name A name for the event source * @param {Object} source A new source of platform events. */ registerSource: function(name, source) { var s = source; var newEvents = s.events; if (newEvents) { newEvents.forEach(function(e) { if (s[e]) { this.eventMap[e] = s[e].bind(s); } }, this); this.eventSources[name] = s; this.eventSourceList.push(s); } }, registerGesture: function(name, source) { var obj = Object.create(null); obj.listeners = 0; obj.index = this.gestures.length; for (var i = 0, g; i < source.exposes.length; i++) { g = source.exposes[i].toLowerCase(); this.dependencyMap[g] = obj; } this.gestures.push(source); }, register: function(element, initial) { var l = this.eventSourceList.length; for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { // call eventsource register es.register.call(es, element, initial); } }, unregister: function(element) { var l = this.eventSourceList.length; for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { // call eventsource register es.unregister.call(es, element); } }, // EVENTS down: function(inEvent) { this.requiredGestures.set(inEvent.pointerId, currentGestures); this.fireEvent('down', inEvent); }, move: function(inEvent) { // pipe move events into gesture queue directly inEvent.type = 'move'; this.fillGestureQueue(inEvent); }, up: function(inEvent) { this.fireEvent('up', inEvent); this.requiredGestures.delete(inEvent.pointerId); }, cancel: function(inEvent) { inEvent.tapPrevented = true; this.fireEvent('up', inEvent); this.requiredGestures.delete(inEvent.pointerId); }, addGestureDependency: function(node, currentGestures) { var gesturesWanted = node._pgEvents; if (gesturesWanted && currentGestures) { var gk = Object.keys(gesturesWanted); for (var i = 0, r, ri, g; i < gk.length; i++) { // gesture g = gk[i]; if (gesturesWanted[g] > 0) { // lookup gesture recognizer r = this.dependencyMap[g]; // recognizer index ri = r ? r.index : -1; currentGestures[ri] = true; } } } }, // LISTENER LOGIC eventHandler: function(inEvent) { // This is used to prevent multiple dispatch of events from // platform events. This can happen when two elements in different scopes // are set up to create pointer events, which is relevant to Shadow DOM. var type = inEvent.type; // only generate the list of desired events on "down" if (type === 'touchstart' || type === 'mousedown' || type === 'pointerdown' || type === 'MSPointerDown') { if (!inEvent._handledByPG) { currentGestures = {}; } // in IOS mode, there is only a listener on the document, so this is not re-entrant if (this.IS_IOS) { var ev = inEvent; if (type === 'touchstart') { var ct = inEvent.changedTouches[0]; // set up a fake event to give to the path builder ev = {target: inEvent.target, clientX: ct.clientX, clientY: ct.clientY, path: inEvent.path}; } // use event path if available, otherwise build a path from target finding var nodes = inEvent.path || scope.targetFinding.path(ev); for (var i = 0, n; i < nodes.length; i++) { n = nodes[i]; this.addGestureDependency(n, currentGestures); } } else { this.addGestureDependency(inEvent.currentTarget, currentGestures); } } if (inEvent._handledByPG) { return; } var fn = this.eventMap && this.eventMap[type]; if (fn) { fn(inEvent); } inEvent._handledByPG = true; }, // set up event listeners listen: function(target, events) { for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) { this.addEvent(target, e); } }, // remove event listeners unlisten: function(target, events) { for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) { this.removeEvent(target, e); } }, addEvent: function(target, eventName) { target.addEventListener(eventName, this.boundHandler); }, removeEvent: function(target, eventName) { target.removeEventListener(eventName, this.boundHandler); }, // EVENT CREATION AND TRACKING /** * Creates a new Event of type `inType`, based on the information in * `inEvent`. * * @param {string} inType A string representing the type of event to create * @param {Event} inEvent A platform event with a target * @return {Event} A PointerEvent of type `inType` */ makeEvent: function(inType, inEvent) { var e = eventFactory.makePointerEvent(inType, inEvent); e.preventDefault = inEvent.preventDefault; e.tapPrevented = inEvent.tapPrevented; e._target = e._target || inEvent.target; return e; }, // make and dispatch an event in one call fireEvent: function(inType, inEvent) { var e = this.makeEvent(inType, inEvent); return this.dispatchEvent(e); }, /** * Returns a snapshot of inEvent, with writable properties. * * @param {Event} inEvent An event that contains properties to copy. * @return {Object} An object containing shallow copies of `inEvent`'s * properties. */ cloneEvent: function(inEvent) { var eventCopy = Object.create(null), p; for (var i = 0; i < CLONE_PROPS.length; i++) { p = CLONE_PROPS[i]; eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i]; // Work around SVGInstanceElement shadow tree // Return the <use> element that is represented by the instance for Safari, Chrome, IE. // This is the behavior implemented by Firefox. if (p === 'target' || p === 'relatedTarget') { if (HAS_SVG_INSTANCE && eventCopy[p] instanceof SVGElementInstance) { eventCopy[p] = eventCopy[p].correspondingUseElement; } } } // keep the semantics of preventDefault eventCopy.preventDefault = function() { inEvent.preventDefault(); }; return eventCopy; }, /** * Dispatches the event to its target. * * @param {Event} inEvent The event to be dispatched. * @return {Boolean} True if an event handler returns true, false otherwise. */ dispatchEvent: function(inEvent) { var t = inEvent._target; if (t) { t.dispatchEvent(inEvent); // clone the event for the gesture system to process // clone after dispatch to pick up gesture prevention code var clone = this.cloneEvent(inEvent); clone.target = t; this.fillGestureQueue(clone); } }, gestureTrigger: function() { // process the gesture queue for (var i = 0, e, rg; i < this.gestureQueue.length; i++) { e = this.gestureQueue[i]; rg = e._requiredGestures; if (rg) { for (var j = 0, g, fn; j < this.gestures.length; j++) { // only run recognizer if an element in the source event's path is listening for those gestures if (rg[j]) { g = this.gestures[j]; fn = g[e.type]; if (fn) { fn.call(g, e); } } } } } this.gestureQueue.length = 0; }, fillGestureQueue: function(ev) { // only trigger the gesture queue once if (!this.gestureQueue.length) { requestAnimationFrame(this.boundGestureTrigger); } ev._requiredGestures = this.requiredGestures.get(ev.pointerId); this.gestureQueue.push(ev); } }; dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher); dispatcher.boundGestureTrigger = dispatcher.gestureTrigger.bind(dispatcher); scope.dispatcher = dispatcher; /** * Listen for `gesture` on `node` with the `handler` function * * If `handler` is the first listener for `gesture`, the underlying gesture recognizer is then enabled. * * @param {Element} node * @param {string} gesture * @return Boolean `gesture` is a valid gesture */ scope.activateGesture = function(node, gesture) { var g = gesture.toLowerCase(); var dep = dispatcher.dependencyMap[g]; if (dep) { var recognizer = dispatcher.gestures[dep.index]; if (!node._pgListeners) { dispatcher.register(node); node._pgListeners = 0; } // TODO(dfreedm): re-evaluate bookkeeping to avoid using attributes if (recognizer) { var touchAction = recognizer.defaultActions && recognizer.defaultActions[g]; var actionNode; switch(node.nodeType) { case Node.ELEMENT_NODE: actionNode = node; break; case Node.DOCUMENT_FRAGMENT_NODE: actionNode = node.host; break; default: actionNode = null; break; } if (touchAction && actionNode && !actionNode.hasAttribute('touch-action')) { actionNode.setAttribute('touch-action', touchAction); } } if (!node._pgEvents) { node._pgEvents = {}; } node._pgEvents[g] = (node._pgEvents[g] || 0) + 1; node._pgListeners++; } return Boolean(dep); }; /** * * Listen for `gesture` from `node` with `handler` function. * * @param {Element} node * @param {string} gesture * @param {Function} handler * @param {Boolean} capture */ scope.addEventListener = function(node, gesture, handler, capture) { if (handler) { scope.activateGesture(node, gesture); node.addEventListener(gesture, handler, capture); } }; /** * Tears down the gesture configuration for `node` * * If `handler` is the last listener for `gesture`, the underlying gesture recognizer is disabled. * * @param {Element} node * @param {string} gesture * @return Boolean `gesture` is a valid gesture */ scope.deactivateGesture = function(node, gesture) { var g = gesture.toLowerCase(); var dep = dispatcher.dependencyMap[g]; if (dep) { if (node._pgListeners > 0) { node._pgListeners--; } if (node._pgListeners === 0) { dispatcher.unregister(node); } if (node._pgEvents) { if (node._pgEvents[g] > 0) { node._pgEvents[g]--; } else { node._pgEvents[g] = 0; } } } return Boolean(dep); }; /** * Stop listening for `gesture` from `node` with `handler` function. * * @param {Element} node * @param {string} gesture * @param {Function} handler * @param {Boolean} capture */ scope.removeEventListener = function(node, gesture, handler, capture) { if (handler) { scope.deactivateGesture(node, gesture); node.removeEventListener(gesture, handler, capture); } }; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var pointermap = dispatcher.pointermap; // radius around touchend that swallows mouse events var DEDUP_DIST = 25; var WHICH_TO_BUTTONS = [0, 1, 4, 2]; var currentButtons = 0; var FIREFOX_LINUX = /Linux.*Firefox\//i; var HAS_BUTTONS = (function() { // firefox on linux returns spec-incorrect values for mouseup.buttons // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.buttons#See_also // https://codereview.chromium.org/727593003/#msg16 if (FIREFOX_LINUX.test(navigator.userAgent)) { return false; } try { return new MouseEvent('test', {buttons: 1}).buttons === 1; } catch (e) { return false; } })(); // handler block for native mouse events var mouseEvents = { POINTER_ID: 1, POINTER_TYPE: 'mouse', events: [ 'mousedown', 'mousemove', 'mouseup' ], exposes: [ 'down', 'up', 'move' ], register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { if (target === document) { return; } dispatcher.unlisten(target, this.events); }, lastTouches: [], // collide with the global mouse listener isEventSimulatedFromTouch: function(inEvent) { var lts = this.lastTouches; var x = inEvent.clientX, y = inEvent.clientY; for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) { // simulated mouse events will be swallowed near a primary touchend var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y); if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) { return true; } } }, prepareEvent: function(inEvent) { var e = dispatcher.cloneEvent(inEvent); e.pointerId = this.POINTER_ID; e.isPrimary = true; e.pointerType = this.POINTER_TYPE; e._source = 'mouse'; if (!HAS_BUTTONS) { var type = inEvent.type; var bit = WHICH_TO_BUTTONS[inEvent.which] || 0; if (type === 'mousedown') { currentButtons |= bit; } else if (type === 'mouseup') { currentButtons &= ~bit; } e.buttons = currentButtons; } return e; }, mousedown: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var p = pointermap.has(this.POINTER_ID); var e = this.prepareEvent(inEvent); e.target = scope.findTarget(inEvent); pointermap.set(this.POINTER_ID, e.target); dispatcher.down(e); } }, mousemove: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var target = pointermap.get(this.POINTER_ID); if (target) { var e = this.prepareEvent(inEvent); e.target = target; // handle case where we missed a mouseup if ((HAS_BUTTONS ? e.buttons : e.which) === 0) { if (!HAS_BUTTONS) { currentButtons = e.buttons = 0; } dispatcher.cancel(e); this.cleanupMouse(e.buttons); } else { dispatcher.move(e); } } } }, mouseup: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(this.POINTER_ID); dispatcher.up(e); this.cleanupMouse(e.buttons); } }, cleanupMouse: function(buttons) { if (buttons === 0) { pointermap.delete(this.POINTER_ID); } } }; scope.mouseEvents = mouseEvents; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var allShadows = scope.targetFinding.allShadows.bind(scope.targetFinding); var pointermap = dispatcher.pointermap; var touchMap = Array.prototype.map.call.bind(Array.prototype.map); // This should be long enough to ignore compat mouse events made by touch var DEDUP_TIMEOUT = 2500; var DEDUP_DIST = 25; var CLICK_COUNT_TIMEOUT = 200; var HYSTERESIS = 20; var ATTRIB = 'touch-action'; // TODO(dfreedm): disable until http://crbug.com/399765 is resolved // var HAS_TOUCH_ACTION = ATTRIB in document.head.style; var HAS_TOUCH_ACTION = false; // handler block for native touch events var touchEvents = { IS_IOS: false, events: [ 'touchstart', 'touchmove', 'touchend', 'touchcancel' ], exposes: [ 'down', 'up', 'move' ], register: function(target, initial) { if (this.IS_IOS ? initial : !initial) { dispatcher.listen(target, this.events); } }, unregister: function(target) { if (!this.IS_IOS) { dispatcher.unlisten(target, this.events); } }, scrollTypes: { EMITTER: 'none', XSCROLLER: 'pan-x', YSCROLLER: 'pan-y', }, touchActionToScrollType: function(touchAction) { var t = touchAction; var st = this.scrollTypes; if (t === st.EMITTER) { return 'none'; } else if (t === st.XSCROLLER) { return 'X'; } else if (t === st.YSCROLLER) { return 'Y'; } else { return 'XY'; } }, POINTER_TYPE: 'touch', firstTouch: null, isPrimaryTouch: function(inTouch) { return this.firstTouch === inTouch.identifier; }, setPrimaryTouch: function(inTouch) { // set primary touch if there no pointers, or the only pointer is the mouse if (pointermap.pointers() === 0 || (pointermap.pointers() === 1 && pointermap.has(1))) { this.firstTouch = inTouch.identifier; this.firstXY = {X: inTouch.clientX, Y: inTouch.clientY}; this.firstTarget = inTouch.target; this.scrolling = null; this.cancelResetClickCount(); } }, removePrimaryPointer: function(inPointer) { if (inPointer.isPrimary) { this.firstTouch = null; this.firstXY = null; this.resetClickCount(); } }, clickCount: 0, resetId: null, resetClickCount: function() { var fn = function() { this.clickCount = 0; this.resetId = null; }.bind(this); this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT); }, cancelResetClickCount: function() { if (this.resetId) { clearTimeout(this.resetId); } }, typeToButtons: function(type) { var ret = 0; if (type === 'touchstart' || type === 'touchmove') { ret = 1; } return ret; }, findTarget: function(touch, id) { if (this.currentTouchEvent.type === 'touchstart') { if (this.isPrimaryTouch(touch)) { var fastPath = { clientX: touch.clientX, clientY: touch.clientY, path: this.currentTouchEvent.path, target: this.currentTouchEvent.target }; return scope.findTarget(fastPath); } else { return scope.findTarget(touch); } } // reuse target we found in touchstart return pointermap.get(id); }, touchToPointer: function(inTouch) { var cte = this.currentTouchEvent; var e = dispatcher.cloneEvent(inTouch); // Spec specifies that pointerId 1 is reserved for Mouse. // Touch identifiers can start at 0. // Add 2 to the touch identifier for compatibility. var id = e.pointerId = inTouch.identifier + 2; e.target = this.findTarget(inTouch, id); e.bubbles = true; e.cancelable = true; e.detail = this.clickCount; e.buttons = this.typeToButtons(cte.type); e.width = inTouch.webkitRadiusX || inTouch.radiusX || 0; e.height = inTouch.webkitRadiusY || inTouch.radiusY || 0; e.pressure = inTouch.webkitForce || inTouch.force || 0.5; e.isPrimary = this.isPrimaryTouch(inTouch); e.pointerType = this.POINTER_TYPE; e._source = 'touch'; // forward touch preventDefaults var self = this; e.preventDefault = function() { self.scrolling = false; self.firstXY = null; cte.preventDefault(); }; return e; }, processTouches: function(inEvent, inFunction) { var tl = inEvent.changedTouches; this.currentTouchEvent = inEvent; for (var i = 0, t, p; i < tl.length; i++) { t = tl[i]; p = this.touchToPointer(t); if (inEvent.type === 'touchstart') { pointermap.set(p.pointerId, p.target); } if (pointermap.has(p.pointerId)) { inFunction.call(this, p); } if (inEvent.type === 'touchend' || inEvent._cancel) { this.cleanUpPointer(p); } } }, // For single axis scrollers, determines whether the element should emit // pointer events or behave as a scroller shouldScroll: function(inEvent) { if (this.firstXY) { var ret; var touchAction = scope.targetFinding.findTouchAction(inEvent); var scrollAxis = this.touchActionToScrollType(touchAction); if (scrollAxis === 'none') { // this element is a touch-action: none, should never scroll ret = false; } else if (scrollAxis === 'XY') { // this element should always scroll ret = true; } else { var t = inEvent.changedTouches[0]; // check the intended scroll axis, and other axis var a = scrollAxis; var oa = scrollAxis === 'Y' ? 'X' : 'Y'; var da = Math.abs(t['client' + a] - this.firstXY[a]); var doa = Math.abs(t['client' + oa] - this.firstXY[oa]); // if delta in the scroll axis > delta other axis, scroll instead of // making events ret = da >= doa; } return ret; } }, findTouch: function(inTL, inId) { for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) { if (t.identifier === inId) { return true; } } }, // In some instances, a touchstart can happen without a touchend. This // leaves the pointermap in a broken state. // Therefore, on every touchstart, we remove the touches that did not fire a // touchend event. // To keep state globally consistent, we fire a // pointercancel for this "abandoned" touch vacuumTouches: function(inEvent) { var tl = inEvent.touches; // pointermap.pointers() should be < tl.length here, as the touchstart has not // been processed yet. if (pointermap.pointers() >= tl.length) { var d = []; pointermap.forEach(function(value, key) { // Never remove pointerId == 1, which is mouse. // Touch identifiers are 2 smaller than their pointerId, which is the // index in pointermap. if (key !== 1 && !this.findTouch(tl, key - 2)) { var p = value; d.push(p); } }, this); d.forEach(function(p) { this.cancel(p); pointermap.delete(p.pointerId); }, this); } }, touchstart: function(inEvent) { this.vacuumTouches(inEvent); this.setPrimaryTouch(inEvent.changedTouches[0]); this.dedupSynthMouse(inEvent); if (!this.scrolling) { this.clickCount++; this.processTouches(inEvent, this.down); } }, down: function(inPointer) { dispatcher.down(inPointer); }, touchmove: function(inEvent) { if (HAS_TOUCH_ACTION) { // touchevent.cancelable == false is sent when the page is scrolling under native Touch Action in Chrome 36 // https://groups.google.com/a/chromium.org/d/msg/input-dev/wHnyukcYBcA/b9kmtwM1jJQJ if (inEvent.cancelable) { this.processTouches(inEvent, this.move); } } else { if (!this.scrolling) { if (this.scrolling === null && this.shouldScroll(inEvent)) { this.scrolling = true; } else { this.scrolling = false; inEvent.preventDefault(); this.processTouches(inEvent, this.move); } } else if (this.firstXY) { var t = inEvent.changedTouches[0]; var dx = t.clientX - this.firstXY.X; var dy = t.clientY - this.firstXY.Y; var dd = Math.sqrt(dx * dx + dy * dy); if (dd >= HYSTERESIS) { this.touchcancel(inEvent); this.scrolling = true; this.firstXY = null; } } } }, move: function(inPointer) { dispatcher.move(inPointer); }, touchend: function(inEvent) { this.dedupSynthMouse(inEvent); this.processTouches(inEvent, this.up); }, up: function(inPointer) { inPointer.relatedTarget = scope.findTarget(inPointer); dispatcher.up(inPointer); }, cancel: function(inPointer) { dispatcher.cancel(inPointer); }, touchcancel: function(inEvent) { inEvent._cancel = true; this.processTouches(inEvent, this.cancel); }, cleanUpPointer: function(inPointer) { pointermap['delete'](inPointer.pointerId); this.removePrimaryPointer(inPointer); }, // prevent synth mouse events from creating pointer events dedupSynthMouse: function(inEvent) { var lts = scope.mouseEvents.lastTouches; var t = inEvent.changedTouches[0]; // only the primary finger will synth mouse events if (this.isPrimaryTouch(t)) { // remember x/y of last touch var lt = {x: t.clientX, y: t.clientY}; lts.push(lt); var fn = (function(lts, lt){ var i = lts.indexOf(lt); if (i > -1) { lts.splice(i, 1); } }).bind(null, lts, lt); setTimeout(fn, DEDUP_TIMEOUT); } } }; // prevent "ghost clicks" that come from elements that were removed in a touch handler var STOP_PROP_FN = Event.prototype.stopImmediatePropagation || Event.prototype.stopPropagation; document.addEventListener('click', function(ev) { var x = ev.clientX, y = ev.clientY; // check if a click is within DEDUP_DIST px radius of the touchstart var closeTo = function(touch) { var dx = Math.abs(x - touch.x), dy = Math.abs(y - touch.y); return (dx <= DEDUP_DIST && dy <= DEDUP_DIST); }; // if click coordinates are close to touch coordinates, assume the click came from a touch var wasTouched = scope.mouseEvents.lastTouches.some(closeTo); // if the click came from touch, and the touchstart target is not in the path of the click event, // then the touchstart target was probably removed, and the click should be "busted" var path = scope.targetFinding.path(ev); if (wasTouched) { for (var i = 0; i < path.length; i++) { if (path[i] === touchEvents.firstTarget) { return; } } ev.preventDefault(); STOP_PROP_FN.call(ev); } }, true); scope.touchEvents = touchEvents; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var pointermap = dispatcher.pointermap; var HAS_BITMAP_TYPE = window.MSPointerEvent && typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number'; var msEvents = { events: [ 'MSPointerDown', 'MSPointerMove', 'MSPointerUp', 'MSPointerCancel', ], register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { if (target === document) { return; } dispatcher.unlisten(target, this.events); }, POINTER_TYPES: [ '', 'unavailable', 'touch', 'pen', 'mouse' ], prepareEvent: function(inEvent) { var e = inEvent; e = dispatcher.cloneEvent(inEvent); if (HAS_BITMAP_TYPE) { e.pointerType = this.POINTER_TYPES[inEvent.pointerType]; } e._source = 'ms'; return e; }, cleanup: function(id) { pointermap['delete'](id); }, MSPointerDown: function(inEvent) { var e = this.prepareEvent(inEvent); e.target = scope.findTarget(inEvent); pointermap.set(inEvent.pointerId, e.target); dispatcher.down(e); }, MSPointerMove: function(inEvent) { var target = pointermap.get(inEvent.pointerId); if (target) { var e = this.prepareEvent(inEvent); e.target = target; dispatcher.move(e); } }, MSPointerUp: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.up(e); this.cleanup(inEvent.pointerId); }, MSPointerCancel: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.cancel(e); this.cleanup(inEvent.pointerId); } }; scope.msEvents = msEvents; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var pointermap = dispatcher.pointermap; var pointerEvents = { events: [ 'pointerdown', 'pointermove', 'pointerup', 'pointercancel' ], prepareEvent: function(inEvent) { var e = dispatcher.cloneEvent(inEvent); e._source = 'pointer'; return e; }, register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { if (target === document) { return; } dispatcher.unlisten(target, this.events); }, cleanup: function(id) { pointermap['delete'](id); }, pointerdown: function(inEvent) { var e = this.prepareEvent(inEvent); e.target = scope.findTarget(inEvent); pointermap.set(e.pointerId, e.target); dispatcher.down(e); }, pointermove: function(inEvent) { var target = pointermap.get(inEvent.pointerId); if (target) { var e = this.prepareEvent(inEvent); e.target = target; dispatcher.move(e); } }, pointerup: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.up(e); this.cleanup(inEvent.pointerId); }, pointercancel: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.cancel(e); this.cleanup(inEvent.pointerId); } }; scope.pointerEvents = pointerEvents; })(window.PolymerGestures); /** * This module contains the handlers for native platform events. * From here, the dispatcher is called to create unified pointer events. * Included are touch events (v1), mouse events, and MSPointerEvents. */ (function(scope) { var dispatcher = scope.dispatcher; var nav = window.navigator; if (window.PointerEvent) { dispatcher.registerSource('pointer', scope.pointerEvents); } else if (nav.msPointerEnabled) { dispatcher.registerSource('ms', scope.msEvents); } else { dispatcher.registerSource('mouse', scope.mouseEvents); if (window.ontouchstart !== undefined) { dispatcher.registerSource('touch', scope.touchEvents); } } // Work around iOS bugs https://bugs.webkit.org/show_bug.cgi?id=135628 and https://bugs.webkit.org/show_bug.cgi?id=136506 var ua = navigator.userAgent; var IS_IOS = ua.match(/iPad|iPhone|iPod/) && 'ontouchstart' in window; dispatcher.IS_IOS = IS_IOS; scope.touchEvents.IS_IOS = IS_IOS; dispatcher.register(document, true); })(window.PolymerGestures); /** * This event denotes the beginning of a series of tracking events. * * @module PointerGestures * @submodule Events * @class trackstart */ /** * Pixels moved in the x direction since trackstart. * @type Number * @property dx */ /** * Pixes moved in the y direction since trackstart. * @type Number * @property dy */ /** * Pixels moved in the x direction since the last track. * @type Number * @property ddx */ /** * Pixles moved in the y direction since the last track. * @type Number * @property ddy */ /** * The clientX position of the track gesture. * @type Number * @property clientX */ /** * The clientY position of the track gesture. * @type Number * @property clientY */ /** * The pageX position of the track gesture. * @type Number * @property pageX */ /** * The pageY position of the track gesture. * @type Number * @property pageY */ /** * The screenX position of the track gesture. * @type Number * @property screenX */ /** * The screenY position of the track gesture. * @type Number * @property screenY */ /** * The last x axis direction of the pointer. * @type Number * @property xDirection */ /** * The last y axis direction of the pointer. * @type Number * @property yDirection */ /** * A shared object between all tracking events. * @type Object * @property trackInfo */ /** * The element currently under the pointer. * @type Element * @property relatedTarget */ /** * The type of pointer that make the track gesture. * @type String * @property pointerType */ /** * * This event fires for all pointer movement being tracked. * * @class track * @extends trackstart */ /** * This event fires when the pointer is no longer being tracked. * * @class trackend * @extends trackstart */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var pointermap = new scope.PointerMap(); var track = { events: [ 'down', 'move', 'up', ], exposes: [ 'trackstart', 'track', 'trackx', 'tracky', 'trackend' ], defaultActions: { 'track': 'none', 'trackx': 'pan-y', 'tracky': 'pan-x' }, WIGGLE_THRESHOLD: 4, clampDir: function(inDelta) { return inDelta > 0 ? 1 : -1; }, calcPositionDelta: function(inA, inB) { var x = 0, y = 0; if (inA && inB) { x = inB.pageX - inA.pageX; y = inB.pageY - inA.pageY; } return {x: x, y: y}; }, fireTrack: function(inType, inEvent, inTrackingData) { var t = inTrackingData; var d = this.calcPositionDelta(t.downEvent, inEvent); var dd = this.calcPositionDelta(t.lastMoveEvent, inEvent); if (dd.x) { t.xDirection = this.clampDir(dd.x); } else if (inType === 'trackx') { return; } if (dd.y) { t.yDirection = this.clampDir(dd.y); } else if (inType === 'tracky') { return; } var gestureProto = { bubbles: true, cancelable: true, trackInfo: t.trackInfo, relatedTarget: inEvent.relatedTarget, pointerType: inEvent.pointerType, pointerId: inEvent.pointerId, _source: 'track' }; if (inType !== 'tracky') { gestureProto.x = inEvent.x; gestureProto.dx = d.x; gestureProto.ddx = dd.x; gestureProto.clientX = inEvent.clientX; gestureProto.pageX = inEvent.pageX; gestureProto.screenX = inEvent.screenX; gestureProto.xDirection = t.xDirection; } if (inType !== 'trackx') { gestureProto.dy = d.y; gestureProto.ddy = dd.y; gestureProto.y = inEvent.y; gestureProto.clientY = inEvent.clientY; gestureProto.pageY = inEvent.pageY; gestureProto.screenY = inEvent.screenY; gestureProto.yDirection = t.yDirection; } var e = eventFactory.makeGestureEvent(inType, gestureProto); t.downTarget.dispatchEvent(e); }, down: function(inEvent) { if (inEvent.isPrimary && (inEvent.pointerType === 'mouse' ? inEvent.buttons === 1 : true)) { var p = { downEvent: inEvent, downTarget: inEvent.target, trackInfo: {}, lastMoveEvent: null, xDirection: 0, yDirection: 0, tracking: false }; pointermap.set(inEvent.pointerId, p); } }, move: function(inEvent) { var p = pointermap.get(inEvent.pointerId); if (p) { if (!p.tracking) { var d = this.calcPositionDelta(p.downEvent, inEvent); var move = d.x * d.x + d.y * d.y; // start tracking only if finger moves more than WIGGLE_THRESHOLD if (move > this.WIGGLE_THRESHOLD) { p.tracking = true; p.lastMoveEvent = p.downEvent; this.fireTrack('trackstart', inEvent, p); } } if (p.tracking) { this.fireTrack('track', inEvent, p); this.fireTrack('trackx', inEvent, p); this.fireTrack('tracky', inEvent, p); } p.lastMoveEvent = inEvent; } }, up: function(inEvent) { var p = pointermap.get(inEvent.pointerId); if (p) { if (p.tracking) { this.fireTrack('trackend', inEvent, p); } pointermap.delete(inEvent.pointerId); } } }; dispatcher.registerGesture('track', track); })(window.PolymerGestures); /** * This event is fired when a pointer is held down for 200ms. * * @module PointerGestures * @submodule Events * @class hold */ /** * Type of pointer that made the holding event. * @type String * @property pointerType */ /** * Screen X axis position of the held pointer * @type Number * @property clientX */ /** * Screen Y axis position of the held pointer * @type Number * @property clientY */ /** * Type of pointer that made the holding event. * @type String * @property pointerType */ /** * This event is fired every 200ms while a pointer is held down. * * @class holdpulse * @extends hold */ /** * Milliseconds pointer has been held down. * @type Number * @property holdTime */ /** * This event is fired when a held pointer is released or moved. * * @class release */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var hold = { // wait at least HOLD_DELAY ms between hold and pulse events HOLD_DELAY: 200, // pointer can move WIGGLE_THRESHOLD pixels before not counting as a hold WIGGLE_THRESHOLD: 16, events: [ 'down', 'move', 'up', ], exposes: [ 'hold', 'holdpulse', 'release' ], heldPointer: null, holdJob: null, pulse: function() { var hold = Date.now() - this.heldPointer.timeStamp; var type = this.held ? 'holdpulse' : 'hold'; this.fireHold(type, hold); this.held = true; }, cancel: function() { clearInterval(this.holdJob); if (this.held) { this.fireHold('release'); } this.held = false; this.heldPointer = null; this.target = null; this.holdJob = null; }, down: function(inEvent) { if (inEvent.isPrimary && !this.heldPointer) { this.heldPointer = inEvent; this.target = inEvent.target; this.holdJob = setInterval(this.pulse.bind(this), this.HOLD_DELAY); } }, up: function(inEvent) { if (this.heldPointer && this.heldPointer.pointerId === inEvent.pointerId) { this.cancel(); } }, move: function(inEvent) { if (this.heldPointer && this.heldPointer.pointerId === inEvent.pointerId) { var x = inEvent.clientX - this.heldPointer.clientX; var y = inEvent.clientY - this.heldPointer.clientY; if ((x * x + y * y) > this.WIGGLE_THRESHOLD) { this.cancel(); } } }, fireHold: function(inType, inHoldTime) { var p = { bubbles: true, cancelable: true, pointerType: this.heldPointer.pointerType, pointerId: this.heldPointer.pointerId, x: this.heldPointer.clientX, y: this.heldPointer.clientY, _source: 'hold' }; if (inHoldTime) { p.holdTime = inHoldTime; } var e = eventFactory.makeGestureEvent(inType, p); this.target.dispatchEvent(e); } }; dispatcher.registerGesture('hold', hold); })(window.PolymerGestures); /** * This event is fired when a pointer quickly goes down and up, and is used to * denote activation. * * Any gesture event can prevent the tap event from being created by calling * `event.preventTap`. * * Any pointer event can prevent the tap by setting the `tapPrevented` property * on itself. * * @module PointerGestures * @submodule Events * @class tap */ /** * X axis position of the tap. * @property x * @type Number */ /** * Y axis position of the tap. * @property y * @type Number */ /** * Type of the pointer that made the tap. * @property pointerType * @type String */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var pointermap = new scope.PointerMap(); var tap = { events: [ 'down', 'up' ], exposes: [ 'tap' ], down: function(inEvent) { if (inEvent.isPrimary && !inEvent.tapPrevented) { pointermap.set(inEvent.pointerId, { target: inEvent.target, buttons: inEvent.buttons, x: inEvent.clientX, y: inEvent.clientY }); } }, shouldTap: function(e, downState) { var tap = true; if (e.pointerType === 'mouse') { // only allow left click to tap for mouse tap = (e.buttons ^ 1) && (downState.buttons & 1); } return tap && !e.tapPrevented; }, up: function(inEvent) { var start = pointermap.get(inEvent.pointerId); if (start && this.shouldTap(inEvent, start)) { // up.relatedTarget is target currently under finger var t = scope.targetFinding.LCA(start.target, inEvent.relatedTarget); if (t) { var e = eventFactory.makeGestureEvent('tap', { bubbles: true, cancelable: true, x: inEvent.clientX, y: inEvent.clientY, detail: inEvent.detail, pointerType: inEvent.pointerType, pointerId: inEvent.pointerId, altKey: inEvent.altKey, ctrlKey: inEvent.ctrlKey, metaKey: inEvent.metaKey, shiftKey: inEvent.shiftKey, _source: 'tap' }); t.dispatchEvent(e); } } pointermap.delete(inEvent.pointerId); } }; // patch eventFactory to remove id from tap's pointermap for preventTap calls eventFactory.preventTap = function(e) { return function() { e.tapPrevented = true; pointermap.delete(e.pointerId); }; }; dispatcher.registerGesture('tap', tap); })(window.PolymerGestures); /* * Basic strategy: find the farthest apart points, use as diameter of circle * react to size change and rotation of the chord */ /** * @module pointer-gestures * @submodule Events * @class pinch */ /** * Scale of the pinch zoom gesture * @property scale * @type Number */ /** * Center X position of pointers causing pinch * @property centerX * @type Number */ /** * Center Y position of pointers causing pinch * @property centerY * @type Number */ /** * @module pointer-gestures * @submodule Events * @class rotate */ /** * Angle (in degrees) of rotation. Measured from starting positions of pointers. * @property angle * @type Number */ /** * Center X position of pointers causing rotation * @property centerX * @type Number */ /** * Center Y position of pointers causing rotation * @property centerY * @type Number */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var pointermap = new scope.PointerMap(); var RAD_TO_DEG = 180 / Math.PI; var pinch = { events: [ 'down', 'up', 'move', 'cancel' ], exposes: [ 'pinchstart', 'pinch', 'pinchend', 'rotate' ], defaultActions: { 'pinch': 'none', 'rotate': 'none' }, reference: {}, down: function(inEvent) { pointermap.set(inEvent.pointerId, inEvent); if (pointermap.pointers() == 2) { var points = this.calcChord(); var angle = this.calcAngle(points); this.reference = { angle: angle, diameter: points.diameter, target: scope.targetFinding.LCA(points.a.target, points.b.target) }; this.firePinch('pinchstart', points.diameter, points); } }, up: function(inEvent) { var p = pointermap.get(inEvent.pointerId); var num = pointermap.pointers(); if (p) { if (num === 2) { // fire 'pinchend' before deleting pointer var points = this.calcChord(); this.firePinch('pinchend', points.diameter, points); } pointermap.delete(inEvent.pointerId); } }, move: function(inEvent) { if (pointermap.has(inEvent.pointerId)) { pointermap.set(inEvent.pointerId, inEvent); if (pointermap.pointers() > 1) { this.calcPinchRotate(); } } }, cancel: function(inEvent) { this.up(inEvent); }, firePinch: function(type, diameter, points) { var zoom = diameter / this.reference.diameter; var e = eventFactory.makeGestureEvent(type, { bubbles: true, cancelable: true, scale: zoom, centerX: points.center.x, centerY: points.center.y, _source: 'pinch' }); this.reference.target.dispatchEvent(e); }, fireRotate: function(angle, points) { var diff = Math.round((angle - this.reference.angle) % 360); var e = eventFactory.makeGestureEvent('rotate', { bubbles: true, cancelable: true, angle: diff, centerX: points.center.x, centerY: points.center.y, _source: 'pinch' }); this.reference.target.dispatchEvent(e); }, calcPinchRotate: function() { var points = this.calcChord(); var diameter = points.diameter; var angle = this.calcAngle(points); if (diameter != this.reference.diameter) { this.firePinch('pinch', diameter, points); } if (angle != this.reference.angle) { this.fireRotate(angle, points); } }, calcChord: function() { var pointers = []; pointermap.forEach(function(p) { pointers.push(p); }); var dist = 0; // start with at least two pointers var points = {a: pointers[0], b: pointers[1]}; var x, y, d; for (var i = 0; i < pointers.length; i++) { var a = pointers[i]; for (var j = i + 1; j < pointers.length; j++) { var b = pointers[j]; x = Math.abs(a.clientX - b.clientX); y = Math.abs(a.clientY - b.clientY); d = x + y; if (d > dist) { dist = d; points = {a: a, b: b}; } } } x = Math.abs(points.a.clientX + points.b.clientX) / 2; y = Math.abs(points.a.clientY + points.b.clientY) / 2; points.center = { x: x, y: y }; points.diameter = dist; return points; }, calcAngle: function(points) { var x = points.a.clientX - points.b.clientX; var y = points.a.clientY - points.b.clientY; return (360 + Math.atan2(y, x) * RAD_TO_DEG) % 360; } }; dispatcher.registerGesture('pinch', pinch); })(window.PolymerGestures); (function (global) { 'use strict'; var Token, TokenName, Syntax, Messages, source, index, length, delegate, lookahead, state; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; Syntax = { ArrayExpression: 'ArrayExpression', BinaryExpression: 'BinaryExpression', CallExpression: 'CallExpression', ConditionalExpression: 'ConditionalExpression', EmptyStatement: 'EmptyStatement', ExpressionStatement: 'ExpressionStatement', Identifier: 'Identifier', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', ObjectExpression: 'ObjectExpression', Program: 'Program', Property: 'Property', ThisExpression: 'ThisExpression', UnaryExpression: 'UnaryExpression' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared' }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 32) || // space (ch === 9) || // tab (ch === 0xB) || (ch === 0xC) || (ch === 0xA0) || (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122); // a..z } function isIdentifierPart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57); // 0..9 } // 7.6.1.1 Keywords function isKeyword(id) { return (id === 'this') } // 7.4 Comments function skipWhitespace() { while (index < length && isWhiteSpace(source.charCodeAt(index))) { ++index; } } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; id = getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2; switch (code) { // Check for most common single-character punctuators. case 46: // . dot case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 123: // { open curly brace case 125: // } close curly brace case 91: // [ case 93: // ] case 58: // : case 63: // ? ++index; return { type: Token.Punctuator, value: String.fromCharCode(code), range: [start, index] }; default: code2 = source.charCodeAt(index + 1); // '=' (char #61) marks an assignment or comparison operator. if (code2 === 61) { switch (code) { case 37: // % case 38: // & case 42: // *: case 43: // + case 45: // - case 47: // / case 60: // < case 62: // > case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), range: [start, index] }; case 33: // ! case 61: // = index += 2; // !== and === if (source.charCodeAt(index) === 61) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; // Other 2-character punctuators: && || if (ch1 === ch2 && ('&|'.indexOf(ch1) >= 0)) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. if (number === '0') { // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: str += ch; break; } } else { if (ch === '\r' && source[index] === '\n') { ++index; } } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advance() { var ch; skipWhitespace(); if (index >= length) { return { type: Token.EOF, range: [index, index] }; } ch = source.charCodeAt(index); // Very common: ( and ) and ; if (ch === 40 || ch === 41 || ch === 58) { return scanPunctuator(); } // String literal starts with single quote (#39) or double quote (#34). if (ch === 39 || ch === 34) { return scanStringLiteral(); } if (isIdentifierStart(ch)) { return scanIdentifier(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lookahead = advance(); index = token.range[1]; return token; } function peek() { var pos; pos = index; lookahead = advance(); index = pos; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, index) { assert(index < args.length, 'Message reference must be in range'); return args[index]; } ); error = new Error(msg); error.index = index; error.description = msg; throw error; } // Throw an exception because of the token. function throwUnexpected(token) { throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { return lookahead.type === Token.Keyword && lookahead.value === keyword; } function consumeSemicolon() { // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } skipWhitespace(); if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = []; expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else { elements.push(parseExpression()); if (!match(']')) { expect(','); } } } expect(']'); return delegate.createArrayExpression(elements); } // 11.1.5 Object Initialiser function parseObjectPropertyKey() { var token; skipWhitespace(); token = lex(); // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { return delegate.createLiteral(token); } return delegate.createIdentifier(token.value); } function parseObjectProperty() { var token, key; token = lookahead; skipWhitespace(); if (token.type === Token.EOF || token.type === Token.Punctuator) { throwUnexpected(token); } key = parseObjectPropertyKey(); expect(':'); return delegate.createProperty('init', key, parseExpression()); } function parseObjectInitialiser() { var properties = []; expect('{'); while (!match('}')) { properties.push(parseObjectProperty()); if (!match('}')) { expect(','); } } expect('}'); return delegate.createObjectExpression(properties); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); expr = parseExpression(); expect(')'); return expr; } // 11.1 Primary Expressions function parsePrimaryExpression() { var type, token, expr; if (match('(')) { return parseGroupExpression(); } type = lookahead.type; if (type === Token.Identifier) { expr = delegate.createIdentifier(lex().value); } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { expr = delegate.createLiteral(lex()); } else if (type === Token.Keyword) { if (matchKeyword('this')) { lex(); expr = delegate.createThisExpression(); } } else if (type === Token.BooleanLiteral) { token = lex(); token.value = (token.value === 'true'); expr = delegate.createLiteral(token); } else if (type === Token.NullLiteral) { token = lex(); token.value = null; expr = delegate.createLiteral(token); } else if (match('[')) { expr = parseArrayInitialiser(); } else if (match('{')) { expr = parseObjectInitialiser(); } if (expr) { return expr; } throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = []; expect('('); if (!match(')')) { while (index < length) { args.push(parseExpression()); if (match(')')) { break; } expect(','); } } expect(')'); return args; } function parseNonComputedProperty() { var token; token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return delegate.createIdentifier(token.value); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseLeftHandSideExpression() { var expr, args, property; expr = parsePrimaryExpression(); while (true) { if (match('[')) { property = parseComputedMember(); expr = delegate.createMemberExpression('[', expr, property); } else if (match('.')) { property = parseNonComputedMember(); expr = delegate.createMemberExpression('.', expr, property); } else if (match('(')) { args = parseArguments(); expr = delegate.createCallExpression(expr, args); } else { break; } } return expr; } // 11.3 Postfix Expressions var parsePostfixExpression = parseLeftHandSideExpression; // 11.4 Unary Operators function parseUnaryExpression() { var token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { expr = parsePostfixExpression(); } else if (match('+') || match('-') || match('!')) { token = lex(); expr = parseUnaryExpression(); expr = delegate.createUnaryExpression(token.value, expr); } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { throwError({}, Messages.UnexpectedToken); } else { expr = parsePostfixExpression(); } return expr; } function binaryPrecedence(token) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = 7; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var expr, token, prec, stack, right, operator, left, i; left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token); if (prec === 0) { return left; } token.prec = prec; lex(); right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); expr = delegate.createBinaryExpression(operator, left, right); stack.push(expr); } // Shift. token = lex(); token.prec = prec; stack.push(token); expr = parseUnaryExpression(); stack.push(expr); } // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, consequent, alternate; expr = parseBinaryExpression(); if (match('?')) { lex(); consequent = parseConditionalExpression(); expect(':'); alternate = parseConditionalExpression(); expr = delegate.createConditionalExpression(expr, consequent, alternate); } return expr; } // Simplification since we do not support AssignmentExpression. var parseExpression = parseConditionalExpression; // Polymer Syntax extensions // Filter :: // Identifier // Identifier "(" ")" // Identifier "(" FilterArguments ")" function parseFilter() { var identifier, args; identifier = lex(); if (identifier.type !== Token.Identifier) { throwUnexpected(identifier); } args = match('(') ? parseArguments() : []; return delegate.createFilter(identifier.value, args); } // Filters :: // "|" Filter // Filters "|" Filter function parseFilters() { while (match('|')) { lex(); parseFilter(); } } // TopLevel :: // LabelledExpressions // AsExpression // InExpression // FilterExpression // AsExpression :: // FilterExpression as Identifier // InExpression :: // Identifier, Identifier in FilterExpression // Identifier in FilterExpression // FilterExpression :: // Expression // Expression Filters function parseTopLevel() { skipWhitespace(); peek(); var expr = parseExpression(); if (expr) { if (lookahead.value === ',' || lookahead.value == 'in' && expr.type === Syntax.Identifier) { parseInExpression(expr); } else { parseFilters(); if (lookahead.value === 'as') { parseAsExpression(expr); } else { delegate.createTopLevel(expr); } } } if (lookahead.type !== Token.EOF) { throwUnexpected(lookahead); } } function parseAsExpression(expr) { lex(); // as var identifier = lex().value; delegate.createAsExpression(expr, identifier); } function parseInExpression(identifier) { var indexName; if (lookahead.value === ',') { lex(); if (lookahead.type !== Token.Identifier) throwUnexpected(lookahead); indexName = lex().value; } lex(); // in var expr = parseExpression(); parseFilters(); delegate.createInExpression(identifier.name, indexName, expr); } function parse(code, inDelegate) { delegate = inDelegate; source = code; index = 0; length = source.length; lookahead = null; state = { labelSet: {} }; return parseTopLevel(); } global.esprima = { parse: parse }; })(this); // Copyright (c) 2014 The Polymer Project Authors. All rights reserved. // This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt // The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt // The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt // Code distributed by Google as part of the polymer project is also // subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt (function (global) { 'use strict'; function prepareBinding(expressionText, name, node, filterRegistry) { var expression; try { expression = getExpression(expressionText); if (expression.scopeIdent && (node.nodeType !== Node.ELEMENT_NODE || node.tagName !== 'TEMPLATE' || (name !== 'bind' && name !== 'repeat'))) { throw Error('as and in can only be used within <template bind/repeat>'); } } catch (ex) { console.error('Invalid expression syntax: ' + expressionText, ex); return; } return function(model, node, oneTime) { var binding = expression.getBinding(model, filterRegistry, oneTime); if (expression.scopeIdent && binding) { node.polymerExpressionScopeIdent_ = expression.scopeIdent; if (expression.indexIdent) node.polymerExpressionIndexIdent_ = expression.indexIdent; } return binding; } } // TODO(rafaelw): Implement simple LRU. var expressionParseCache = Object.create(null); function getExpression(expressionText) { var expression = expressionParseCache[expressionText]; if (!expression) { var delegate = new ASTDelegate(); esprima.parse(expressionText, delegate); expression = new Expression(delegate); expressionParseCache[expressionText] = expression; } return expression; } function Literal(value) { this.value = value; this.valueFn_ = undefined; } Literal.prototype = { valueFn: function() { if (!this.valueFn_) { var value = this.value; this.valueFn_ = function() { return value; } } return this.valueFn_; } } function IdentPath(name) { this.name = name; this.path = Path.get(name); } IdentPath.prototype = { valueFn: function() { if (!this.valueFn_) { var name = this.name; var path = this.path; this.valueFn_ = function(model, observer) { if (observer) observer.addPath(model, path); return path.getValueFrom(model); } } return this.valueFn_; }, setValue: function(model, newValue) { if (this.path.length == 1) model = findScope(model, this.path[0]); return this.path.setValueFrom(model, newValue); } }; function MemberExpression(object, property, accessor) { this.computed = accessor == '['; this.dynamicDeps = typeof object == 'function' || object.dynamicDeps || (this.computed && !(property instanceof Literal)); this.simplePath = !this.dynamicDeps && (property instanceof IdentPath || property instanceof Literal) && (object instanceof MemberExpression || object instanceof IdentPath); this.object = this.simplePath ? object : getFn(object); this.property = !this.computed || this.simplePath ? property : getFn(property); } MemberExpression.prototype = { get fullPath() { if (!this.fullPath_) { var parts = this.object instanceof MemberExpression ? this.object.fullPath.slice() : [this.object.name]; parts.push(this.property instanceof IdentPath ? this.property.name : this.property.value); this.fullPath_ = Path.get(parts); } return this.fullPath_; }, valueFn: function() { if (!this.valueFn_) { var object = this.object; if (this.simplePath) { var path = this.fullPath; this.valueFn_ = function(model, observer) { if (observer) observer.addPath(model, path); return path.getValueFrom(model); }; } else if (!this.computed) { var path = Path.get(this.property.name); this.valueFn_ = function(model, observer, filterRegistry) { var context = object(model, observer, filterRegistry); if (observer) observer.addPath(context, path); return path.getValueFrom(context); } } else { // Computed property. var property = this.property; this.valueFn_ = function(model, observer, filterRegistry) { var context = object(model, observer, filterRegistry); var propName = property(model, observer, filterRegistry); if (observer) observer.addPath(context, [propName]); return context ? context[propName] : undefined; }; } } return this.valueFn_; }, setValue: function(model, newValue) { if (this.simplePath) { this.fullPath.setValueFrom(model, newValue); return newValue; } var object = this.object(model); var propName = this.property instanceof IdentPath ? this.property.name : this.property(model); return object[propName] = newValue; } }; function Filter(name, args) { this.name = name; this.args = []; for (var i = 0; i < args.length; i++) { this.args[i] = getFn(args[i]); } } Filter.prototype = { transform: function(model, observer, filterRegistry, toModelDirection, initialArgs) { var fn = filterRegistry[this.name]; var context = model; if (fn) { context = undefined; } else { fn = context[this.name]; if (!fn) { console.error('Cannot find function or filter: ' + this.name); return; } } // If toModelDirection is falsey, then the "normal" (dom-bound) direction // is used. Otherwise, it looks for a 'toModel' property function on the // object. if (toModelDirection) { fn = fn.toModel; } else if (typeof fn.toDOM == 'function') { fn = fn.toDOM; } if (typeof fn != 'function') { console.error('Cannot find function or filter: ' + this.name); return; } var args = initialArgs || []; for (var i = 0; i < this.args.length; i++) { args.push(getFn(this.args[i])(model, observer, filterRegistry)); } return fn.apply(context, args); } }; function notImplemented() { throw Error('Not Implemented'); } var unaryOperators = { '+': function(v) { return +v; }, '-': function(v) { return -v; }, '!': function(v) { return !v; } }; var binaryOperators = { '+': function(l, r) { return l+r; }, '-': function(l, r) { return l-r; }, '*': function(l, r) { return l*r; }, '/': function(l, r) { return l/r; }, '%': function(l, r) { return l%r; }, '<': function(l, r) { return l<r; }, '>': function(l, r) { return l>r; }, '<=': function(l, r) { return l<=r; }, '>=': function(l, r) { return l>=r; }, '==': function(l, r) { return l==r; }, '!=': function(l, r) { return l!=r; }, '===': function(l, r) { return l===r; }, '!==': function(l, r) { return l!==r; }, '&&': function(l, r) { return l&&r; }, '||': function(l, r) { return l||r; }, }; function getFn(arg) { return typeof arg == 'function' ? arg : arg.valueFn(); } function ASTDelegate() { this.expression = null; this.filters = []; this.deps = {}; this.currentPath = undefined; this.scopeIdent = undefined; this.indexIdent = undefined; this.dynamicDeps = false; } ASTDelegate.prototype = { createUnaryExpression: function(op, argument) { if (!unaryOperators[op]) throw Error('Disallowed operator: ' + op); argument = getFn(argument); return function(model, observer, filterRegistry) { return unaryOperators[op](argument(model, observer, filterRegistry)); }; }, createBinaryExpression: function(op, left, right) { if (!binaryOperators[op]) throw Error('Disallowed operator: ' + op); left = getFn(left); right = getFn(right); switch (op) { case '||': this.dynamicDeps = true; return function(model, observer, filterRegistry) { return left(model, observer, filterRegistry) || right(model, observer, filterRegistry); }; case '&&': this.dynamicDeps = true; return function(model, observer, filterRegistry) { return left(model, observer, filterRegistry) && right(model, observer, filterRegistry); }; } return function(model, observer, filterRegistry) { return binaryOperators[op](left(model, observer, filterRegistry), right(model, observer, filterRegistry)); }; }, createConditionalExpression: function(test, consequent, alternate) { test = getFn(test); consequent = getFn(consequent); alternate = getFn(alternate); this.dynamicDeps = true; return function(model, observer, filterRegistry) { return test(model, observer, filterRegistry) ? consequent(model, observer, filterRegistry) : alternate(model, observer, filterRegistry); } }, createIdentifier: function(name) { var ident = new IdentPath(name); ident.type = 'Identifier'; return ident; }, createMemberExpression: function(accessor, object, property) { var ex = new MemberExpression(object, property, accessor); if (ex.dynamicDeps) this.dynamicDeps = true; return ex; }, createCallExpression: function(expression, args) { if (!(expression instanceof IdentPath)) throw Error('Only identifier function invocations are allowed'); var filter = new Filter(expression.name, args); return function(model, observer, filterRegistry) { return filter.transform(model, observer, filterRegistry, false); }; }, createLiteral: function(token) { return new Literal(token.value); }, createArrayExpression: function(elements) { for (var i = 0; i < elements.length; i++) elements[i] = getFn(elements[i]); return function(model, observer, filterRegistry) { var arr = [] for (var i = 0; i < elements.length; i++) arr.push(elements[i](model, observer, filterRegistry)); return arr; } }, createProperty: function(kind, key, value) { return { key: key instanceof IdentPath ? key.name : key.value, value: value }; }, createObjectExpression: function(properties) { for (var i = 0; i < properties.length; i++) properties[i].value = getFn(properties[i].value); return function(model, observer, filterRegistry) { var obj = {}; for (var i = 0; i < properties.length; i++) obj[properties[i].key] = properties[i].value(model, observer, filterRegistry); return obj; } }, createFilter: function(name, args) { this.filters.push(new Filter(name, args)); }, createAsExpression: function(expression, scopeIdent) { this.expression = expression; this.scopeIdent = scopeIdent; }, createInExpression: function(scopeIdent, indexIdent, expression) { this.expression = expression; this.scopeIdent = scopeIdent; this.indexIdent = indexIdent; }, createTopLevel: function(expression) { this.expression = expression; }, createThisExpression: notImplemented } function ConstantObservable(value) { this.value_ = value; } ConstantObservable.prototype = { open: function() { return this.value_; }, discardChanges: function() { return this.value_; }, deliver: function() {}, close: function() {}, } function Expression(delegate) { this.scopeIdent = delegate.scopeIdent; this.indexIdent = delegate.indexIdent; if (!delegate.expression) throw Error('No expression found.'); this.expression = delegate.expression; getFn(this.expression); // forces enumeration of path dependencies this.filters = delegate.filters; this.dynamicDeps = delegate.dynamicDeps; } Expression.prototype = { getBinding: function(model, filterRegistry, oneTime) { if (oneTime) return this.getValue(model, undefined, filterRegistry); var observer = new CompoundObserver(); // captures deps. var firstValue = this.getValue(model, observer, filterRegistry); var firstTime = true; var self = this; function valueFn() { // deps cannot have changed on first value retrieval. if (firstTime) { firstTime = false; return firstValue; } if (self.dynamicDeps) observer.startReset(); var value = self.getValue(model, self.dynamicDeps ? observer : undefined, filterRegistry); if (self.dynamicDeps) observer.finishReset(); return value; } function setValueFn(newValue) { self.setValue(model, newValue, filterRegistry); return newValue; } return new ObserverTransform(observer, valueFn, setValueFn, true); }, getValue: function(model, observer, filterRegistry) { var value = getFn(this.expression)(model, observer, filterRegistry); for (var i = 0; i < this.filters.length; i++) { value = this.filters[i].transform(model, observer, filterRegistry, false, [value]); } return value; }, setValue: function(model, newValue, filterRegistry) { var count = this.filters ? this.filters.length : 0; while (count-- > 0) { newValue = this.filters[count].transform(model, undefined, filterRegistry, true, [newValue]); } if (this.expression.setValue) return this.expression.setValue(model, newValue); } } /** * Converts a style property name to a css property name. For example: * "WebkitUserSelect" to "-webkit-user-select" */ function convertStylePropertyName(name) { return String(name).replace(/[A-Z]/g, function(c) { return '-' + c.toLowerCase(); }); } var parentScopeName = '@' + Math.random().toString(36).slice(2); // Single ident paths must bind directly to the appropriate scope object. // I.e. Pushed values in two-bindings need to be assigned to the actual model // object. function findScope(model, prop) { while (model[parentScopeName] && !Object.prototype.hasOwnProperty.call(model, prop)) { model = model[parentScopeName]; } return model; } function isLiteralExpression(pathString) { switch (pathString) { case '': return false; case 'false': case 'null': case 'true': return true; } if (!isNaN(Number(pathString))) return true; return false; }; function PolymerExpressions() {} PolymerExpressions.prototype = { // "built-in" filters styleObject: function(value) { var parts = []; for (var key in value) { parts.push(convertStylePropertyName(key) + ': ' + value[key]); } return parts.join('; '); }, tokenList: function(value) { var tokens = []; for (var key in value) { if (value[key]) tokens.push(key); } return tokens.join(' '); }, // binding delegate API prepareInstancePositionChanged: function(template) { var indexIdent = template.polymerExpressionIndexIdent_; if (!indexIdent) return; return function(templateInstance, index) { templateInstance.model[indexIdent] = index; }; }, prepareBinding: function(pathString, name, node) { var path = Path.get(pathString); if (!isLiteralExpression(pathString) && path.valid) { if (path.length == 1) { return function(model, node, oneTime) { if (oneTime) return path.getValueFrom(model); var scope = findScope(model, path[0]); return new PathObserver(scope, path); }; } return; // bail out early if pathString is simple path. } return prepareBinding(pathString, name, node, this); }, prepareInstanceModel: function(template) { var scopeName = template.polymerExpressionScopeIdent_; if (!scopeName) return; var parentScope = template.templateInstance ? template.templateInstance.model : template.model; var indexName = template.polymerExpressionIndexIdent_; return function(model) { return createScopeObject(parentScope, model, scopeName, indexName); }; } }; var createScopeObject = ('__proto__' in {}) ? function(parentScope, model, scopeName, indexName) { var scope = {}; scope[scopeName] = model; scope[indexName] = undefined; scope[parentScopeName] = parentScope; scope.__proto__ = parentScope; return scope; } : function(parentScope, model, scopeName, indexName) { var scope = Object.create(parentScope); Object.defineProperty(scope, scopeName, { value: model, configurable: true, writable: true }); Object.defineProperty(scope, indexName, { value: undefined, configurable: true, writable: true }); Object.defineProperty(scope, parentScopeName, { value: parentScope, configurable: true, writable: true }); return scope; }; global.PolymerExpressions = PolymerExpressions; PolymerExpressions.getExpression = getExpression; })(this); Polymer = { version: '0.5.3' }; // TODO(sorvell): this ensures Polymer is an object and not a function // Platform is currently defining it as a function to allow for async loading // of polymer; once we refine the loading process this likely goes away. if (typeof window.Polymer === 'function') { Polymer = {}; } (function(scope) { function withDependencies(task, depends) { depends = depends || []; if (!depends.map) { depends = [depends]; } return task.apply(this, depends.map(marshal)); } function module(name, dependsOrFactory, moduleFactory) { var module; switch (arguments.length) { case 0: return; case 1: module = null; break; case 2: // dependsOrFactory is `factory` in this case module = dependsOrFactory.apply(this); break; default: // dependsOrFactory is `depends` in this case module = withDependencies(moduleFactory, dependsOrFactory); break; } modules[name] = module; }; function marshal(name) { return modules[name]; } var modules = {}; function using(depends, task) { HTMLImports.whenImportsReady(function() { withDependencies(task, depends); }); }; // exports scope.marshal = marshal; // `module` confuses commonjs detectors scope.modularize = module; scope.using = using; })(window); /* Build only script. Ensures scripts needed for basic x-platform compatibility will be run when platform.js is not loaded. */ if (!window.WebComponents) { /* On supported platforms, platform.js is not needed. To retain compatibility with the polyfills, we stub out minimal functionality. */ if (!window.WebComponents) { WebComponents = { flush: function() {}, flags: {log: {}} }; Platform = WebComponents; CustomElements = { useNative: true, ready: true, takeRecords: function() {}, instanceof: function(obj, base) { return obj instanceof base; } }; HTMLImports = { useNative: true }; addEventListener('HTMLImportsLoaded', function() { document.dispatchEvent( new CustomEvent('WebComponentsReady', {bubbles: true}) ); }); // ShadowDOM ShadowDOMPolyfill = null; wrap = unwrap = function(n){ return n; }; } /* Create polyfill scope and feature detect native support. */ window.HTMLImports = window.HTMLImports || {flags:{}}; (function(scope) { /** Basic setup and simple module executer. We collect modules and then execute the code later, only if it's necessary for polyfilling. */ var IMPORT_LINK_TYPE = 'import'; var useNative = Boolean(IMPORT_LINK_TYPE in document.createElement('link')); /** Support `currentScript` on all browsers as `document._currentScript.` NOTE: We cannot polyfill `document.currentScript` because it's not possible both to override and maintain the ability to capture the native value. Therefore we choose to expose `_currentScript` both when native imports and the polyfill are in use. */ // NOTE: ShadowDOMPolyfill intrusion. var hasShadowDOMPolyfill = Boolean(window.ShadowDOMPolyfill); var wrap = function(node) { return hasShadowDOMPolyfill ? ShadowDOMPolyfill.wrapIfNeeded(node) : node; }; var rootDocument = wrap(document); var currentScriptDescriptor = { get: function() { var script = HTMLImports.currentScript || document.currentScript || // NOTE: only works when called in synchronously executing code. // readyState should check if `loading` but IE10 is // interactive when scripts run so we cheat. (document.readyState !== 'complete' ? document.scripts[document.scripts.length - 1] : null); return wrap(script); }, configurable: true }; Object.defineProperty(document, '_currentScript', currentScriptDescriptor); Object.defineProperty(rootDocument, '_currentScript', currentScriptDescriptor); /** Add support for the `HTMLImportsLoaded` event and the `HTMLImports.whenReady` method. This api is necessary because unlike the native implementation, script elements do not force imports to resolve. Instead, users should wrap code in either an `HTMLImportsLoaded` hander or after load time in an `HTMLImports.whenReady(callback)` call. NOTE: This module also supports these apis under the native implementation. Therefore, if this file is loaded, the same code can be used under both the polyfill and native implementation. */ var isIE = /Trident/.test(navigator.userAgent); // call a callback when all HTMLImports in the document at call time // (or at least document ready) have loaded. // 1. ensure the document is in a ready state (has dom), then // 2. watch for loading of imports and call callback when done function whenReady(callback, doc) { doc = doc || rootDocument; // if document is loading, wait and try again whenDocumentReady(function() { watchImportsLoad(callback, doc); }, doc); } // call the callback when the document is in a ready state (has dom) var requiredReadyState = isIE ? 'complete' : 'interactive'; var READY_EVENT = 'readystatechange'; function isDocumentReady(doc) { return (doc.readyState === 'complete' || doc.readyState === requiredReadyState); } // call <callback> when we ensure the document is in a ready state function whenDocumentReady(callback, doc) { if (!isDocumentReady(doc)) { var checkReady = function() { if (doc.readyState === 'complete' || doc.readyState === requiredReadyState) { doc.removeEventListener(READY_EVENT, checkReady); whenDocumentReady(callback, doc); } }; doc.addEventListener(READY_EVENT, checkReady); } else if (callback) { callback(); } } function markTargetLoaded(event) { event.target.__loaded = true; } // call <callback> when we ensure all imports have loaded function watchImportsLoad(callback, doc) { var imports = doc.querySelectorAll('link[rel=import]'); var loaded = 0, l = imports.length; function checkDone(d) { if ((loaded == l) && callback) { callback(); } } function loadedImport(e) { markTargetLoaded(e); loaded++; checkDone(); } if (l) { for (var i=0, imp; (i<l) && (imp=imports[i]); i++) { if (isImportLoaded(imp)) { loadedImport.call(imp, {target: imp}); } else { imp.addEventListener('load', loadedImport); imp.addEventListener('error', loadedImport); } } } else { checkDone(); } } // NOTE: test for native imports loading is based on explicitly watching // all imports (see below). // However, we cannot rely on this entirely without watching the entire document // for import links. For perf reasons, currently only head is watched. // Instead, we fallback to checking if the import property is available // and the document is not itself loading. function isImportLoaded(link) { return useNative ? link.__loaded || (link.import && link.import.readyState !== 'loading') : link.__importParsed; } // TODO(sorvell): Workaround for // https://www.w3.org/Bugs/Public/show_bug.cgi?id=25007, should be removed when // this bug is addressed. // (1) Install a mutation observer to see when HTMLImports have loaded // (2) if this script is run during document load it will watch any existing // imports for loading. // // NOTE: The workaround has restricted functionality: (1) it's only compatible // with imports that are added to document.head since the mutation observer // watches only head for perf reasons, (2) it requires this script // to run before any imports have completed loading. if (useNative) { new MutationObserver(function(mxns) { for (var i=0, l=mxns.length, m; (i < l) && (m=mxns[i]); i++) { if (m.addedNodes) { handleImports(m.addedNodes); } } }).observe(document.head, {childList: true}); function handleImports(nodes) { for (var i=0, l=nodes.length, n; (i<l) && (n=nodes[i]); i++) { if (isImport(n)) { handleImport(n); } } } function isImport(element) { return element.localName === 'link' && element.rel === 'import'; } function handleImport(element) { var loaded = element.import; if (loaded) { markTargetLoaded({target: element}); } else { element.addEventListener('load', markTargetLoaded); element.addEventListener('error', markTargetLoaded); } } // make sure to catch any imports that are in the process of loading // when this script is run. (function() { if (document.readyState === 'loading') { var imports = document.querySelectorAll('link[rel=import]'); for (var i=0, l=imports.length, imp; (i<l) && (imp=imports[i]); i++) { handleImport(imp); } } })(); } // Fire the 'HTMLImportsLoaded' event when imports in document at load time // have loaded. This event is required to simulate the script blocking // behavior of native imports. A main document script that needs to be sure // imports have loaded should wait for this event. whenReady(function() { HTMLImports.ready = true; HTMLImports.readyTime = new Date().getTime(); rootDocument.dispatchEvent( new CustomEvent('HTMLImportsLoaded', {bubbles: true}) ); }); // exports scope.IMPORT_LINK_TYPE = IMPORT_LINK_TYPE; scope.useNative = useNative; scope.rootDocument = rootDocument; scope.whenReady = whenReady; scope.isIE = isIE; })(HTMLImports); (function(scope) { // TODO(sorvell): It's desireable to provide a default stylesheet // that's convenient for styling unresolved elements, but // it's cumbersome to have to include this manually in every page. // It would make sense to put inside some HTMLImport but // the HTMLImports polyfill does not allow loading of stylesheets // that block rendering. Therefore this injection is tolerated here. var style = document.createElement('style'); style.textContent = '' + 'body {' + 'transition: opacity ease-in 0.2s;' + ' } \n' + 'body[unresolved] {' + 'opacity: 0; display: block; overflow: hidden;' + ' } \n' ; var head = document.querySelector('head'); head.insertBefore(style, head.firstChild); })(Platform); /* Build only script. Ensures scripts needed for basic x-platform compatibility will be run when platform.js is not loaded. */ } (function(global) { 'use strict'; var testingExposeCycleCount = global.testingExposeCycleCount; // 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; } // Firefox OS Apps do not allow eval. This feature detection is very hacky // but even if some other platform adds support for this function this code // will continue to work. if (typeof navigator != 'undefined' && navigator.getDeviceStorage) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); function isIndex(s) { return +s === s >>> 0 && s !== ''; } function toNumber(s) { return +s; } function isObject(obj) { return obj === Object(obj); } var numberIsNaN = global.Number.isNaN || function(value) { return typeof value === 'number' && global.isNaN(value); } function areSameValue(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; if (numberIsNaN(left) && numberIsNaN(right)) return true; return left !== left && right !== right; } 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 identStart = '[\$_a-zA-Z]'; var identPart = '[\$_a-zA-Z0-9]'; var identRegExp = new RegExp('^' + identStart + '+' + identPart + '*' + '$'); function getPathCharType(char) { if (char === undefined) return 'eof'; var code = char.charCodeAt(0); switch(code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' case 0x30: // 0 return char; case 0x5F: // _ case 0x24: // $ return 'ident'; case 0x20: // Space case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws'; } // a-z, A-Z if ((0x61 <= code && code <= 0x7A) || (0x41 <= code && code <= 0x5A)) return 'ident'; // 1-9 if (0x31 <= code && code <= 0x39) return 'number'; return 'else'; } var pathStateMachine = { 'beforePath': { 'ws': ['beforePath'], 'ident': ['inIdent', 'append'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'inPath': { 'ws': ['inPath'], '.': ['beforeIdent'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'beforeIdent': { 'ws': ['beforeIdent'], 'ident': ['inIdent', 'append'] }, 'inIdent': { 'ident': ['inIdent', 'append'], '0': ['inIdent', 'append'], 'number': ['inIdent', 'append'], 'ws': ['inPath', 'push'], '.': ['beforeIdent', 'push'], '[': ['beforeElement', 'push'], 'eof': ['afterPath', 'push'] }, 'beforeElement': { 'ws': ['beforeElement'], '0': ['afterZero', 'append'], 'number': ['inIndex', 'append'], "'": ['inSingleQuote', 'append', ''], '"': ['inDoubleQuote', 'append', ''] }, 'afterZero': { 'ws': ['afterElement', 'push'], ']': ['inPath', 'push'] }, 'inIndex': { '0': ['inIndex', 'append'], 'number': ['inIndex', 'append'], 'ws': ['afterElement'], ']': ['inPath', 'push'] }, 'inSingleQuote': { "'": ['afterElement'], 'eof': ['error'], 'else': ['inSingleQuote', 'append'] }, 'inDoubleQuote': { '"': ['afterElement'], 'eof': ['error'], 'else': ['inDoubleQuote', 'append'] }, 'afterElement': { 'ws': ['afterElement'], ']': ['inPath', 'push'] } } function noop() {} function parsePath(path) { var keys = []; var index = -1; var c, newChar, key, type, transition, action, typeMap, mode = 'beforePath'; var actions = { push: function() { if (key === undefined) return; keys.push(key); key = undefined; }, append: function() { if (key === undefined) key = newChar else key += newChar; } }; function maybeUnescapeQuote() { if (index >= path.length) return; var nextChar = path[index + 1]; if ((mode == 'inSingleQuote' && nextChar == "'") || (mode == 'inDoubleQuote' && nextChar == '"')) { index++; newChar = nextChar; actions.append(); return true; } } while (mode) { index++; c = path[index]; if (c == '\\' && maybeUnescapeQuote(mode)) continue; type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap['else'] || 'error'; if (transition == 'error') return; // parse error; mode = transition[0]; action = actions[transition[1]] || noop; newChar = transition[2] === undefined ? c : transition[2]; action(); if (mode === 'afterPath') { return keys; } } return; // parse error } function isIdent(s) { return identRegExp.test(s); } var constructorIsPrivate = {}; function Path(parts, privateToken) { if (privateToken !== constructorIsPrivate) throw Error('Use Path.get to retrieve path objects'); for (var i = 0; i < parts.length; i++) { this.push(String(parts[i])); } if (hasEval && this.length) { this.getValueFrom = this.compiledGetValueFromFn(); } } // TODO(rafaelw): Make simple LRU cache var pathCache = {}; function getPath(pathString) { if (pathString instanceof Path) return pathString; if (pathString == null || pathString.length == 0) pathString = ''; if (typeof pathString != 'string') { if (isIndex(pathString.length)) { // Constructed with array-like (pre-parsed) keys return new Path(pathString, constructorIsPrivate); } pathString = String(pathString); } var path = pathCache[pathString]; if (path) return path; var parts = parsePath(pathString); if (!parts) return invalidPath; var path = new Path(parts, constructorIsPrivate); pathCache[pathString] = path; return path; } Path.get = getPath; function formatAccessor(key) { if (isIndex(key)) { return '[' + key + ']'; } else { return '["' + key.replace(/"/g, '\\"') + '"]'; } } Path.prototype = createObject({ __proto__: [], valid: true, toString: function() { var pathString = ''; for (var i = 0; i < this.length; i++) { var key = this[i]; if (isIdent(key)) { pathString += i ? '.' + key : key; } else { pathString += formatAccessor(key); } } return pathString; }, getValueFrom: function(obj, directObserver) { for (var i = 0; i < this.length; i++) { if (obj == null) return; obj = obj[this[i]]; } return obj; }, iterateObjects: function(obj, observe) { for (var i = 0; i < this.length; i++) { if (i) obj = obj[this[i - 1]]; if (!isObject(obj)) return; observe(obj, this[i]); } }, compiledGetValueFromFn: function() { var str = ''; var pathString = 'obj'; str += 'if (obj != null'; var i = 0; var key; for (; i < (this.length - 1); i++) { key = this[i]; pathString += isIdent(key) ? '.' + key : formatAccessor(key); str += ' &&\n ' + pathString + ' != null'; } str += ')\n'; var key = this[i]; pathString += isIdent(key) ? '.' + key : formatAccessor(key); str += ' return ' + pathString + ';\nelse\n return undefined;'; return new Function('obj', str); }, setValueFrom: function(obj, value) { if (!this.length) return false; for (var i = 0; i < this.length - 1; i++) { if (!isObject(obj)) return false; obj = obj[this[i]]; } if (!isObject(obj)) return false; obj[this[i]] = value; return true; } }); var invalidPath = new Path('', constructorIsPrivate); invalidPath.valid = false; invalidPath.getValueFrom = invalidPath.setValueFrom = function() {}; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (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(){ return function(fn) { return Promise.resolve().then(fn); } })() : (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 observedSetCache = []; function newObservedSet() { var observerCount = 0; var observers = []; var objects = []; var rootObj; var rootObjProps; function observe(obj, prop) { if (!obj) return; if (obj === rootObj) rootObjProps[prop] = true; if (objects.indexOf(obj) < 0) { objects.push(obj); Object.observe(obj, callback); } observe(Object.getPrototypeOf(obj), prop); } function allRootObjNonObservedProps(recs) { for (var i = 0; i < recs.length; i++) { var rec = recs[i]; if (rec.object !== rootObj || rootObjProps[rec.name] || rec.type === 'setPrototype') { return false; } } return true; } function callback(recs) { if (allRootObjNonObservedProps(recs)) return; var observer; for (var i = 0; i < observers.length; i++) { observer = observers[i]; if (observer.state_ == OPENED) { observer.iterateObjects_(observe); } } for (var i = 0; i < observers.length; i++) { observer = observers[i]; if (observer.state_ == OPENED) { observer.check_(); } } } var record = { objects: objects, get rootObject() { return rootObj; }, set rootObject(value) { rootObj = value; rootObjProps = {}; }, open: function(obs, object) { observers.push(obs); observerCount++; obs.iterateObjects_(observe); }, close: function(obs) { observerCount--; if (observerCount > 0) { return; } for (var i = 0; i < objects.length; i++) { Object.unobserve(objects[i], callback); Observer.unobservedCount++; } observers.length = 0; objects.length = 0; rootObj = undefined; rootObjProps = undefined; observedSetCache.push(this); if (lastObservedSet === this) lastObservedSet = null; }, }; return record; } var lastObservedSet; function getObservedSet(observer, obj) { if (!lastObservedSet || lastObservedSet.rootObject !== obj) { lastObservedSet = observedSetCache.pop() || newObservedSet(); lastObservedSet.rootObject = obj; } lastObservedSet.open(observer, obj); return lastObservedSet; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var RESETTING = 3; 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; global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) 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 (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_; } }); function ArrayObserver(array) { if (!Array.isArray(array)) throw Error('Provided object is not an Array'); ObjectObserver.call(this, array); } ArrayObserver.prototype = createObject({ __proto__: ObjectObserver.prototype, arrayObserve: true, copyObject: function(arr) { return arr.slice(); }, check_: function(changeRecords) { var splices; if (hasObserve) { if (!changeRecords) return false; splices = projectArraySplices(this.value_, changeRecords); } else { splices = calcSplices(this.value_, 0, this.value_.length, this.oldObject_, 0, this.oldObject_.length); } if (!splices || !splices.length) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([splices]); return true; } }); ArrayObserver.applySplices = function(previous, current, splices) { splices.forEach(function(splice) { var spliceArgs = [splice.index, splice.removed.length]; var addIndex = splice.index; while (addIndex < splice.index + splice.addedCount) { spliceArgs.push(current[addIndex]); addIndex++; } Array.prototype.splice.apply(previous, spliceArgs); }); }; function PathObserver(object, path) { Observer.call(this); this.object_ = object; this.path_ = getPath(path); this.directObserver_ = undefined; } PathObserver.prototype = createObject({ __proto__: Observer.prototype, get path() { return this.path_; }, connect_: function() { if (hasObserve) this.directObserver_ = getObservedSet(this, this.object_); this.check_(undefined, true); }, disconnect_: function() { this.value_ = undefined; if (this.directObserver_) { this.directObserver_.close(this); this.directObserver_ = undefined; } }, iterateObjects_: function(observe) { this.path_.iterateObjects(this.object_, observe); }, check_: function(changeRecords, skipChanges) { var oldValue = this.value_; this.value_ = this.path_.getValueFrom(this.object_); if (skipChanges || areSameValue(this.value_, oldValue)) return false; this.report_([this.value_, oldValue, this]); return true; }, setValue: function(newValue) { if (this.path_) this.path_.setValueFrom(this.object_, newValue); } }); function CompoundObserver(reportChangesOnOpen) { Observer.call(this); this.reportChangesOnOpen_ = reportChangesOnOpen; this.value_ = []; this.directObserver_ = undefined; this.observed_ = []; } var observerSentinel = {}; CompoundObserver.prototype = createObject({ __proto__: Observer.prototype, connect_: function() { if (hasObserve) { var object; var needsDirectObserver = false; for (var i = 0; i < this.observed_.length; i += 2) { object = this.observed_[i] if (object !== observerSentinel) { needsDirectObserver = true; break; } } if (needsDirectObserver) this.directObserver_ = getObservedSet(this, object); } this.check_(undefined, !this.reportChangesOnOpen_); }, disconnect_: function() { for (var i = 0; i < this.observed_.length; i += 2) { if (this.observed_[i] === observerSentinel) this.observed_[i + 1].close(); } this.observed_.length = 0; this.value_.length = 0; if (this.directObserver_) { this.directObserver_.close(this); this.directObserver_ = undefined; } }, addPath: function(object, path) { if (this.state_ != UNOPENED && this.state_ != RESETTING) throw Error('Cannot add paths once started.'); var path = getPath(path); this.observed_.push(object, path); if (!this.reportChangesOnOpen_) return; var index = this.observed_.length / 2 - 1; this.value_[index] = path.getValueFrom(object); }, addObserver: function(observer) { if (this.state_ != UNOPENED && this.state_ != RESETTING) throw Error('Cannot add observers once started.'); this.observed_.push(observerSentinel, observer); if (!this.reportChangesOnOpen_) return; var index = this.observed_.length / 2 - 1; this.value_[index] = observer.open(this.deliver, this); }, startReset: function() { if (this.state_ != OPENED) throw Error('Can only reset while open'); this.state_ = RESETTING; this.disconnect_(); }, finishReset: function() { if (this.state_ != RESETTING) throw Error('Can only finishReset after startReset'); this.state_ = OPENED; this.connect_(); return this.value_; }, iterateObjects_: function(observe) { var object; for (var i = 0; i < this.observed_.length; i += 2) { object = this.observed_[i] if (object !== observerSentinel) this.observed_[i + 1].iterateObjects(object, observe) } }, check_: function(changeRecords, skipChanges) { var oldValues; for (var i = 0; i < this.observed_.length; i += 2) { var object = this.observed_[i]; var path = this.observed_[i+1]; var value; if (object === observerSentinel) { var observable = path; value = this.state_ === UNOPENED ? observable.open(this.deliver, this) : observable.discardChanges(); } else { value = path.getValueFrom(object); } if (skipChanges) { this.value_[i / 2] = value; continue; } if (areSameValue(value, this.value_[i / 2])) continue; oldValues = oldValues || []; oldValues[i / 2] = this.value_[i / 2]; this.value_[i / 2] = value; } if (!oldValues) return false; // TODO(rafaelw): Having observed_ as the third callback arg here is // pretty lame API. Fix. this.report_([this.value_, oldValues, this.observed_]); return true; } }); function identFn(value) { return value; } function ObserverTransform(observable, getValueFn, setValueFn, dontPassThroughSet) { this.callback_ = undefined; this.target_ = undefined; this.value_ = undefined; this.observable_ = observable; this.getValueFn_ = getValueFn || identFn; this.setValueFn_ = setValueFn || identFn; // TODO(rafaelw): This is a temporary hack. PolymerExpressions needs this // at the moment because of a bug in it's dependency tracking. this.dontPassThroughSet_ = dontPassThroughSet; } ObserverTransform.prototype = { open: function(callback, target) { this.callback_ = callback; this.target_ = target; this.value_ = this.getValueFn_(this.observable_.open(this.observedCallback_, this)); return this.value_; }, observedCallback_: function(value) { value = this.getValueFn_(value); if (areSameValue(value, this.value_)) return; var oldValue = this.value_; this.value_ = value; this.callback_.call(this.target_, this.value_, oldValue); }, discardChanges: function() { this.value_ = this.getValueFn_(this.observable_.discardChanges()); return this.value_; }, deliver: function() { return this.observable_.deliver(); }, setValue: function(value) { value = this.setValueFn_(value); if (!this.dontPassThroughSet_ && this.observable_.setValue) return this.observable_.setValue(value); }, close: function() { if (this.observable_) this.observable_.close(); this.callback_ = undefined; this.target_ = undefined; this.observable_ = undefined; this.value_ = undefined; this.getValueFn_ = undefined; this.setValueFn_ = undefined; } } 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 }; } function newSplice(index, removed, addedCount) { return { index: index, removed: removed, addedCount: addedCount }; } var EDIT_LEAVE = 0; var EDIT_UPDATE = 1; var EDIT_ADD = 2; var EDIT_DELETE = 3; function ArraySplice() {} ArraySplice.prototype = { // Note: This function is *based* on the computation of the Levenshtein // "edit" distance. The one change is that "updates" are treated as two // edits - not one. With Array splices, an update is really a delete // followed by an add. By retaining this, we optimize for "keeping" the // maximum array items in the original array. For example: // // 'xxxx123' -> '123yyyy' // // With 1-edit updates, the shortest path would be just to update all seven // characters. With 2-edit updates, we delete 4, leave 3, and add 4. This // leaves the substring '123' intact. calcEditDistances: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { // "Deletion" columns var rowCount = oldEnd - oldStart + 1; var columnCount = currentEnd - currentStart + 1; var distances = new Array(rowCount); // "Addition" rows. Initialize null column. for (var i = 0; i < rowCount; i++) { distances[i] = new Array(columnCount); distances[i][0] = i; } // Initialize null row for (var j = 0; j < columnCount; j++) distances[0][j] = j; for (var i = 1; i < rowCount; i++) { for (var j = 1; j < columnCount; j++) { if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) distances[i][j] = distances[i - 1][j - 1]; else { var north = distances[i - 1][j] + 1; var west = distances[i][j - 1] + 1; distances[i][j] = north < west ? north : west; } } } return distances; }, // This starts at the final weight, and walks "backward" by finding // the minimum previous weight recursively until the origin of the weight // matrix. spliceOperationsFromEditDistances: function(distances) { var i = distances.length - 1; var j = distances[0].length - 1; var current = distances[i][j]; var edits = []; while (i > 0 || j > 0) { if (i == 0) { edits.push(EDIT_ADD); j--; continue; } if (j == 0) { edits.push(EDIT_DELETE); i--; continue; } var northWest = distances[i - 1][j - 1]; var west = distances[i - 1][j]; var north = distances[i][j - 1]; var min; if (west < north) min = west < northWest ? west : northWest; else min = north < northWest ? north : northWest; if (min == northWest) { if (northWest == current) { edits.push(EDIT_LEAVE); } else { edits.push(EDIT_UPDATE); current = northWest; } i--; j--; } else if (min == west) { edits.push(EDIT_DELETE); i--; current = west; } else { edits.push(EDIT_ADD); j--; current = north; } } edits.reverse(); return edits; }, /** * Splice Projection functions: * * A splice map is a representation of how a previous array of items * was transformed into a new array of items. Conceptually it is a list of * tuples of * * <index, removed, addedCount> * * which are kept in ascending index order of. The tuple represents that at * the |index|, |removed| sequence of items were removed, and counting forward * from |index|, |addedCount| items were added. */ /** * Lacking individual splice mutation information, the minimal set of * splices can be synthesized given the previous state and final state of an * array. The basic approach is to calculate the edit distance matrix and * choose the shortest path through it. * * Complexity: O(l * p) * l: The length of the current array * p: The length of the old array */ calcSplices: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { var prefixCount = 0; var suffixCount = 0; var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); if (currentStart == 0 && oldStart == 0) prefixCount = this.sharedPrefix(current, old, minLength); if (currentEnd == current.length && oldEnd == old.length) suffixCount = this.sharedSuffix(current, old, minLength - prefixCount); currentStart += prefixCount; oldStart += prefixCount; currentEnd -= suffixCount; oldEnd -= suffixCount; if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return []; if (currentStart == currentEnd) { var splice = newSplice(currentStart, [], 0); while (oldStart < oldEnd) splice.removed.push(old[oldStart++]); return [ splice ]; } else if (oldStart == oldEnd) return [ newSplice(currentStart, [], currentEnd - currentStart) ]; var ops = this.spliceOperationsFromEditDistances( this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); var splice = undefined; var splices = []; var index = currentStart; var oldIndex = oldStart; for (var i = 0; i < ops.length; i++) { switch(ops[i]) { case EDIT_LEAVE: if (splice) { splices.push(splice); splice = undefined; } index++; oldIndex++; break; case EDIT_UPDATE: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; splice.removed.push(old[oldIndex]); oldIndex++; break; case EDIT_ADD: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; break; case EDIT_DELETE: if (!splice) splice = newSplice(index, [], 0); splice.removed.push(old[oldIndex]); oldIndex++; break; } } if (splice) { splices.push(splice); } return splices; }, sharedPrefix: function(current, old, searchLength) { for (var i = 0; i < searchLength; i++) if (!this.equals(current[i], old[i])) return i; return searchLength; }, sharedSuffix: function(current, old, searchLength) { var index1 = current.length; var index2 = old.length; var count = 0; while (count < searchLength && this.equals(current[--index1], old[--index2])) count++; return count; }, calculateSplices: function(current, previous) { return this.calcSplices(current, 0, current.length, previous, 0, previous.length); }, equals: function(currentValue, previousValue) { return currentValue === previousValue; } }; var arraySplice = new ArraySplice(); function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { return arraySplice.calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd); } function intersect(start1, end1, start2, end2) { // Disjoint if (end1 < start2 || end2 < start1) return -1; // Adjacent if (end1 == start2 || end2 == start1) return 0; // Non-zero intersect, span1 first if (start1 < start2) { if (end1 < end2) return end1 - start2; // Overlap else return end2 - start2; // Contained } else { // Non-zero intersect, span2 first if (end2 < end1) return end2 - start1; // Overlap else return end1 - start1; // Contained } } function mergeSplice(splices, index, removed, addedCount) { var splice = newSplice(index, removed, addedCount); var inserted = false; var insertionOffset = 0; for (var i = 0; i < splices.length; i++) { var current = splices[i]; current.index += insertionOffset; if (inserted) continue; var intersectCount = intersect(splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount); if (intersectCount >= 0) { // Merge the two splices splices.splice(i, 1); i--; insertionOffset -= current.addedCount - current.removed.length; splice.addedCount += current.addedCount - intersectCount; var deleteCount = splice.removed.length + current.removed.length - intersectCount; if (!splice.addedCount && !deleteCount) { // merged splice is a noop. discard. inserted = true; } else { var removed = current.removed; if (splice.index < current.index) { // some prefix of splice.removed is prepended to current.removed. var prepend = splice.removed.slice(0, current.index - splice.index); Array.prototype.push.apply(prepend, removed); removed = prepend; } if (splice.index + splice.removed.length > current.index + current.addedCount) { // some suffix of splice.removed is appended to current.removed. var append = splice.removed.slice(current.index + current.addedCount - splice.index); Array.prototype.push.apply(removed, append); } splice.removed = removed; if (current.index < splice.index) { splice.index = current.index; } } } else if (splice.index < current.index) { // Insert splice here. inserted = true; splices.splice(i, 0, splice); i++; var offset = splice.addedCount - splice.removed.length current.index += offset; insertionOffset += offset; } } if (!inserted) splices.push(splice); } function createInitialSplices(array, changeRecords) { var splices = []; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; switch(record.type) { case 'splice': mergeSplice(splices, record.index, record.removed.slice(), record.addedCount); break; case 'add': case 'update': case 'delete': if (!isIndex(record.name)) continue; var index = toNumber(record.name); if (index < 0) continue; mergeSplice(splices, index, [record.oldValue], 1); break; default: console.error('Unexpected record type: ' + JSON.stringify(record)); break; } } return splices; } function projectArraySplices(array, changeRecords) { var splices = []; createInitialSplices(array, changeRecords).forEach(function(splice) { if (splice.addedCount == 1 && splice.removed.length == 1) { if (splice.removed[0] !== array[splice.index]) splices.push(splice); return }; splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length)); }); return splices; } // Export the observe-js object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, export as a global object. var expose = global; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { expose = exports = module.exports; } expose = exports; } expose.Observer = Observer; expose.Observer.runEOM_ = runEOM; expose.Observer.observerSentinel_ = observerSentinel; // for testing. expose.Observer.hasObjectObserve = hasObserve; expose.ArrayObserver = ArrayObserver; expose.ArrayObserver.calculateSplices = function(current, previous) { return arraySplice.calculateSplices(current, previous); }; expose.ArraySplice = ArraySplice; expose.ObjectObserver = ObjectObserver; expose.PathObserver = PathObserver; expose.CompoundObserver = CompoundObserver; expose.Path = Path; expose.ObserverTransform = ObserverTransform; })(typeof global !== 'undefined' && global && typeof module !== 'undefined' && module ? global : this || window); // Copyright (c) 2014 The Polymer Project Authors. All rights reserved. // This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt // The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt // The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt // Code distributed by Google as part of the polymer project is also // subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt (function(global) { 'use strict'; var filter = Array.prototype.filter.call.bind(Array.prototype.filter); function getTreeScope(node) { while (node.parentNode) { node = node.parentNode; } return typeof node.getElementById === 'function' ? node : null; } Node.prototype.bind = function(name, observable) { console.error('Unhandled binding to Node: ', this, name, observable); }; Node.prototype.bindFinished = function() {}; function updateBindings(node, name, binding) { var bindings = node.bindings_; if (!bindings) bindings = node.bindings_ = {}; if (bindings[name]) binding[name].close(); return bindings[name] = binding; } function returnBinding(node, name, binding) { return binding; } function sanitizeValue(value) { return value == null ? '' : value; } function updateText(node, value) { node.data = sanitizeValue(value); } function textBinding(node) { return function(value) { return updateText(node, value); }; } var maybeUpdateBindings = returnBinding; Object.defineProperty(Platform, 'enableBindingsReflection', { get: function() { return maybeUpdateBindings === updateBindings; }, set: function(enable) { maybeUpdateBindings = enable ? updateBindings : returnBinding; return enable; }, configurable: true }); Text.prototype.bind = function(name, value, oneTime) { if (name !== 'textContent') return Node.prototype.bind.call(this, name, value, oneTime); if (oneTime) return updateText(this, value); var observable = value; updateText(this, observable.open(textBinding(this))); return maybeUpdateBindings(this, name, observable); } function updateAttribute(el, name, conditional, value) { if (conditional) { if (value) el.setAttribute(name, ''); else el.removeAttribute(name); return; } el.setAttribute(name, sanitizeValue(value)); } function attributeBinding(el, name, conditional) { return function(value) { updateAttribute(el, name, conditional, value); }; } Element.prototype.bind = function(name, value, oneTime) { var conditional = name[name.length - 1] == '?'; if (conditional) { this.removeAttribute(name); name = name.slice(0, -1); } if (oneTime) return updateAttribute(this, name, conditional, value); var observable = value; updateAttribute(this, name, conditional, observable.open(attributeBinding(this, name, conditional))); return maybeUpdateBindings(this, name, observable); }; var checkboxEventType; (function() { // Attempt to feature-detect which event (change or click) is fired first // for checkboxes. var div = document.createElement('div'); var checkbox = div.appendChild(document.createElement('input')); checkbox.setAttribute('type', 'checkbox'); var first; var count = 0; checkbox.addEventListener('click', function(e) { count++; first = first || 'click'; }); checkbox.addEventListener('change', function() { count++; first = first || 'change'; }); var event = document.createEvent('MouseEvent'); event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); checkbox.dispatchEvent(event); // WebKit/Blink don't fire the change event if the element is outside the // document, so assume 'change' for that case. checkboxEventType = count == 1 ? 'change' : first; })(); function getEventForInputType(element) { switch (element.type) { case 'checkbox': return checkboxEventType; case 'radio': case 'select-multiple': case 'select-one': return 'change'; case 'range': if (/Trident|MSIE/.test(navigator.userAgent)) return 'change'; default: return 'input'; } } function updateInput(input, property, value, santizeFn) { input[property] = (santizeFn || sanitizeValue)(value); } function inputBinding(input, property, santizeFn) { return function(value) { return updateInput(input, property, value, santizeFn); } } function noop() {} function bindInputEvent(input, property, observable, postEventFn) { var eventType = getEventForInputType(input); function eventHandler() { observable.setValue(input[property]); observable.discardChanges(); (postEventFn || noop)(input); Platform.performMicrotaskCheckpoint(); } input.addEventListener(eventType, eventHandler); return { close: function() { input.removeEventListener(eventType, eventHandler); observable.close(); }, observable_: observable } } function booleanSanitize(value) { return Boolean(value); } // |element| is assumed to be an HTMLInputElement with |type| == 'radio'. // Returns an array containing all radio buttons other than |element| that // have the same |name|, either in the form that |element| belongs to or, // if no form, in the document tree to which |element| belongs. // // This implementation is based upon the HTML spec definition of a // "radio button group": // http://www.whatwg.org/specs/web-apps/current-work/multipage/number-state.html#radio-button-group // function getAssociatedRadioButtons(element) { if (element.form) { return filter(element.form.elements, function(el) { return el != element && el.tagName == 'INPUT' && el.type == 'radio' && el.name == element.name; }); } else { var treeScope = getTreeScope(element); if (!treeScope) return []; var radios = treeScope.querySelectorAll( 'input[type="radio"][name="' + element.name + '"]'); return filter(radios, function(el) { return el != element && !el.form; }); } } function checkedPostEvent(input) { // Only the radio button that is getting checked gets an event. We // therefore find all the associated radio buttons and update their // check binding manually. if (input.tagName === 'INPUT' && input.type === 'radio') { getAssociatedRadioButtons(input).forEach(function(radio) { var checkedBinding = radio.bindings_.checked; if (checkedBinding) { // Set the value directly to avoid an infinite call stack. checkedBinding.observable_.setValue(false); } }); } } HTMLInputElement.prototype.bind = function(name, value, oneTime) { if (name !== 'value' && name !== 'checked') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute(name); var sanitizeFn = name == 'checked' ? booleanSanitize : sanitizeValue; var postEventFn = name == 'checked' ? checkedPostEvent : noop; if (oneTime) return updateInput(this, name, value, sanitizeFn); var observable = value; var binding = bindInputEvent(this, name, observable, postEventFn); updateInput(this, name, observable.open(inputBinding(this, name, sanitizeFn)), sanitizeFn); // Checkboxes may need to update bindings of other checkboxes. return updateBindings(this, name, binding); } HTMLTextAreaElement.prototype.bind = function(name, value, oneTime) { if (name !== 'value') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute('value'); if (oneTime) return updateInput(this, 'value', value); var observable = value; var binding = bindInputEvent(this, 'value', observable); updateInput(this, 'value', observable.open(inputBinding(this, 'value', sanitizeValue))); return maybeUpdateBindings(this, name, binding); } function updateOption(option, value) { var parentNode = option.parentNode;; var select; var selectBinding; var oldValue; if (parentNode instanceof HTMLSelectElement && parentNode.bindings_ && parentNode.bindings_.value) { select = parentNode; selectBinding = select.bindings_.value; oldValue = select.value; } option.value = sanitizeValue(value); if (select && select.value != oldValue) { selectBinding.observable_.setValue(select.value); selectBinding.observable_.discardChanges(); Platform.performMicrotaskCheckpoint(); } } function optionBinding(option) { return function(value) { updateOption(option, value); } } HTMLOptionElement.prototype.bind = function(name, value, oneTime) { if (name !== 'value') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute('value'); if (oneTime) return updateOption(this, value); var observable = value; var binding = bindInputEvent(this, 'value', observable); updateOption(this, observable.open(optionBinding(this))); return maybeUpdateBindings(this, name, binding); } HTMLSelectElement.prototype.bind = function(name, value, oneTime) { if (name === 'selectedindex') name = 'selectedIndex'; if (name !== 'selectedIndex' && name !== 'value') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute(name); if (oneTime) return updateInput(this, name, value); var observable = value; var binding = bindInputEvent(this, name, observable); updateInput(this, name, observable.open(inputBinding(this, name))); // Option update events may need to access select bindings. return updateBindings(this, name, binding); } })(this); // Copyright (c) 2014 The Polymer Project Authors. All rights reserved. // This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt // The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt // The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt // Code distributed by Google as part of the polymer project is also // subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt (function(global) { 'use strict'; function assert(v) { if (!v) throw new Error('Assertion failed'); } var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); function getFragmentRoot(node) { var p; while (p = node.parentNode) { node = p; } return node; } function searchRefId(node, id) { if (!id) return; var ref; var selector = '#' + id; while (!ref) { node = getFragmentRoot(node); if (node.protoContent_) ref = node.protoContent_.querySelector(selector); else if (node.getElementById) ref = node.getElementById(id); if (ref || !node.templateCreator_) break node = node.templateCreator_; } return ref; } function getInstanceRoot(node) { while (node.parentNode) { node = node.parentNode; } return node.templateCreator_ ? node : null; } var Map; if (global.Map && typeof global.Map.prototype.forEach === 'function') { Map = global.Map; } else { Map = function() { this.keys = []; this.values = []; }; Map.prototype = { set: function(key, value) { var index = this.keys.indexOf(key); if (index < 0) { this.keys.push(key); this.values.push(value); } else { this.values[index] = value; } }, get: function(key) { var index = this.keys.indexOf(key); if (index < 0) return; return this.values[index]; }, delete: function(key, value) { var index = this.keys.indexOf(key); if (index < 0) return false; this.keys.splice(index, 1); this.values.splice(index, 1); return true; }, forEach: function(f, opt_this) { for (var i = 0; i < this.keys.length; i++) f.call(opt_this || this, this.values[i], this.keys[i], this); } }; } // JScript does not have __proto__. We wrap all object literals with // createObject which uses Object.create, Object.defineProperty and // Object.getOwnPropertyDescriptor to create a new object that does the exact // same thing. The main downside to this solution is that we have to extract // all those property descriptors for IE. 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; }; // IE does not support have Document.prototype.contains. if (typeof document.contains != 'function') { Document.prototype.contains = function(node) { if (node === this || node.parentNode === this) return true; return this.documentElement.contains(node); } } var BIND = 'bind'; var REPEAT = 'repeat'; var IF = 'if'; var templateAttributeDirectives = { 'template': true, 'repeat': true, 'bind': true, 'ref': true, 'if': true }; var semanticTemplateElements = { 'THEAD': true, 'TBODY': true, 'TFOOT': true, 'TH': true, 'TR': true, 'TD': true, 'COLGROUP': true, 'COL': true, 'CAPTION': true, 'OPTION': true, 'OPTGROUP': true }; var hasTemplateElement = typeof HTMLTemplateElement !== 'undefined'; if (hasTemplateElement) { // TODO(rafaelw): Remove when fix for // https://codereview.chromium.org/164803002/ // makes it to Chrome release. (function() { var t = document.createElement('template'); var d = t.content.ownerDocument; var html = d.appendChild(d.createElement('html')); var head = html.appendChild(d.createElement('head')); var base = d.createElement('base'); base.href = document.baseURI; head.appendChild(base); })(); } var allTemplatesSelectors = 'template, ' + Object.keys(semanticTemplateElements).map(function(tagName) { return tagName.toLowerCase() + '[template]'; }).join(', '); function isSVGTemplate(el) { return el.tagName == 'template' && el.namespaceURI == 'http://www.w3.org/2000/svg'; } function isHTMLTemplate(el) { return el.tagName == 'TEMPLATE' && el.namespaceURI == 'http://www.w3.org/1999/xhtml'; } function isAttributeTemplate(el) { return Boolean(semanticTemplateElements[el.tagName] && el.hasAttribute('template')); } function isTemplate(el) { if (el.isTemplate_ === undefined) el.isTemplate_ = el.tagName == 'TEMPLATE' || isAttributeTemplate(el); return el.isTemplate_; } // FIXME: Observe templates being added/removed from documents // FIXME: Expose imperative API to decorate and observe templates in // "disconnected tress" (e.g. ShadowRoot) document.addEventListener('DOMContentLoaded', function(e) { bootstrapTemplatesRecursivelyFrom(document); // FIXME: Is this needed? Seems like it shouldn't be. Platform.performMicrotaskCheckpoint(); }, false); function forAllTemplatesFrom(node, fn) { var subTemplates = node.querySelectorAll(allTemplatesSelectors); if (isTemplate(node)) fn(node) forEach(subTemplates, fn); } function bootstrapTemplatesRecursivelyFrom(node) { function bootstrap(template) { if (!HTMLTemplateElement.decorate(template)) bootstrapTemplatesRecursivelyFrom(template.content); } forAllTemplatesFrom(node, bootstrap); } if (!hasTemplateElement) { /** * This represents a <template> element. * @constructor * @extends {HTMLElement} */ global.HTMLTemplateElement = function() { throw TypeError('Illegal constructor'); }; } var hasProto = '__proto__' in {}; function mixin(to, from) { Object.getOwnPropertyNames(from).forEach(function(name) { Object.defineProperty(to, name, Object.getOwnPropertyDescriptor(from, name)); }); } // http://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html#dfn-template-contents-owner function getOrCreateTemplateContentsOwner(template) { var doc = template.ownerDocument if (!doc.defaultView) return doc; var d = doc.templateContentsOwner_; if (!d) { // TODO(arv): This should either be a Document or HTMLDocument depending // on doc. d = doc.implementation.createHTMLDocument(''); while (d.lastChild) { d.removeChild(d.lastChild); } doc.templateContentsOwner_ = d; } return d; } function getTemplateStagingDocument(template) { if (!template.stagingDocument_) { var owner = template.ownerDocument; if (!owner.stagingDocument_) { owner.stagingDocument_ = owner.implementation.createHTMLDocument(''); owner.stagingDocument_.isStagingDocument = true; // TODO(rafaelw): Remove when fix for // https://codereview.chromium.org/164803002/ // makes it to Chrome release. var base = owner.stagingDocument_.createElement('base'); base.href = document.baseURI; owner.stagingDocument_.head.appendChild(base); owner.stagingDocument_.stagingDocument_ = owner.stagingDocument_; } template.stagingDocument_ = owner.stagingDocument_; } return template.stagingDocument_; } // For non-template browsers, the parser will disallow <template> in certain // locations, so we allow "attribute templates" which combine the template // element with the top-level container node of the content, e.g. // // <tr template repeat="{{ foo }}"" class="bar"><td>Bar</td></tr> // // becomes // // <template repeat="{{ foo }}"> // + #document-fragment // + <tr class="bar"> // + <td>Bar</td> // function extractTemplateFromAttributeTemplate(el) { var template = el.ownerDocument.createElement('template'); el.parentNode.insertBefore(template, el); var attribs = el.attributes; var count = attribs.length; while (count-- > 0) { var attrib = attribs[count]; if (templateAttributeDirectives[attrib.name]) { if (attrib.name !== 'template') template.setAttribute(attrib.name, attrib.value); el.removeAttribute(attrib.name); } } return template; } function extractTemplateFromSVGTemplate(el) { var template = el.ownerDocument.createElement('template'); el.parentNode.insertBefore(template, el); var attribs = el.attributes; var count = attribs.length; while (count-- > 0) { var attrib = attribs[count]; template.setAttribute(attrib.name, attrib.value); el.removeAttribute(attrib.name); } el.parentNode.removeChild(el); return template; } function liftNonNativeTemplateChildrenIntoContent(template, el, useRoot) { var content = template.content; if (useRoot) { content.appendChild(el); return; } var child; while (child = el.firstChild) { content.appendChild(child); } } var templateObserver; if (typeof MutationObserver == 'function') { templateObserver = new MutationObserver(function(records) { for (var i = 0; i < records.length; i++) { records[i].target.refChanged_(); } }); } /** * Ensures proper API and content model for template elements. * @param {HTMLTemplateElement} opt_instanceRef The template element which * |el| template element will return as the value of its ref(), and whose * content will be used as source when createInstance() is invoked. */ HTMLTemplateElement.decorate = function(el, opt_instanceRef) { if (el.templateIsDecorated_) return false; var templateElement = el; templateElement.templateIsDecorated_ = true; var isNativeHTMLTemplate = isHTMLTemplate(templateElement) && hasTemplateElement; var bootstrapContents = isNativeHTMLTemplate; var liftContents = !isNativeHTMLTemplate; var liftRoot = false; if (!isNativeHTMLTemplate) { if (isAttributeTemplate(templateElement)) { assert(!opt_instanceRef); templateElement = extractTemplateFromAttributeTemplate(el); templateElement.templateIsDecorated_ = true; isNativeHTMLTemplate = hasTemplateElement; liftRoot = true; } else if (isSVGTemplate(templateElement)) { templateElement = extractTemplateFromSVGTemplate(el); templateElement.templateIsDecorated_ = true; isNativeHTMLTemplate = hasTemplateElement; } } if (!isNativeHTMLTemplate) { fixTemplateElementPrototype(templateElement); var doc = getOrCreateTemplateContentsOwner(templateElement); templateElement.content_ = doc.createDocumentFragment(); } if (opt_instanceRef) { // template is contained within an instance, its direct content must be // empty templateElement.instanceRef_ = opt_instanceRef; } else if (liftContents) { liftNonNativeTemplateChildrenIntoContent(templateElement, el, liftRoot); } else if (bootstrapContents) { bootstrapTemplatesRecursivelyFrom(templateElement.content); } return true; }; // TODO(rafaelw): This used to decorate recursively all templates from a given // node. This happens by default on 'DOMContentLoaded', but may be needed // in subtrees not descendent from document (e.g. ShadowRoot). // Review whether this is the right public API. HTMLTemplateElement.bootstrap = bootstrapTemplatesRecursivelyFrom; var htmlElement = global.HTMLUnknownElement || HTMLElement; var contentDescriptor = { get: function() { return this.content_; }, enumerable: true, configurable: true }; if (!hasTemplateElement) { // Gecko is more picky with the prototype than WebKit. Make sure to use the // same prototype as created in the constructor. HTMLTemplateElement.prototype = Object.create(htmlElement.prototype); Object.defineProperty(HTMLTemplateElement.prototype, 'content', contentDescriptor); } function fixTemplateElementPrototype(el) { if (hasProto) el.__proto__ = HTMLTemplateElement.prototype; else mixin(el, HTMLTemplateElement.prototype); } function ensureSetModelScheduled(template) { if (!template.setModelFn_) { template.setModelFn_ = function() { template.setModelFnScheduled_ = false; var map = getBindings(template, template.delegate_ && template.delegate_.prepareBinding); processBindings(template, map, template.model_); }; } if (!template.setModelFnScheduled_) { template.setModelFnScheduled_ = true; Observer.runEOM_(template.setModelFn_); } } mixin(HTMLTemplateElement.prototype, { bind: function(name, value, oneTime) { if (name != 'ref') return Element.prototype.bind.call(this, name, value, oneTime); var self = this; var ref = oneTime ? value : value.open(function(ref) { self.setAttribute('ref', ref); self.refChanged_(); }); this.setAttribute('ref', ref); this.refChanged_(); if (oneTime) return; if (!this.bindings_) { this.bindings_ = { ref: value }; } else { this.bindings_.ref = value; } return value; }, processBindingDirectives_: function(directives) { if (this.iterator_) this.iterator_.closeDeps(); if (!directives.if && !directives.bind && !directives.repeat) { if (this.iterator_) { this.iterator_.close(); this.iterator_ = undefined; } return; } if (!this.iterator_) { this.iterator_ = new TemplateIterator(this); } this.iterator_.updateDependencies(directives, this.model_); if (templateObserver) { templateObserver.observe(this, { attributes: true, attributeFilter: ['ref'] }); } return this.iterator_; }, createInstance: function(model, bindingDelegate, delegate_) { if (bindingDelegate) delegate_ = this.newDelegate_(bindingDelegate); else if (!delegate_) delegate_ = this.delegate_; if (!this.refContent_) this.refContent_ = this.ref_.content; var content = this.refContent_; if (content.firstChild === null) return emptyInstance; var map = getInstanceBindingMap(content, delegate_); var stagingDocument = getTemplateStagingDocument(this); var instance = stagingDocument.createDocumentFragment(); instance.templateCreator_ = this; instance.protoContent_ = content; instance.bindings_ = []; instance.terminator_ = null; var instanceRecord = instance.templateInstance_ = { firstNode: null, lastNode: null, model: model }; var i = 0; var collectTerminator = false; for (var child = content.firstChild; child; child = child.nextSibling) { // The terminator of the instance is the clone of the last child of the // content. If the last child is an active template, it may produce // instances as a result of production, so simply collecting the last // child of the instance after it has finished producing may be wrong. if (child.nextSibling === null) collectTerminator = true; var clone = cloneAndBindInstance(child, instance, stagingDocument, map.children[i++], model, delegate_, instance.bindings_); clone.templateInstance_ = instanceRecord; if (collectTerminator) instance.terminator_ = clone; } instanceRecord.firstNode = instance.firstChild; instanceRecord.lastNode = instance.lastChild; instance.templateCreator_ = undefined; instance.protoContent_ = undefined; return instance; }, get model() { return this.model_; }, set model(model) { this.model_ = model; ensureSetModelScheduled(this); }, get bindingDelegate() { return this.delegate_ && this.delegate_.raw; }, refChanged_: function() { if (!this.iterator_ || this.refContent_ === this.ref_.content) return; this.refContent_ = undefined; this.iterator_.valueChanged(); this.iterator_.updateIteratedValue(this.iterator_.getUpdatedValue()); }, clear: function() { this.model_ = undefined; this.delegate_ = undefined; if (this.bindings_ && this.bindings_.ref) this.bindings_.ref.close() this.refContent_ = undefined; if (!this.iterator_) return; this.iterator_.valueChanged(); this.iterator_.close() this.iterator_ = undefined; }, setDelegate_: function(delegate) { this.delegate_ = delegate; this.bindingMap_ = undefined; if (this.iterator_) { this.iterator_.instancePositionChangedFn_ = undefined; this.iterator_.instanceModelFn_ = undefined; } }, newDelegate_: function(bindingDelegate) { if (!bindingDelegate) return; function delegateFn(name) { var fn = bindingDelegate && bindingDelegate[name]; if (typeof fn != 'function') return; return function() { return fn.apply(bindingDelegate, arguments); }; } return { bindingMaps: {}, raw: bindingDelegate, prepareBinding: delegateFn('prepareBinding'), prepareInstanceModel: delegateFn('prepareInstanceModel'), prepareInstancePositionChanged: delegateFn('prepareInstancePositionChanged') }; }, set bindingDelegate(bindingDelegate) { if (this.delegate_) { throw Error('Template must be cleared before a new bindingDelegate ' + 'can be assigned'); } this.setDelegate_(this.newDelegate_(bindingDelegate)); }, get ref_() { var ref = searchRefId(this, this.getAttribute('ref')); if (!ref) ref = this.instanceRef_; if (!ref) return this; var nextRef = ref.ref_; return nextRef ? nextRef : ref; } }); // Returns // a) undefined if there are no mustaches. // b) [TEXT, (ONE_TIME?, PATH, DELEGATE_FN, TEXT)+] if there is at least one mustache. function parseMustaches(s, name, node, prepareBindingFn) { if (!s || !s.length) return; var tokens; var length = s.length; var startIndex = 0, lastIndex = 0, endIndex = 0; var onlyOneTime = true; while (lastIndex < length) { var startIndex = s.indexOf('{{', lastIndex); var oneTimeStart = s.indexOf('[[', lastIndex); var oneTime = false; var terminator = '}}'; if (oneTimeStart >= 0 && (startIndex < 0 || oneTimeStart < startIndex)) { startIndex = oneTimeStart; oneTime = true; terminator = ']]'; } endIndex = startIndex < 0 ? -1 : s.indexOf(terminator, startIndex + 2); if (endIndex < 0) { if (!tokens) return; tokens.push(s.slice(lastIndex)); // TEXT break; } tokens = tokens || []; tokens.push(s.slice(lastIndex, startIndex)); // TEXT var pathString = s.slice(startIndex + 2, endIndex).trim(); tokens.push(oneTime); // ONE_TIME? onlyOneTime = onlyOneTime && oneTime; var delegateFn = prepareBindingFn && prepareBindingFn(pathString, name, node); // Don't try to parse the expression if there's a prepareBinding function if (delegateFn == null) { tokens.push(Path.get(pathString)); // PATH } else { tokens.push(null); } tokens.push(delegateFn); // DELEGATE_FN lastIndex = endIndex + 2; } if (lastIndex === length) tokens.push(''); // TEXT tokens.hasOnePath = tokens.length === 5; tokens.isSimplePath = tokens.hasOnePath && tokens[0] == '' && tokens[4] == ''; tokens.onlyOneTime = onlyOneTime; tokens.combinator = function(values) { var newValue = tokens[0]; for (var i = 1; i < tokens.length; i += 4) { var value = tokens.hasOnePath ? values : values[(i - 1) / 4]; if (value !== undefined) newValue += value; newValue += tokens[i + 3]; } return newValue; } return tokens; }; function processOneTimeBinding(name, tokens, node, model) { if (tokens.hasOnePath) { var delegateFn = tokens[3]; var value = delegateFn ? delegateFn(model, node, true) : tokens[2].getValueFrom(model); return tokens.isSimplePath ? value : tokens.combinator(value); } var values = []; for (var i = 1; i < tokens.length; i += 4) { var delegateFn = tokens[i + 2]; values[(i - 1) / 4] = delegateFn ? delegateFn(model, node) : tokens[i + 1].getValueFrom(model); } return tokens.combinator(values); } function processSinglePathBinding(name, tokens, node, model) { var delegateFn = tokens[3]; var observer = delegateFn ? delegateFn(model, node, false) : new PathObserver(model, tokens[2]); return tokens.isSimplePath ? observer : new ObserverTransform(observer, tokens.combinator); } function processBinding(name, tokens, node, model) { if (tokens.onlyOneTime) return processOneTimeBinding(name, tokens, node, model); if (tokens.hasOnePath) return processSinglePathBinding(name, tokens, node, model); var observer = new CompoundObserver(); for (var i = 1; i < tokens.length; i += 4) { var oneTime = tokens[i]; var delegateFn = tokens[i + 2]; if (delegateFn) { var value = delegateFn(model, node, oneTime); if (oneTime) observer.addPath(value) else observer.addObserver(value); continue; } var path = tokens[i + 1]; if (oneTime) observer.addPath(path.getValueFrom(model)) else observer.addPath(model, path); } return new ObserverTransform(observer, tokens.combinator); } function processBindings(node, bindings, model, instanceBindings) { for (var i = 0; i < bindings.length; i += 2) { var name = bindings[i] var tokens = bindings[i + 1]; var value = processBinding(name, tokens, node, model); var binding = node.bind(name, value, tokens.onlyOneTime); if (binding && instanceBindings) instanceBindings.push(binding); } node.bindFinished(); if (!bindings.isTemplate) return; node.model_ = model; var iter = node.processBindingDirectives_(bindings); if (instanceBindings && iter) instanceBindings.push(iter); } function parseWithDefault(el, name, prepareBindingFn) { var v = el.getAttribute(name); return parseMustaches(v == '' ? '{{}}' : v, name, el, prepareBindingFn); } function parseAttributeBindings(element, prepareBindingFn) { assert(element); var bindings = []; var ifFound = false; var bindFound = false; for (var i = 0; i < element.attributes.length; i++) { var attr = element.attributes[i]; var name = attr.name; var value = attr.value; // Allow bindings expressed in attributes to be prefixed with underbars. // We do this to allow correct semantics for browsers that don't implement // <template> where certain attributes might trigger side-effects -- and // for IE which sanitizes certain attributes, disallowing mustache // replacements in their text. while (name[0] === '_') { name = name.substring(1); } if (isTemplate(element) && (name === IF || name === BIND || name === REPEAT)) { continue; } var tokens = parseMustaches(value, name, element, prepareBindingFn); if (!tokens) continue; bindings.push(name, tokens); } if (isTemplate(element)) { bindings.isTemplate = true; bindings.if = parseWithDefault(element, IF, prepareBindingFn); bindings.bind = parseWithDefault(element, BIND, prepareBindingFn); bindings.repeat = parseWithDefault(element, REPEAT, prepareBindingFn); if (bindings.if && !bindings.bind && !bindings.repeat) bindings.bind = parseMustaches('{{}}', BIND, element, prepareBindingFn); } return bindings; } function getBindings(node, prepareBindingFn) { if (node.nodeType === Node.ELEMENT_NODE) return parseAttributeBindings(node, prepareBindingFn); if (node.nodeType === Node.TEXT_NODE) { var tokens = parseMustaches(node.data, 'textContent', node, prepareBindingFn); if (tokens) return ['textContent', tokens]; } return []; } function cloneAndBindInstance(node, parent, stagingDocument, bindings, model, delegate, instanceBindings, instanceRecord) { var clone = parent.appendChild(stagingDocument.importNode(node, false)); var i = 0; for (var child = node.firstChild; child; child = child.nextSibling) { cloneAndBindInstance(child, clone, stagingDocument, bindings.children[i++], model, delegate, instanceBindings); } if (bindings.isTemplate) { HTMLTemplateElement.decorate(clone, node); if (delegate) clone.setDelegate_(delegate); } processBindings(clone, bindings, model, instanceBindings); return clone; } function createInstanceBindingMap(node, prepareBindingFn) { var map = getBindings(node, prepareBindingFn); map.children = {}; var index = 0; for (var child = node.firstChild; child; child = child.nextSibling) { map.children[index++] = createInstanceBindingMap(child, prepareBindingFn); } return map; } var contentUidCounter = 1; // TODO(rafaelw): Setup a MutationObserver on content which clears the id // so that bindingMaps regenerate when the template.content changes. function getContentUid(content) { var id = content.id_; if (!id) id = content.id_ = contentUidCounter++; return id; } // Each delegate is associated with a set of bindingMaps, one for each // content which may be used by a template. The intent is that each binding // delegate gets the opportunity to prepare the instance (via the prepare* // delegate calls) once across all uses. // TODO(rafaelw): Separate out the parse map from the binding map. In the // current implementation, if two delegates need a binding map for the same // content, the second will have to reparse. function getInstanceBindingMap(content, delegate_) { var contentId = getContentUid(content); if (delegate_) { var map = delegate_.bindingMaps[contentId]; if (!map) { map = delegate_.bindingMaps[contentId] = createInstanceBindingMap(content, delegate_.prepareBinding) || []; } return map; } var map = content.bindingMap_; if (!map) { map = content.bindingMap_ = createInstanceBindingMap(content, undefined) || []; } return map; } Object.defineProperty(Node.prototype, 'templateInstance', { get: function() { var instance = this.templateInstance_; return instance ? instance : (this.parentNode ? this.parentNode.templateInstance : undefined); } }); var emptyInstance = document.createDocumentFragment(); emptyInstance.bindings_ = []; emptyInstance.terminator_ = null; function TemplateIterator(templateElement) { this.closed = false; this.templateElement_ = templateElement; this.instances = []; this.deps = undefined; this.iteratedValue = []; this.presentValue = undefined; this.arrayObserver = undefined; } TemplateIterator.prototype = { closeDeps: function() { var deps = this.deps; if (deps) { if (deps.ifOneTime === false) deps.ifValue.close(); if (deps.oneTime === false) deps.value.close(); } }, updateDependencies: function(directives, model) { this.closeDeps(); var deps = this.deps = {}; var template = this.templateElement_; var ifValue = true; if (directives.if) { deps.hasIf = true; deps.ifOneTime = directives.if.onlyOneTime; deps.ifValue = processBinding(IF, directives.if, template, model); ifValue = deps.ifValue; // oneTime if & predicate is false. nothing else to do. if (deps.ifOneTime && !ifValue) { this.valueChanged(); return; } if (!deps.ifOneTime) ifValue = ifValue.open(this.updateIfValue, this); } if (directives.repeat) { deps.repeat = true; deps.oneTime = directives.repeat.onlyOneTime; deps.value = processBinding(REPEAT, directives.repeat, template, model); } else { deps.repeat = false; deps.oneTime = directives.bind.onlyOneTime; deps.value = processBinding(BIND, directives.bind, template, model); } var value = deps.value; if (!deps.oneTime) value = value.open(this.updateIteratedValue, this); if (!ifValue) { this.valueChanged(); return; } this.updateValue(value); }, /** * Gets the updated value of the bind/repeat. This can potentially call * user code (if a bindingDelegate is set up) so we try to avoid it if we * already have the value in hand (from Observer.open). */ getUpdatedValue: function() { var value = this.deps.value; if (!this.deps.oneTime) value = value.discardChanges(); return value; }, updateIfValue: function(ifValue) { if (!ifValue) { this.valueChanged(); return; } this.updateValue(this.getUpdatedValue()); }, updateIteratedValue: function(value) { if (this.deps.hasIf) { var ifValue = this.deps.ifValue; if (!this.deps.ifOneTime) ifValue = ifValue.discardChanges(); if (!ifValue) { this.valueChanged(); return; } } this.updateValue(value); }, updateValue: function(value) { if (!this.deps.repeat) value = [value]; var observe = this.deps.repeat && !this.deps.oneTime && Array.isArray(value); this.valueChanged(value, observe); }, valueChanged: function(value, observeValue) { if (!Array.isArray(value)) value = []; if (value === this.iteratedValue) return; this.unobserve(); this.presentValue = value; if (observeValue) { this.arrayObserver = new ArrayObserver(this.presentValue); this.arrayObserver.open(this.handleSplices, this); } this.handleSplices(ArrayObserver.calculateSplices(this.presentValue, this.iteratedValue)); }, getLastInstanceNode: function(index) { if (index == -1) return this.templateElement_; var instance = this.instances[index]; var terminator = instance.terminator_; if (!terminator) return this.getLastInstanceNode(index - 1); if (terminator.nodeType !== Node.ELEMENT_NODE || this.templateElement_ === terminator) { return terminator; } var subtemplateIterator = terminator.iterator_; if (!subtemplateIterator) return terminator; return subtemplateIterator.getLastTemplateNode(); }, getLastTemplateNode: function() { return this.getLastInstanceNode(this.instances.length - 1); }, insertInstanceAt: function(index, fragment) { var previousInstanceLast = this.getLastInstanceNode(index - 1); var parent = this.templateElement_.parentNode; this.instances.splice(index, 0, fragment); parent.insertBefore(fragment, previousInstanceLast.nextSibling); }, extractInstanceAt: function(index) { var previousInstanceLast = this.getLastInstanceNode(index - 1); var lastNode = this.getLastInstanceNode(index); var parent = this.templateElement_.parentNode; var instance = this.instances.splice(index, 1)[0]; while (lastNode !== previousInstanceLast) { var node = previousInstanceLast.nextSibling; if (node == lastNode) lastNode = previousInstanceLast; instance.appendChild(parent.removeChild(node)); } return instance; }, getDelegateFn: function(fn) { fn = fn && fn(this.templateElement_); return typeof fn === 'function' ? fn : null; }, handleSplices: function(splices) { if (this.closed || !splices.length) return; var template = this.templateElement_; if (!template.parentNode) { this.close(); return; } ArrayObserver.applySplices(this.iteratedValue, this.presentValue, splices); var delegate = template.delegate_; if (this.instanceModelFn_ === undefined) { this.instanceModelFn_ = this.getDelegateFn(delegate && delegate.prepareInstanceModel); } if (this.instancePositionChangedFn_ === undefined) { this.instancePositionChangedFn_ = this.getDelegateFn(delegate && delegate.prepareInstancePositionChanged); } // Instance Removals var instanceCache = new Map; var removeDelta = 0; for (var i = 0; i < splices.length; i++) { var splice = splices[i]; var removed = splice.removed; for (var j = 0; j < removed.length; j++) { var model = removed[j]; var instance = this.extractInstanceAt(splice.index + removeDelta); if (instance !== emptyInstance) { instanceCache.set(model, instance); } } removeDelta -= splice.addedCount; } // Instance Insertions for (var i = 0; i < splices.length; i++) { var splice = splices[i]; var addIndex = splice.index; for (; addIndex < splice.index + splice.addedCount; addIndex++) { var model = this.iteratedValue[addIndex]; var instance = instanceCache.get(model); if (instance) { instanceCache.delete(model); } else { if (this.instanceModelFn_) { model = this.instanceModelFn_(model); } if (model === undefined) { instance = emptyInstance; } else { instance = template.createInstance(model, undefined, delegate); } } this.insertInstanceAt(addIndex, instance); } } instanceCache.forEach(function(instance) { this.closeInstanceBindings(instance); }, this); if (this.instancePositionChangedFn_) this.reportInstancesMoved(splices); }, reportInstanceMoved: function(index) { var instance = this.instances[index]; if (instance === emptyInstance) return; this.instancePositionChangedFn_(instance.templateInstance_, index); }, reportInstancesMoved: function(splices) { var index = 0; var offset = 0; for (var i = 0; i < splices.length; i++) { var splice = splices[i]; if (offset != 0) { while (index < splice.index) { this.reportInstanceMoved(index); index++; } } else { index = splice.index; } while (index < splice.index + splice.addedCount) { this.reportInstanceMoved(index); index++; } offset += splice.addedCount - splice.removed.length; } if (offset == 0) return; var length = this.instances.length; while (index < length) { this.reportInstanceMoved(index); index++; } }, closeInstanceBindings: function(instance) { var bindings = instance.bindings_; for (var i = 0; i < bindings.length; i++) { bindings[i].close(); } }, unobserve: function() { if (!this.arrayObserver) return; this.arrayObserver.close(); this.arrayObserver = undefined; }, close: function() { if (this.closed) return; this.unobserve(); for (var i = 0; i < this.instances.length; i++) { this.closeInstanceBindings(this.instances[i]); } this.instances.length = 0; this.closeDeps(); this.templateElement_.iterator_ = undefined; this.closed = true; } }; // Polyfill-specific API. HTMLTemplateElement.forAllTemplatesFrom_ = forAllTemplatesFrom; })(this); (function(scope) { 'use strict'; // feature detect for URL constructor var hasWorkingUrl = false; if (!scope.forceJURL) { try { var u = new URL('b', 'http://a'); u.pathname = 'c%20d'; hasWorkingUrl = u.href === 'http://a/c%20d'; } catch(e) {} } if (hasWorkingUrl) return; var relative = Object.create(null); relative['ftp'] = 21; relative['file'] = 0; relative['gopher'] = 70; relative['http'] = 80; relative['https'] = 443; relative['ws'] = 80; relative['wss'] = 443; var relativePathDotMapping = Object.create(null); relativePathDotMapping['%2e'] = '.'; relativePathDotMapping['.%2e'] = '..'; relativePathDotMapping['%2e.'] = '..'; relativePathDotMapping['%2e%2e'] = '..'; function isRelativeScheme(scheme) { return relative[scheme] !== undefined; } function invalid() { clear.call(this); this._isInvalid = true; } function IDNAToASCII(h) { if ('' == h) { invalid.call(this) } // XXX return h.toLowerCase() } function percentEscape(c) { var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ? ` [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } function percentEscapeQuery(c) { // XXX This actually needs to encode c using encoding and then // convert the bytes one-by-one. var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?') [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } var EOF = undefined, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; function parse(input, stateOverride, base) { function err(message) { errors.push(message) } var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = []; loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) { var c = input[cursor]; switch (state) { case 'scheme start': if (c && ALPHA.test(c)) { buffer += c.toLowerCase(); // ASCII-safe state = 'scheme'; } else if (!stateOverride) { buffer = ''; state = 'no scheme'; continue; } else { err('Invalid scheme.'); break loop; } break; case 'scheme': if (c && ALPHANUMERIC.test(c)) { buffer += c.toLowerCase(); // ASCII-safe } else if (':' == c) { this._scheme = buffer; buffer = ''; if (stateOverride) { break loop; } if (isRelativeScheme(this._scheme)) { this._isRelative = true; } if ('file' == this._scheme) { state = 'relative'; } else if (this._isRelative && base && base._scheme == this._scheme) { state = 'relative or authority'; } else if (this._isRelative) { state = 'authority first slash'; } else { state = 'scheme data'; } } else if (!stateOverride) { buffer = ''; cursor = 0; state = 'no scheme'; continue; } else if (EOF == c) { break loop; } else { err('Code point not allowed in scheme: ' + c) break loop; } break; case 'scheme data': if ('?' == c) { query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } else { // XXX error handling if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._schemeData += percentEscape(c); } } break; case 'no scheme': if (!base || !(isRelativeScheme(base._scheme))) { err('Missing scheme.'); invalid.call(this); } else { state = 'relative'; continue; } break; case 'relative or authority': if ('/' == c && '/' == input[cursor+1]) { state = 'authority ignore slashes'; } else { err('Expected /, got: ' + c); state = 'relative'; continue } break; case 'relative': this._isRelative = true; if ('file' != this._scheme) this._scheme = base._scheme; if (EOF == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; break loop; } else if ('/' == c || '\\' == c) { if ('\\' == c) err('\\ is an invalid code point.'); state = 'relative slash'; } else if ('?' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = '?'; state = 'query'; } else if ('#' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._fragment = '#'; state = 'fragment'; } else { var nextC = input[cursor+1] var nextNextC = input[cursor+2] if ( 'file' != this._scheme || !ALPHA.test(c) || (nextC != ':' && nextC != '|') || (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._path.pop(); } state = 'relative path'; continue; } break; case 'relative slash': if ('/' == c || '\\' == c) { if ('\\' == c) { err('\\ is an invalid code point.'); } if ('file' == this._scheme) { state = 'file host'; } else { state = 'authority ignore slashes'; } } else { if ('file' != this._scheme) { this._host = base._host; this._port = base._port; } state = 'relative path'; continue; } break; case 'authority first slash': if ('/' == c) { state = 'authority second slash'; } else { err("Expected '/', got: " + c); state = 'authority ignore slashes'; continue; } break; case 'authority second slash': state = 'authority ignore slashes'; if ('/' != c) { err("Expected '/', got: " + c); continue; } break; case 'authority ignore slashes': if ('/' != c && '\\' != c) { state = 'authority'; continue; } else { err('Expected authority, got: ' + c); } break; case 'authority': if ('@' == c) { if (seenAt) { err('@ already seen.'); buffer += '%40'; } seenAt = true; for (var i = 0; i < buffer.length; i++) { var cp = buffer[i]; if ('\t' == cp || '\n' == cp || '\r' == cp) { err('Invalid whitespace in authority.'); continue; } // XXX check URL code points if (':' == cp && null === this._password) { this._password = ''; continue; } var tempC = percentEscape(cp); (null !== this._password) ? this._password += tempC : this._username += tempC; } buffer = ''; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { cursor -= buffer.length; buffer = ''; state = 'host'; continue; } else { buffer += c; } break; case 'file host': if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) { state = 'relative path'; } else if (buffer.length == 0) { state = 'relative path start'; } else { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; } continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid whitespace in file host.'); } else { buffer += c; } break; case 'host': case 'hostname': if (':' == c && !seenBracket) { // XXX host parsing this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'port'; if ('hostname' == stateOverride) { break loop; } } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; if (stateOverride) { break loop; } continue; } else if ('\t' != c && '\n' != c && '\r' != c) { if ('[' == c) { seenBracket = true; } else if (']' == c) { seenBracket = false; } buffer += c; } else { err('Invalid code point in host/hostname: ' + c); } break; case 'port': if (/[0-9]/.test(c)) { buffer += c; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) { if ('' != buffer) { var temp = parseInt(buffer, 10); if (temp != relative[this._scheme]) { this._port = temp + ''; } buffer = ''; } if (stateOverride) { break loop; } state = 'relative path start'; continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid code point in port: ' + c); } else { invalid.call(this); } break; case 'relative path start': if ('\\' == c) err("'\\' not allowed in path."); state = 'relative path'; if ('/' != c && '\\' != c) { continue; } break; case 'relative path': if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) { if ('\\' == c) { err('\\ not allowed in relative path.'); } var tmp; if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { buffer = tmp; } if ('..' == buffer) { this._path.pop(); if ('/' != c && '\\' != c) { this._path.push(''); } } else if ('.' == buffer && '/' != c && '\\' != c) { this._path.push(''); } else if ('.' != buffer) { if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') { buffer = buffer[0] + ':'; } this._path.push(buffer); } buffer = ''; if ('?' == c) { this._query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } } else if ('\t' != c && '\n' != c && '\r' != c) { buffer += percentEscape(c); } break; case 'query': if (!stateOverride && '#' == c) { this._fragment = '#'; state = 'fragment'; } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._query += percentEscapeQuery(c); } break; case 'fragment': if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._fragment += c; } break; } cursor++; } } function clear() { this._scheme = ''; this._schemeData = ''; this._username = ''; this._password = null; this._host = ''; this._port = ''; this._path = []; this._query = ''; this._fragment = ''; this._isInvalid = false; this._isRelative = false; } // Does not process domain names or IP addresses. // Does not handle encoding for the query parameter. function jURL(url, base /* , encoding */) { if (base !== undefined && !(base instanceof jURL)) base = new jURL(String(base)); this._url = url; clear.call(this); var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); // encoding = encoding || 'utf-8' parse.call(this, input, null, base); } jURL.prototype = { get href() { if (this._isInvalid) return this._url; var authority = ''; if ('' != this._username || null != this._password) { authority = this._username + (null != this._password ? ':' + this._password : '') + '@'; } return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment; }, set href(href) { clear.call(this); parse.call(this, href); }, get protocol() { return this._scheme + ':'; }, set protocol(protocol) { if (this._isInvalid) return; parse.call(this, protocol + ':', 'scheme start'); }, get host() { return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host; }, set host(host) { if (this._isInvalid || !this._isRelative) return; parse.call(this, host, 'host'); }, get hostname() { return this._host; }, set hostname(hostname) { if (this._isInvalid || !this._isRelative) return; parse.call(this, hostname, 'hostname'); }, get port() { return this._port; }, set port(port) { if (this._isInvalid || !this._isRelative) return; parse.call(this, port, 'port'); }, get pathname() { return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData; }, set pathname(pathname) { if (this._isInvalid || !this._isRelative) return; this._path = []; parse.call(this, pathname, 'relative path start'); }, get search() { return this._isInvalid || !this._query || '?' == this._query ? '' : this._query; }, set search(search) { if (this._isInvalid || !this._isRelative) return; this._query = '?'; if ('?' == search[0]) search = search.slice(1); parse.call(this, search, 'query'); }, get hash() { return this._isInvalid || !this._fragment || '#' == this._fragment ? '' : this._fragment; }, set hash(hash) { if (this._isInvalid) return; this._fragment = '#'; if ('#' == hash[0]) hash = hash.slice(1); parse.call(this, hash, 'fragment'); }, get origin() { var host; if (this._isInvalid || !this._scheme) { return ''; } // javascript: Gecko returns String(""), WebKit/Blink String("null") // Gecko throws error for "data://" // data: Gecko returns "", Blink returns "data://", WebKit returns "null" // Gecko returns String("") for file: mailto: // WebKit/Blink returns String("SCHEME://") for file: mailto: switch (this._scheme) { case 'data': case 'file': case 'javascript': case 'mailto': return 'null'; } host = this.host; if (!host) { return ''; } return this._scheme + '://' + host; } }; // Copy over the static methods var OriginalURL = scope.URL; if (OriginalURL) { jURL.createObjectURL = function(blob) { // IE extension allows a second optional options argument. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx return OriginalURL.createObjectURL.apply(OriginalURL, arguments); }; jURL.revokeObjectURL = function(url) { OriginalURL.revokeObjectURL(url); }; } scope.URL = jURL; })(this); (function(scope) { var iterations = 0; var callbacks = []; var twiddle = document.createTextNode(''); function endOfMicrotask(callback) { twiddle.textContent = iterations++; callbacks.push(callback); } function atEndOfMicrotask() { while (callbacks.length) { callbacks.shift()(); } } new (window.MutationObserver || JsMutationObserver)(atEndOfMicrotask) .observe(twiddle, {characterData: true}) ; // exports scope.endOfMicrotask = endOfMicrotask; // bc Platform.endOfMicrotask = endOfMicrotask; })(Polymer); (function(scope) { /** * @class Polymer */ // imports var endOfMicrotask = scope.endOfMicrotask; // logging var log = window.WebComponents ? WebComponents.flags.log : {}; // inject style sheet var style = document.createElement('style'); style.textContent = 'template {display: none !important;} /* injected by platform.js */'; var head = document.querySelector('head'); head.insertBefore(style, head.firstChild); /** * Force any pending data changes to be observed before * the next task. Data changes are processed asynchronously but are guaranteed * to be processed, for example, before painting. This method should rarely be * needed. It does nothing when Object.observe is available; * when Object.observe is not available, Polymer automatically flushes data * changes approximately every 1/10 second. * Therefore, `flush` should only be used when a data mutation should be * observed sooner than this. * * @method flush */ // flush (with logging) var flushing; function flush() { if (!flushing) { flushing = true; endOfMicrotask(function() { flushing = false; log.data && console.group('flush'); Platform.performMicrotaskCheckpoint(); log.data && console.groupEnd(); }); } }; // polling dirty checker // flush periodically if platform does not have object observe. if (!Observer.hasObjectObserve) { var FLUSH_POLL_INTERVAL = 125; window.addEventListener('WebComponentsReady', function() { flush(); // watch document visiblity to toggle dirty-checking var visibilityHandler = function() { // only flush if the page is visibile if (document.visibilityState === 'hidden') { if (scope.flushPoll) { clearInterval(scope.flushPoll); } } else { scope.flushPoll = setInterval(flush, FLUSH_POLL_INTERVAL); } }; if (typeof document.visibilityState === 'string') { document.addEventListener('visibilitychange', visibilityHandler); } visibilityHandler(); }); } else { // make flush a no-op when we have Object.observe flush = function() {}; } if (window.CustomElements && !CustomElements.useNative) { var originalImportNode = Document.prototype.importNode; Document.prototype.importNode = function(node, deep) { var imported = originalImportNode.call(this, node, deep); CustomElements.upgradeAll(imported); return imported; }; } // exports scope.flush = flush; // bc Platform.flush = flush; })(window.Polymer); (function(scope) { var urlResolver = { resolveDom: function(root, url) { url = url || baseUrl(root); this.resolveAttributes(root, url); this.resolveStyles(root, url); // handle template.content var templates = root.querySelectorAll('template'); if (templates) { for (var i = 0, l = templates.length, t; (i < l) && (t = templates[i]); i++) { if (t.content) { this.resolveDom(t.content, url); } } } }, resolveTemplate: function(template) { this.resolveDom(template.content, baseUrl(template)); }, resolveStyles: function(root, url) { var styles = root.querySelectorAll('style'); if (styles) { for (var i = 0, l = styles.length, s; (i < l) && (s = styles[i]); i++) { this.resolveStyle(s, url); } } }, resolveStyle: function(style, url) { url = url || baseUrl(style); style.textContent = this.resolveCssText(style.textContent, url); }, resolveCssText: function(cssText, baseUrl, keepAbsolute) { cssText = replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, CSS_URL_REGEXP); return replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, CSS_IMPORT_REGEXP); }, resolveAttributes: function(root, url) { if (root.hasAttributes && root.hasAttributes()) { this.resolveElementAttributes(root, url); } // search for attributes that host urls var nodes = root && root.querySelectorAll(URL_ATTRS_SELECTOR); if (nodes) { for (var i = 0, l = nodes.length, n; (i < l) && (n = nodes[i]); i++) { this.resolveElementAttributes(n, url); } } }, resolveElementAttributes: function(node, url) { url = url || baseUrl(node); URL_ATTRS.forEach(function(v) { var attr = node.attributes[v]; var value = attr && attr.value; var replacement; if (value && value.search(URL_TEMPLATE_SEARCH) < 0) { if (v === 'style') { replacement = replaceUrlsInCssText(value, url, false, CSS_URL_REGEXP); } else { replacement = resolveRelativeUrl(url, value); } attr.value = replacement; } }); } }; var CSS_URL_REGEXP = /(url\()([^)]*)(\))/g; var CSS_IMPORT_REGEXP = /(@import[\s]+(?!url\())([^;]*)(;)/g; var URL_ATTRS = ['href', 'src', 'action', 'style', 'url']; var URL_ATTRS_SELECTOR = '[' + URL_ATTRS.join('],[') + ']'; var URL_TEMPLATE_SEARCH = '{{.*}}'; var URL_HASH = '#'; function baseUrl(node) { var u = new URL(node.ownerDocument.baseURI); u.search = ''; u.hash = ''; return u; } function replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, regexp) { return cssText.replace(regexp, function(m, pre, url, post) { var urlPath = url.replace(/["']/g, ''); urlPath = resolveRelativeUrl(baseUrl, urlPath, keepAbsolute); return pre + '\'' + urlPath + '\'' + post; }); } function resolveRelativeUrl(baseUrl, url, keepAbsolute) { // do not resolve '/' absolute urls if (url && url[0] === '/') { return url; } // do not resolve '#' links, they are used for routing if (url && url[0] === '#') { return url; } var u = new URL(url, baseUrl); return keepAbsolute ? u.href : makeDocumentRelPath(u.href); } function makeDocumentRelPath(url) { var root = baseUrl(document.documentElement); var u = new URL(url, root); if (u.host === root.host && u.port === root.port && u.protocol === root.protocol) { return makeRelPath(root, u); } else { return url; } } // make a relative path from source to target function makeRelPath(sourceUrl, targetUrl) { var source = sourceUrl.pathname; var target = targetUrl.pathname; var s = source.split('/'); var t = target.split('/'); while (s.length && s[0] === t[0]){ s.shift(); t.shift(); } for (var i = 0, l = s.length - 1; i < l; i++) { t.unshift('..'); } // empty '#' is discarded but we need to preserve it. var hash = (targetUrl.href.slice(-1) === URL_HASH) ? URL_HASH : targetUrl.hash; return t.join('/') + targetUrl.search + hash; } // exports scope.urlResolver = urlResolver; })(Polymer); (function(scope) { var endOfMicrotask = Polymer.endOfMicrotask; // Generic url loader function Loader(regex) { this.cache = Object.create(null); this.map = Object.create(null); this.requests = 0; this.regex = regex; } Loader.prototype = { // TODO(dfreedm): there may be a better factoring here // extract absolute urls from the text (full of relative urls) extractUrls: function(text, base) { var matches = []; var matched, u; while ((matched = this.regex.exec(text))) { u = new URL(matched[1], base); matches.push({matched: matched[0], url: u.href}); } return matches; }, // take a text blob, a root url, and a callback and load all the urls found within the text // returns a map of absolute url to text process: function(text, root, callback) { var matches = this.extractUrls(text, root); // every call to process returns all the text this loader has ever received var done = callback.bind(null, this.map); this.fetch(matches, done); }, // build a mapping of url -> text from matches fetch: function(matches, callback) { var inflight = matches.length; // return early if there is no fetching to be done if (!inflight) { return callback(); } // wait for all subrequests to return var done = function() { if (--inflight === 0) { callback(); } }; // start fetching all subrequests var m, req, url; for (var i = 0; i < inflight; i++) { m = matches[i]; url = m.url; req = this.cache[url]; // if this url has already been requested, skip requesting it again if (!req) { req = this.xhr(url); req.match = m; this.cache[url] = req; } // wait for the request to process its subrequests req.wait(done); } }, handleXhr: function(request) { var match = request.match; var url = match.url; // handle errors with an empty string var response = request.response || request.responseText || ''; this.map[url] = response; this.fetch(this.extractUrls(response, url), request.resolve); }, xhr: function(url) { this.requests++; var request = new XMLHttpRequest(); request.open('GET', url, true); request.send(); request.onerror = request.onload = this.handleXhr.bind(this, request); // queue of tasks to run after XHR returns request.pending = []; request.resolve = function() { var pending = request.pending; for(var i = 0; i < pending.length; i++) { pending[i](); } request.pending = null; }; // if we have already resolved, pending is null, async call the callback request.wait = function(fn) { if (request.pending) { request.pending.push(fn); } else { endOfMicrotask(fn); } }; return request; } }; scope.Loader = Loader; })(Polymer); (function(scope) { var urlResolver = scope.urlResolver; var Loader = scope.Loader; function StyleResolver() { this.loader = new Loader(this.regex); } StyleResolver.prototype = { regex: /@import\s+(?:url)?["'\(]*([^'"\)]*)['"\)]*;/g, // Recursively replace @imports with the text at that url resolve: function(text, url, callback) { var done = function(map) { callback(this.flatten(text, url, map)); }.bind(this); this.loader.process(text, url, done); }, // resolve the textContent of a style node resolveNode: function(style, url, callback) { var text = style.textContent; var done = function(text) { style.textContent = text; callback(style); }; this.resolve(text, url, done); }, // flatten all the @imports to text flatten: function(text, base, map) { var matches = this.loader.extractUrls(text, base); var match, url, intermediate; for (var i = 0; i < matches.length; i++) { match = matches[i]; url = match.url; // resolve any css text to be relative to the importer, keep absolute url intermediate = urlResolver.resolveCssText(map[url], url, true); // flatten intermediate @imports intermediate = this.flatten(intermediate, base, map); text = text.replace(match.matched, intermediate); } return text; }, loadStyles: function(styles, base, callback) { var loaded=0, l = styles.length; // called in the context of the style function loadedStyle(style) { loaded++; if (loaded === l && callback) { callback(); } } for (var i=0, s; (i<l) && (s=styles[i]); i++) { this.resolveNode(s, base, loadedStyle); } } }; var styleResolver = new StyleResolver(); // exports scope.styleResolver = styleResolver; })(Polymer); (function(scope) { // copy own properties from 'api' to 'prototype, with name hinting for 'super' function extend(prototype, api) { if (prototype && api) { // use only own properties of 'api' Object.getOwnPropertyNames(api).forEach(function(n) { // acquire property descriptor var pd = Object.getOwnPropertyDescriptor(api, n); if (pd) { // clone property via descriptor Object.defineProperty(prototype, n, pd); // cache name-of-method for 'super' engine if (typeof pd.value == 'function') { // hint the 'super' engine pd.value.nom = n; } } }); } return prototype; } // mixin // copy all properties from inProps (et al) to inObj function mixin(inObj/*, inProps, inMoreProps, ...*/) { var obj = inObj || {}; for (var i = 1; i < arguments.length; i++) { var p = arguments[i]; try { for (var n in p) { copyProperty(n, p, obj); } } catch(x) { } } return obj; } // copy property inName from inSource object to inTarget object function copyProperty(inName, inSource, inTarget) { var pd = getPropertyDescriptor(inSource, inName); Object.defineProperty(inTarget, inName, pd); } // get property descriptor for inName on inObject, even if // inName exists on some link in inObject's prototype chain function getPropertyDescriptor(inObject, inName) { if (inObject) { var pd = Object.getOwnPropertyDescriptor(inObject, inName); return pd || getPropertyDescriptor(Object.getPrototypeOf(inObject), inName); } } // exports scope.extend = extend; scope.mixin = mixin; // for bc Platform.mixin = mixin; })(Polymer); (function(scope) { // usage // invoke cb.call(this) in 100ms, unless the job is re-registered, // which resets the timer // // this.myJob = this.job(this.myJob, cb, 100) // // returns a job handle which can be used to re-register a job var Job = function(inContext) { this.context = inContext; this.boundComplete = this.complete.bind(this) }; Job.prototype = { go: function(callback, wait) { this.callback = callback; var h; if (!wait) { h = requestAnimationFrame(this.boundComplete); this.handle = function() { cancelAnimationFrame(h); } } else { h = setTimeout(this.boundComplete, wait); this.handle = function() { clearTimeout(h); } } }, stop: function() { if (this.handle) { this.handle(); this.handle = null; } }, complete: function() { if (this.handle) { this.stop(); this.callback.call(this.context); } } }; function job(job, callback, wait) { if (job) { job.stop(); } else { job = new Job(this); } job.go(callback, wait); return job; } // exports scope.job = job; })(Polymer); (function(scope) { // dom polyfill, additions, and utility methods var registry = {}; HTMLElement.register = function(tag, prototype) { registry[tag] = prototype; }; // get prototype mapped to node <tag> HTMLElement.getPrototypeForTag = function(tag) { var prototype = !tag ? HTMLElement.prototype : registry[tag]; // TODO(sjmiles): creating <tag> is likely to have wasteful side-effects return prototype || Object.getPrototypeOf(document.createElement(tag)); }; // we have to flag propagation stoppage for the event dispatcher var originalStopPropagation = Event.prototype.stopPropagation; Event.prototype.stopPropagation = function() { this.cancelBubble = true; originalStopPropagation.apply(this, arguments); }; // polyfill DOMTokenList // * add/remove: allow these methods to take multiple classNames // * toggle: add a 2nd argument which forces the given state rather // than toggling. var add = DOMTokenList.prototype.add; var remove = DOMTokenList.prototype.remove; DOMTokenList.prototype.add = function() { for (var i = 0; i < arguments.length; i++) { add.call(this, arguments[i]); } }; DOMTokenList.prototype.remove = function() { for (var i = 0; i < arguments.length; i++) { remove.call(this, arguments[i]); } }; DOMTokenList.prototype.toggle = function(name, bool) { if (arguments.length == 1) { bool = !this.contains(name); } bool ? this.add(name) : this.remove(name); }; DOMTokenList.prototype.switch = function(oldName, newName) { oldName && this.remove(oldName); newName && this.add(newName); }; // add array() to NodeList, NamedNodeMap, HTMLCollection var ArraySlice = function() { return Array.prototype.slice.call(this); }; var namedNodeMap = (window.NamedNodeMap || window.MozNamedAttrMap || {}); NodeList.prototype.array = ArraySlice; namedNodeMap.prototype.array = ArraySlice; HTMLCollection.prototype.array = ArraySlice; // utility function createDOM(inTagOrNode, inHTML, inAttrs) { var dom = typeof inTagOrNode == 'string' ? document.createElement(inTagOrNode) : inTagOrNode.cloneNode(true); dom.innerHTML = inHTML; if (inAttrs) { for (var n in inAttrs) { dom.setAttribute(n, inAttrs[n]); } } return dom; } // exports scope.createDOM = createDOM; })(Polymer); (function(scope) { // super // `arrayOfArgs` is an optional array of args like one might pass // to `Function.apply` // TODO(sjmiles): // $super must be installed on an instance or prototype chain // as `super`, and invoked via `this`, e.g. // `this.super();` // will not work if function objects are not unique, for example, // when using mixins. // The memoization strategy assumes each function exists on only one // prototype chain i.e. we use the function object for memoizing) // perhaps we can bookkeep on the prototype itself instead function $super(arrayOfArgs) { // since we are thunking a method call, performance is important here: // memoize all lookups, once memoized the fast path calls no other // functions // // find the caller (cannot be `strict` because of 'caller') var caller = $super.caller; // memoized 'name of method' var nom = caller.nom; // memoized next implementation prototype var _super = caller._super; if (!_super) { if (!nom) { nom = caller.nom = nameInThis.call(this, caller); } if (!nom) { console.warn('called super() on a method not installed declaratively (has no .nom property)'); } // super prototype is either cached or we have to find it // by searching __proto__ (at the 'top') // invariant: because we cache _super on fn below, we never reach // here from inside a series of calls to super(), so it's ok to // start searching from the prototype of 'this' (at the 'top') // we must never memoize a null super for this reason _super = memoizeSuper(caller, nom, getPrototypeOf(this)); } // our super function var fn = _super[nom]; if (fn) { // memoize information so 'fn' can call 'super' if (!fn._super) { // must not memoize null, or we lose our invariant above memoizeSuper(fn, nom, _super); } // invoke the inherited method // if 'fn' is not function valued, this will throw return fn.apply(this, arrayOfArgs || []); } } function nameInThis(value) { var p = this.__proto__; while (p && p !== HTMLElement.prototype) { // TODO(sjmiles): getOwnPropertyNames is absurdly expensive var n$ = Object.getOwnPropertyNames(p); for (var i=0, l=n$.length, n; i<l && (n=n$[i]); i++) { var d = Object.getOwnPropertyDescriptor(p, n); if (typeof d.value === 'function' && d.value === value) { return n; } } p = p.__proto__; } } function memoizeSuper(method, name, proto) { // find and cache next prototype containing `name` // we need the prototype so we can do another lookup // from here var s = nextSuper(proto, name, method); if (s[name]) { // `s` is a prototype, the actual method is `s[name]` // tag super method with it's name for quicker lookups s[name].nom = name; } return method._super = s; } function nextSuper(proto, name, caller) { // look for an inherited prototype that implements name while (proto) { if ((proto[name] !== caller) && proto[name]) { return proto; } proto = getPrototypeOf(proto); } // must not return null, or we lose our invariant above // in this case, a super() call was invoked where no superclass // method exists // TODO(sjmiles): thow an exception? return Object; } // NOTE: In some platforms (IE10) the prototype chain is faked via // __proto__. Therefore, always get prototype via __proto__ instead of // the more standard Object.getPrototypeOf. function getPrototypeOf(prototype) { return prototype.__proto__; } // utility function to precompute name tags for functions // in a (unchained) prototype function hintSuper(prototype) { // tag functions with their prototype name to optimize // super call invocations for (var n in prototype) { var pd = Object.getOwnPropertyDescriptor(prototype, n); if (pd && typeof pd.value === 'function') { pd.value.nom = n; } } } // exports scope.super = $super; })(Polymer); (function(scope) { function noopHandler(value) { return value; } // helper for deserializing properties of various types to strings var typeHandlers = { string: noopHandler, 'undefined': noopHandler, date: function(value) { return new Date(Date.parse(value) || Date.now()); }, boolean: function(value) { if (value === '') { return true; } return value === 'false' ? false : !!value; }, number: function(value) { var n = parseFloat(value); // hex values like "0xFFFF" parseFloat as 0 if (n === 0) { n = parseInt(value); } return isNaN(n) ? value : n; // this code disabled because encoded values (like "0xFFFF") // do not round trip to their original format //return (String(floatVal) === value) ? floatVal : value; }, object: function(value, currentValue) { if (currentValue === null) { return value; } try { // If the string is an object, we can parse is with the JSON library. // include convenience replace for single-quotes. If the author omits // quotes altogether, parse will fail. return JSON.parse(value.replace(/'/g, '"')); } catch(e) { // The object isn't valid JSON, return the raw value return value; } }, // avoid deserialization of functions 'function': function(value, currentValue) { return currentValue; } }; function deserializeValue(value, currentValue) { // attempt to infer type from default value var inferredType = typeof currentValue; // invent 'date' type value for Date if (currentValue instanceof Date) { inferredType = 'date'; } // delegate deserialization via type string return typeHandlers[inferredType](value, currentValue); } // exports scope.deserializeValue = deserializeValue; })(Polymer); (function(scope) { // imports var extend = scope.extend; // module var api = {}; api.declaration = {}; api.instance = {}; api.publish = function(apis, prototype) { for (var n in apis) { extend(prototype, apis[n]); } }; // exports scope.api = api; })(Polymer); (function(scope) { /** * @class polymer-base */ var utils = { /** * Invokes a function asynchronously. The context of the callback * function is bound to 'this' automatically. Returns a handle which may * be passed to <a href="#cancelAsync">cancelAsync</a> to cancel the * asynchronous call. * * @method async * @param {Function|String} method * @param {any|Array} args * @param {number} timeout */ async: function(method, args, timeout) { // when polyfilling Object.observe, ensure changes // propagate before executing the async method Polymer.flush(); // second argument to `apply` must be an array args = (args && args.length) ? args : [args]; // function to invoke var fn = function() { (this[method] || method).apply(this, args); }.bind(this); // execute `fn` sooner or later var handle = timeout ? setTimeout(fn, timeout) : requestAnimationFrame(fn); // NOTE: switch on inverting handle to determine which time is used. return timeout ? handle : ~handle; }, /** * Cancels a pending callback that was scheduled via * <a href="#async">async</a>. * * @method cancelAsync * @param {handle} handle Handle of the `async` to cancel. */ cancelAsync: function(handle) { if (handle < 0) { cancelAnimationFrame(~handle); } else { clearTimeout(handle); } }, /** * Fire an event. * * @method fire * @returns {Object} event * @param {string} type An event name. * @param {any} detail * @param {Node} onNode Target node. * @param {Boolean} bubbles Set false to prevent bubbling, defaults to true * @param {Boolean} cancelable Set false to prevent cancellation, defaults to true */ fire: function(type, detail, onNode, bubbles, cancelable) { var node = onNode || this; var detail = detail === null || detail === undefined ? {} : detail; var event = new CustomEvent(type, { bubbles: bubbles !== undefined ? bubbles : true, cancelable: cancelable !== undefined ? cancelable : true, detail: detail }); node.dispatchEvent(event); return event; }, /** * Fire an event asynchronously. * * @method asyncFire * @param {string} type An event name. * @param detail * @param {Node} toNode Target node. */ asyncFire: function(/*inType, inDetail*/) { this.async("fire", arguments); }, /** * Remove class from old, add class to anew, if they exist. * * @param classFollows * @param anew A node. * @param old A node * @param className */ classFollows: function(anew, old, className) { if (old) { old.classList.remove(className); } if (anew) { anew.classList.add(className); } }, /** * Inject HTML which contains markup bound to this element into * a target element (replacing target element content). * * @param String html to inject * @param Element target element */ injectBoundHTML: function(html, element) { var template = document.createElement('template'); template.innerHTML = html; var fragment = this.instanceTemplate(template); if (element) { element.textContent = ''; element.appendChild(fragment); } return fragment; } }; // no-operation function for handy stubs var nop = function() {}; // null-object for handy stubs var nob = {}; // deprecated utils.asyncMethod = utils.async; // exports scope.api.instance.utils = utils; scope.nop = nop; scope.nob = nob; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var EVENT_PREFIX = 'on-'; // instance events api var events = { // read-only EVENT_PREFIX: EVENT_PREFIX, // event listeners on host addHostListeners: function() { var events = this.eventDelegates; log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events); // NOTE: host events look like bindings but really are not; // (1) we don't want the attribute to be set and (2) we want to support // multiple event listeners ('host' and 'instance') and Node.bind // by default supports 1 thing being bound. for (var type in events) { var methodName = events[type]; PolymerGestures.addEventListener(this, type, this.element.getEventHandler(this, this, methodName)); } }, // call 'method' or function method on 'obj' with 'args', if the method exists dispatchMethod: function(obj, method, args) { if (obj) { log.events && console.group('[%s] dispatch [%s]', obj.localName, method); var fn = typeof method === 'function' ? method : obj[method]; if (fn) { fn[args ? 'apply' : 'call'](obj, args); } log.events && console.groupEnd(); // NOTE: dirty check right after calling method to ensure // changes apply quickly; in a very complicated app using high // frequency events, this can be a perf concern; in this case, // imperative handlers can be used to avoid flushing. Polymer.flush(); } } }; // exports scope.api.instance.events = events; /** * @class Polymer */ /** * Add a gesture aware event handler to the given `node`. Can be used * in place of `element.addEventListener` and ensures gestures will function * as expected on mobile platforms. Please note that Polymer's declarative * event handlers include this functionality by default. * * @method addEventListener * @param {Node} node node on which to listen * @param {String} eventType name of the event * @param {Function} handlerFn event handler function * @param {Boolean} capture set to true to invoke event capturing * @type Function */ // alias PolymerGestures event listener logic scope.addEventListener = function(node, eventType, handlerFn, capture) { PolymerGestures.addEventListener(wrap(node), eventType, handlerFn, capture); }; /** * Remove a gesture aware event handler on the given `node`. To remove an * event listener, the exact same arguments are required that were passed * to `Polymer.addEventListener`. * * @method removeEventListener * @param {Node} node node on which to listen * @param {String} eventType name of the event * @param {Function} handlerFn event handler function * @param {Boolean} capture set to true to invoke event capturing * @type Function */ scope.removeEventListener = function(node, eventType, handlerFn, capture) { PolymerGestures.removeEventListener(wrap(node), eventType, handlerFn, capture); }; })(Polymer); (function(scope) { // instance api for attributes var attributes = { // copy attributes defined in the element declaration to the instance // e.g. <polymer-element name="x-foo" tabIndex="0"> tabIndex is copied // to the element instance here. copyInstanceAttributes: function () { var a$ = this._instanceAttributes; for (var k in a$) { if (!this.hasAttribute(k)) { this.setAttribute(k, a$[k]); } } }, // for each attribute on this, deserialize value to property as needed takeAttributes: function() { // if we have no publish lookup table, we have no attributes to take // TODO(sjmiles): ad hoc if (this._publishLC) { for (var i=0, a$=this.attributes, l=a$.length, a; (a=a$[i]) && i<l; i++) { this.attributeToProperty(a.name, a.value); } } }, // if attribute 'name' is mapped to a property, deserialize // 'value' into that property attributeToProperty: function(name, value) { // try to match this attribute to a property (attributes are // all lower-case, so this is case-insensitive search) var name = this.propertyForAttribute(name); if (name) { // filter out 'mustached' values, these are to be // replaced with bound-data and are not yet values // themselves if (value && value.search(scope.bindPattern) >= 0) { return; } // get original value var currentValue = this[name]; // deserialize Boolean or Number values from attribute var value = this.deserializeValue(value, currentValue); // only act if the value has changed if (value !== currentValue) { // install new value (has side-effects) this[name] = value; } } }, // return the published property matching name, or undefined propertyForAttribute: function(name) { var match = this._publishLC && this._publishLC[name]; return match; }, // convert representation of `stringValue` based on type of `currentValue` deserializeValue: function(stringValue, currentValue) { return scope.deserializeValue(stringValue, currentValue); }, // convert to a string value based on the type of `inferredType` serializeValue: function(value, inferredType) { if (inferredType === 'boolean') { return value ? '' : undefined; } else if (inferredType !== 'object' && inferredType !== 'function' && value !== undefined) { return value; } }, // serializes `name` property value and updates the corresponding attribute // note that reflection is opt-in. reflectPropertyToAttribute: function(name) { var inferredType = typeof this[name]; // try to intelligently serialize property value var serializedValue = this.serializeValue(this[name], inferredType); // boolean properties must reflect as boolean attributes if (serializedValue !== undefined) { this.setAttribute(name, serializedValue); // TODO(sorvell): we should remove attr for all properties // that have undefined serialization; however, we will need to // refine the attr reflection system to achieve this; pica, for example, // relies on having inferredType object properties not removed as // attrs. } else if (inferredType === 'boolean') { this.removeAttribute(name); } } }; // exports scope.api.instance.attributes = attributes; })(Polymer); (function(scope) { /** * @class polymer-base */ // imports var log = window.WebComponents ? WebComponents.flags.log : {}; // magic words var OBSERVE_SUFFIX = 'Changed'; // element api var empty = []; var updateRecord = { object: undefined, type: 'update', name: undefined, oldValue: undefined }; var numberIsNaN = Number.isNaN || function(value) { return typeof value === 'number' && isNaN(value); }; function areSameValue(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; if (numberIsNaN(left) && numberIsNaN(right)) return true; return left !== left && right !== right; } // capture A's value if B's value is null or undefined, // otherwise use B's value function resolveBindingValue(oldValue, value) { if (value === undefined && oldValue === null) { return value; } return (value === null || value === undefined) ? oldValue : value; } var properties = { // creates a CompoundObserver to observe property changes // NOTE, this is only done there are any properties in the `observe` object createPropertyObserver: function() { var n$ = this._observeNames; if (n$ && n$.length) { var o = this._propertyObserver = new CompoundObserver(true); this.registerObserver(o); // TODO(sorvell): may not be kosher to access the value here (this[n]); // previously we looked at the descriptor on the prototype // this doesn't work for inheritance and not for accessors without // a value property for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) { o.addPath(this, n); this.observeArrayValue(n, this[n], null); } } }, // start observing property changes openPropertyObserver: function() { if (this._propertyObserver) { this._propertyObserver.open(this.notifyPropertyChanges, this); } }, // handler for property changes; routes changes to observing methods // note: array valued properties are observed for array splices notifyPropertyChanges: function(newValues, oldValues, paths) { var name, method, called = {}; for (var i in oldValues) { // note: paths is of form [object, path, object, path] name = paths[2 * i + 1]; method = this.observe[name]; if (method) { var ov = oldValues[i], nv = newValues[i]; // observes the value if it is an array this.observeArrayValue(name, nv, ov); if (!called[method]) { // only invoke change method if one of ov or nv is not (undefined | null) if ((ov !== undefined && ov !== null) || (nv !== undefined && nv !== null)) { called[method] = true; // TODO(sorvell): call method with the set of values it's expecting; // e.g. 'foo bar': 'invalidate' expects the new and old values for // foo and bar. Currently we give only one of these and then // deliver all the arguments. this.invokeMethod(method, [ov, nv, arguments]); } } } } }, // call method iff it exists. invokeMethod: function(method, args) { var fn = this[method] || method; if (typeof fn === 'function') { fn.apply(this, args); } }, /** * Force any pending property changes to synchronously deliver to * handlers specified in the `observe` object. * Note, normally changes are processed at microtask time. * * @method deliverChanges */ deliverChanges: function() { if (this._propertyObserver) { this._propertyObserver.deliver(); } }, observeArrayValue: function(name, value, old) { // we only care if there are registered side-effects var callbackName = this.observe[name]; if (callbackName) { // if we are observing the previous value, stop if (Array.isArray(old)) { log.observe && console.log('[%s] observeArrayValue: unregister observer [%s]', this.localName, name); this.closeNamedObserver(name + '__array'); } // if the new value is an array, being observing it if (Array.isArray(value)) { log.observe && console.log('[%s] observeArrayValue: register observer [%s]', this.localName, name, value); var observer = new ArrayObserver(value); observer.open(function(splices) { this.invokeMethod(callbackName, [splices]); }, this); this.registerNamedObserver(name + '__array', observer); } } }, emitPropertyChangeRecord: function(name, value, oldValue) { var object = this; if (areSameValue(value, oldValue)) { return; } // invoke property change side effects this._propertyChanged(name, value, oldValue); // emit change record if (!Observer.hasObjectObserve) { return; } var notifier = this._objectNotifier; if (!notifier) { notifier = this._objectNotifier = Object.getNotifier(this); } updateRecord.object = this; updateRecord.name = name; updateRecord.oldValue = oldValue; notifier.notify(updateRecord); }, _propertyChanged: function(name, value, oldValue) { if (this.reflect[name]) { this.reflectPropertyToAttribute(name); } }, // creates a property binding (called via bind) to a published property. bindProperty: function(property, observable, oneTime) { if (oneTime) { this[property] = observable; return; } var computed = this.element.prototype.computed; // Binding an "out-only" value to a computed property. Note that // since this observer isn't opened, it doesn't need to be closed on // cleanup. if (computed && computed[property]) { var privateComputedBoundValue = property + 'ComputedBoundObservable_'; this[privateComputedBoundValue] = observable; return; } return this.bindToAccessor(property, observable, resolveBindingValue); }, // NOTE property `name` must be published. This makes it an accessor. bindToAccessor: function(name, observable, resolveFn) { var privateName = name + '_'; var privateObservable = name + 'Observable_'; // Present for properties which are computed and published and have a // bound value. var privateComputedBoundValue = name + 'ComputedBoundObservable_'; this[privateObservable] = observable; var oldValue = this[privateName]; // observable callback var self = this; function updateValue(value, oldValue) { self[privateName] = value; var setObserveable = self[privateComputedBoundValue]; if (setObserveable && typeof setObserveable.setValue == 'function') { setObserveable.setValue(value); } self.emitPropertyChangeRecord(name, value, oldValue); } // resolve initial value var value = observable.open(updateValue); if (resolveFn && !areSameValue(oldValue, value)) { var resolvedValue = resolveFn(oldValue, value); if (!areSameValue(value, resolvedValue)) { value = resolvedValue; if (observable.setValue) { observable.setValue(value); } } } updateValue(value, oldValue); // register and return observable var observer = { close: function() { observable.close(); self[privateObservable] = undefined; self[privateComputedBoundValue] = undefined; } }; this.registerObserver(observer); return observer; }, createComputedProperties: function() { if (!this._computedNames) { return; } for (var i = 0; i < this._computedNames.length; i++) { var name = this._computedNames[i]; var expressionText = this.computed[name]; try { var expression = PolymerExpressions.getExpression(expressionText); var observable = expression.getBinding(this, this.element.syntax); this.bindToAccessor(name, observable); } catch (ex) { console.error('Failed to create computed property', ex); } } }, // property bookkeeping registerObserver: function(observer) { if (!this._observers) { this._observers = [observer]; return; } this._observers.push(observer); }, closeObservers: function() { if (!this._observers) { return; } // observer array items are arrays of observers. var observers = this._observers; for (var i = 0; i < observers.length; i++) { var observer = observers[i]; if (observer && typeof observer.close == 'function') { observer.close(); } } this._observers = []; }, // bookkeeping observers for memory management registerNamedObserver: function(name, observer) { var o$ = this._namedObservers || (this._namedObservers = {}); o$[name] = observer; }, closeNamedObserver: function(name) { var o$ = this._namedObservers; if (o$ && o$[name]) { o$[name].close(); o$[name] = null; return true; } }, closeNamedObservers: function() { if (this._namedObservers) { for (var i in this._namedObservers) { this.closeNamedObserver(i); } this._namedObservers = {}; } } }; // logging var LOG_OBSERVE = '[%s] watching [%s]'; var LOG_OBSERVED = '[%s#%s] watch: [%s] now [%s] was [%s]'; var LOG_CHANGED = '[%s#%s] propertyChanged: [%s] now [%s] was [%s]'; // exports scope.api.instance.properties = properties; })(Polymer); (function(scope) { /** * @class polymer-base */ // imports var log = window.WebComponents ? WebComponents.flags.log : {}; // element api supporting mdv var mdv = { /** * Creates dom cloned from the given template, instantiating bindings * with this element as the template model and `PolymerExpressions` as the * binding delegate. * * @method instanceTemplate * @param {Template} template source template from which to create dom. */ instanceTemplate: function(template) { // ensure template is decorated (lets' things like <tr template ...> work) HTMLTemplateElement.decorate(template); // ensure a default bindingDelegate var syntax = this.syntax || (!template.bindingDelegate && this.element.syntax); var dom = template.createInstance(this, syntax); var observers = dom.bindings_; for (var i = 0; i < observers.length; i++) { this.registerObserver(observers[i]); } return dom; }, // Called by TemplateBinding/NodeBind to setup a binding to the given // property. It's overridden here to support property bindings // in addition to attribute bindings that are supported by default. bind: function(name, observable, oneTime) { var property = this.propertyForAttribute(name); if (!property) { // TODO(sjmiles): this mixin method must use the special form // of `super` installed by `mixinMethod` in declaration/prototype.js return this.mixinSuper(arguments); } else { // use n-way Polymer binding var observer = this.bindProperty(property, observable, oneTime); // NOTE: reflecting binding information is typically required only for // tooling. It has a performance cost so it's opt-in in Node.bind. if (Platform.enableBindingsReflection && observer) { observer.path = observable.path_; this._recordBinding(property, observer); } if (this.reflect[property]) { this.reflectPropertyToAttribute(property); } return observer; } }, _recordBinding: function(name, observer) { this.bindings_ = this.bindings_ || {}; this.bindings_[name] = observer; }, // Called by TemplateBinding when all bindings on an element have been // executed. This signals that all element inputs have been gathered // and it's safe to ready the element, create shadow-root and start // data-observation. bindFinished: function() { this.makeElementReady(); }, // called at detached time to signal that an element's bindings should be // cleaned up. This is done asynchronously so that users have the chance // to call `cancelUnbindAll` to prevent unbinding. asyncUnbindAll: function() { if (!this._unbound) { log.unbind && console.log('[%s] asyncUnbindAll', this.localName); this._unbindAllJob = this.job(this._unbindAllJob, this.unbindAll, 0); } }, /** * This method should rarely be used and only if * <a href="#cancelUnbindAll">`cancelUnbindAll`</a> has been called to * prevent element unbinding. In this case, the element's bindings will * not be automatically cleaned up and it cannot be garbage collected * by the system. If memory pressure is a concern or a * large amount of elements need to be managed in this way, `unbindAll` * can be called to deactivate the element's bindings and allow its * memory to be reclaimed. * * @method unbindAll */ unbindAll: function() { if (!this._unbound) { this.closeObservers(); this.closeNamedObservers(); this._unbound = true; } }, /** * Call in `detached` to prevent the element from unbinding when it is * detached from the dom. The element is unbound as a cleanup step that * allows its memory to be reclaimed. * If `cancelUnbindAll` is used, consider calling * <a href="#unbindAll">`unbindAll`</a> when the element is no longer * needed. This will allow its memory to be reclaimed. * * @method cancelUnbindAll */ cancelUnbindAll: function() { if (this._unbound) { log.unbind && console.warn('[%s] already unbound, cannot cancel unbindAll', this.localName); return; } log.unbind && console.log('[%s] cancelUnbindAll', this.localName); if (this._unbindAllJob) { this._unbindAllJob = this._unbindAllJob.stop(); } } }; function unbindNodeTree(node) { forNodeTree(node, _nodeUnbindAll); } function _nodeUnbindAll(node) { node.unbindAll(); } function forNodeTree(node, callback) { if (node) { callback(node); for (var child = node.firstChild; child; child = child.nextSibling) { forNodeTree(child, callback); } } } var mustachePattern = /\{\{([^{}]*)}}/; // exports scope.bindPattern = mustachePattern; scope.api.instance.mdv = mdv; })(Polymer); (function(scope) { /** * Common prototype for all Polymer Elements. * * @class polymer-base * @homepage polymer.github.io */ var base = { /** * Tags this object as the canonical Base prototype. * * @property PolymerBase * @type boolean * @default true */ PolymerBase: true, /** * Debounce signals. * * Call `job` to defer a named signal, and all subsequent matching signals, * until a wait time has elapsed with no new signal. * * debouncedClickAction: function(e) { * // processClick only when it's been 100ms since the last click * this.job('click', function() { * this.processClick; * }, 100); * } * * @method job * @param String {String} job A string identifier for the job to debounce. * @param Function {Function} callback A function that is called (with `this` context) when the wait time elapses. * @param Number {Number} wait Time in milliseconds (ms) after the last signal that must elapse before invoking `callback` * @type Handle */ job: function(job, callback, wait) { if (typeof job === 'string') { var n = '___' + job; this[n] = Polymer.job.call(this, this[n], callback, wait); } else { // TODO(sjmiles): suggest we deprecate this call signature return Polymer.job.call(this, job, callback, wait); } }, /** * Invoke a superclass method. * * Use `super()` to invoke the most recently overridden call to the * currently executing function. * * To pass arguments through, use the literal `arguments` as the parameter * to `super()`. * * nextPageAction: function(e) { * // invoke the superclass version of `nextPageAction` * this.super(arguments); * } * * To pass custom arguments, arrange them in an array. * * appendSerialNo: function(value, serial) { * // prefix the superclass serial number with our lot # before * // invoking the superlcass * return this.super([value, this.lotNo + serial]) * } * * @method super * @type Any * @param {args) An array of arguments to use when calling the superclass method, or null. */ super: Polymer.super, /** * Lifecycle method called when the element is instantiated. * * Override `created` to perform custom create-time tasks. No need to call * super-class `created` unless you are extending another Polymer element. * Created is called before the element creates `shadowRoot` or prepares * data-observation. * * @method created * @type void */ created: function() { }, /** * Lifecycle method called when the element has populated it's `shadowRoot`, * prepared data-observation, and made itself ready for API interaction. * * @method ready * @type void */ ready: function() { }, /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom create-time tasks, implement `created` * instead, which is called immediately after `createdCallback`. * * @method createdCallback */ createdCallback: function() { if (this.templateInstance && this.templateInstance.model) { console.warn('Attributes on ' + this.localName + ' were data bound ' + 'prior to Polymer upgrading the element. This may result in ' + 'incorrect binding types.'); } this.created(); this.prepareElement(); if (!this.ownerDocument.isStagingDocument) { this.makeElementReady(); } }, // system entry point, do not override prepareElement: function() { if (this._elementPrepared) { console.warn('Element already prepared', this.localName); return; } this._elementPrepared = true; // storage for shadowRoots info this.shadowRoots = {}; // install property observers this.createPropertyObserver(); this.openPropertyObserver(); // install boilerplate attributes this.copyInstanceAttributes(); // process input attributes this.takeAttributes(); // add event listeners this.addHostListeners(); }, // system entry point, do not override makeElementReady: function() { if (this._readied) { return; } this._readied = true; this.createComputedProperties(); this.parseDeclarations(this.__proto__); // NOTE: Support use of the `unresolved` attribute to help polyfill // custom elements' `:unresolved` feature. this.removeAttribute('unresolved'); // user entry point this.ready(); }, /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom tasks in your element, implement `attributeChanged` * instead, which is called immediately after `attributeChangedCallback`. * * @method attributeChangedCallback */ attributeChangedCallback: function(name, oldValue) { // TODO(sjmiles): adhoc filter if (name !== 'class' && name !== 'style') { this.attributeToProperty(name, this.getAttribute(name)); } if (this.attributeChanged) { this.attributeChanged.apply(this, arguments); } }, /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom create-time tasks, implement `attached` * instead, which is called immediately after `attachedCallback`. * * @method attachedCallback */ attachedCallback: function() { // when the element is attached, prevent it from unbinding. this.cancelUnbindAll(); // invoke user action if (this.attached) { this.attached(); } if (!this.hasBeenAttached) { this.hasBeenAttached = true; if (this.domReady) { this.async('domReady'); } } }, /** * Implement to access custom elements in dom descendants, ancestors, * or siblings. Because custom elements upgrade in document order, * elements accessed in `ready` or `attached` may not be upgraded. When * `domReady` is called, all registered custom elements are guaranteed * to have been upgraded. * * @method domReady */ /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom create-time tasks, implement `detached` * instead, which is called immediately after `detachedCallback`. * * @method detachedCallback */ detachedCallback: function() { if (!this.preventDispose) { this.asyncUnbindAll(); } // invoke user action if (this.detached) { this.detached(); } // TODO(sorvell): bc if (this.leftView) { this.leftView(); } }, /** * Walks the prototype-chain of this element and allows specific * classes a chance to process static declarations. * * In particular, each polymer-element has it's own `template`. * `parseDeclarations` is used to accumulate all element `template`s * from an inheritance chain. * * `parseDeclaration` static methods implemented in the chain are called * recursively, oldest first, with the `<polymer-element>` associated * with the current prototype passed as an argument. * * An element may override this method to customize shadow-root generation. * * @method parseDeclarations */ parseDeclarations: function(p) { if (p && p.element) { this.parseDeclarations(p.__proto__); p.parseDeclaration.call(this, p.element); } }, /** * Perform init-time actions based on static information in the * `<polymer-element>` instance argument. * * For example, the standard implementation locates the template associated * with the given `<polymer-element>` and stamps it into a shadow-root to * implement shadow inheritance. * * An element may override this method for custom behavior. * * @method parseDeclaration */ parseDeclaration: function(elementElement) { var template = this.fetchTemplate(elementElement); if (template) { var root = this.shadowFromTemplate(template); this.shadowRoots[elementElement.name] = root; } }, /** * Given a `<polymer-element>`, find an associated template (if any) to be * used for shadow-root generation. * * An element may override this method for custom behavior. * * @method fetchTemplate */ fetchTemplate: function(elementElement) { return elementElement.querySelector('template'); }, /** * Create a shadow-root in this host and stamp `template` as it's * content. * * An element may override this method for custom behavior. * * @method shadowFromTemplate */ shadowFromTemplate: function(template) { if (template) { // make a shadow root var root = this.createShadowRoot(); // stamp template // which includes parsing and applying MDV bindings before being // inserted (to avoid {{}} in attribute values) // e.g. to prevent <img src="images/{{icon}}"> from generating a 404. var dom = this.instanceTemplate(template); // append to shadow dom root.appendChild(dom); // perform post-construction initialization tasks on shadow root this.shadowRootReady(root, template); // return the created shadow root return root; } }, // utility function that stamps a <template> into light-dom lightFromTemplate: function(template, refNode) { if (template) { // TODO(sorvell): mark this element as an eventController so that // event listeners on bound nodes inside it will be called on it. // Note, the expectation here is that events on all descendants // should be handled by this element. this.eventController = this; // stamp template // which includes parsing and applying MDV bindings before being // inserted (to avoid {{}} in attribute values) // e.g. to prevent <img src="images/{{icon}}"> from generating a 404. var dom = this.instanceTemplate(template); // append to shadow dom if (refNode) { this.insertBefore(dom, refNode); } else { this.appendChild(dom); } // perform post-construction initialization tasks on ahem, light root this.shadowRootReady(this); // return the created shadow root return dom; } }, shadowRootReady: function(root) { // locate nodes with id and store references to them in this.$ hash this.marshalNodeReferences(root); }, // locate nodes with id and store references to them in this.$ hash marshalNodeReferences: function(root) { // establish $ instance variable var $ = this.$ = this.$ || {}; // populate $ from nodes with ID from the LOCAL tree if (root) { var n$ = root.querySelectorAll("[id]"); for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) { $[n.id] = n; }; } }, /** * Register a one-time callback when a child-list or sub-tree mutation * occurs on node. * * For persistent callbacks, call onMutation from your listener. * * @method onMutation * @param Node {Node} node Node to watch for mutations. * @param Function {Function} listener Function to call on mutation. The function is invoked as `listener.call(this, observer, mutations);` where `observer` is the MutationObserver that triggered the notification, and `mutations` is the native mutation list. */ onMutation: function(node, listener) { var observer = new MutationObserver(function(mutations) { listener.call(this, observer, mutations); observer.disconnect(); }.bind(this)); observer.observe(node, {childList: true, subtree: true}); } }; /** * @class Polymer */ /** * Returns true if the object includes <a href="#polymer-base">polymer-base</a> in it's prototype chain. * * @method isBase * @param Object {Object} object Object to test. * @type Boolean */ function isBase(object) { return object.hasOwnProperty('PolymerBase') } // name a base constructor for dev tools /** * The Polymer base-class constructor. * * @property Base * @type Function */ function PolymerBase() {}; PolymerBase.prototype = base; base.constructor = PolymerBase; // exports scope.Base = PolymerBase; scope.isBase = isBase; scope.api.instance.base = base; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var hasShadowDOMPolyfill = window.ShadowDOMPolyfill; // magic words var STYLE_SCOPE_ATTRIBUTE = 'element'; var STYLE_CONTROLLER_SCOPE = 'controller'; var styles = { STYLE_SCOPE_ATTRIBUTE: STYLE_SCOPE_ATTRIBUTE, /** * Installs external stylesheets and <style> elements with the attribute * polymer-scope='controller' into the scope of element. This is intended * to be a called during custom element construction. */ installControllerStyles: function() { // apply controller styles, but only if they are not yet applied var scope = this.findStyleScope(); if (scope && !this.scopeHasNamedStyle(scope, this.localName)) { // allow inherited controller styles var proto = getPrototypeOf(this), cssText = ''; while (proto && proto.element) { cssText += proto.element.cssTextForScope(STYLE_CONTROLLER_SCOPE); proto = getPrototypeOf(proto); } if (cssText) { this.installScopeCssText(cssText, scope); } } }, installScopeStyle: function(style, name, scope) { var scope = scope || this.findStyleScope(), name = name || ''; if (scope && !this.scopeHasNamedStyle(scope, this.localName + name)) { var cssText = ''; if (style instanceof Array) { for (var i=0, l=style.length, s; (i<l) && (s=style[i]); i++) { cssText += s.textContent + '\n\n'; } } else { cssText = style.textContent; } this.installScopeCssText(cssText, scope, name); } }, installScopeCssText: function(cssText, scope, name) { scope = scope || this.findStyleScope(); name = name || ''; if (!scope) { return; } if (hasShadowDOMPolyfill) { cssText = shimCssText(cssText, scope.host); } var style = this.element.cssTextToScopeStyle(cssText, STYLE_CONTROLLER_SCOPE); Polymer.applyStyleToScope(style, scope); // cache that this style has been applied this.styleCacheForScope(scope)[this.localName + name] = true; }, findStyleScope: function(node) { // find the shadow root that contains this element var n = node || this; while (n.parentNode) { n = n.parentNode; } return n; }, scopeHasNamedStyle: function(scope, name) { var cache = this.styleCacheForScope(scope); return cache[name]; }, styleCacheForScope: function(scope) { if (hasShadowDOMPolyfill) { var scopeName = scope.host ? scope.host.localName : scope.localName; return polyfillScopeStyleCache[scopeName] || (polyfillScopeStyleCache[scopeName] = {}); } else { return scope._scopeStyles = (scope._scopeStyles || {}); } } }; var polyfillScopeStyleCache = {}; // NOTE: use raw prototype traversal so that we ensure correct traversal // on platforms where the protoype chain is simulated via __proto__ (IE10) function getPrototypeOf(prototype) { return prototype.__proto__; } function shimCssText(cssText, host) { var name = '', is = false; if (host) { name = host.localName; is = host.hasAttribute('is'); } var selector = WebComponents.ShadowCSS.makeScopeSelector(name, is); return WebComponents.ShadowCSS.shimCssText(cssText, selector); } // exports scope.api.instance.styles = styles; })(Polymer); (function(scope) { // imports var extend = scope.extend; var api = scope.api; // imperative implementation: Polymer() // specify an 'own' prototype for tag `name` function element(name, prototype) { if (typeof name !== 'string') { var script = prototype || document._currentScript; prototype = name; name = script && script.parentNode && script.parentNode.getAttribute ? script.parentNode.getAttribute('name') : ''; if (!name) { throw 'Element name could not be inferred.'; } } if (getRegisteredPrototype(name)) { throw 'Already registered (Polymer) prototype for element ' + name; } // cache the prototype registerPrototype(name, prototype); // notify the registrar waiting for 'name', if any notifyPrototype(name); } // async prototype source function waitingForPrototype(name, client) { waitPrototype[name] = client; } var waitPrototype = {}; function notifyPrototype(name) { if (waitPrototype[name]) { waitPrototype[name].registerWhenReady(); delete waitPrototype[name]; } } // utility and bookkeeping // maps tag names to prototypes, as registered with // Polymer. Prototypes associated with a tag name // using document.registerElement are available from // HTMLElement.getPrototypeForTag(). // If an element was fully registered by Polymer, then // Polymer.getRegisteredPrototype(name) === // HTMLElement.getPrototypeForTag(name) var prototypesByName = {}; function registerPrototype(name, prototype) { return prototypesByName[name] = prototype || {}; } function getRegisteredPrototype(name) { return prototypesByName[name]; } function instanceOfType(element, type) { if (typeof type !== 'string') { return false; } var proto = HTMLElement.getPrototypeForTag(type); var ctor = proto && proto.constructor; if (!ctor) { return false; } if (CustomElements.instanceof) { return CustomElements.instanceof(element, ctor); } return element instanceof ctor; } // exports scope.getRegisteredPrototype = getRegisteredPrototype; scope.waitingForPrototype = waitingForPrototype; scope.instanceOfType = instanceOfType; // namespace shenanigans so we can expose our scope on the registration // function // make window.Polymer reference `element()` window.Polymer = element; // TODO(sjmiles): find a way to do this that is less terrible // copy window.Polymer properties onto `element()` extend(Polymer, scope); // Under the HTMLImports polyfill, scripts in the main document // do not block on imports; we want to allow calls to Polymer in the main // document. WebComponents collects those calls until we can process them, which // we do here. if (WebComponents.consumeDeclarations) { WebComponents.consumeDeclarations(function(declarations) { if (declarations) { for (var i=0, l=declarations.length, d; (i<l) && (d=declarations[i]); i++) { element.apply(null, d); } } }); } })(Polymer); (function(scope) { /** * @class polymer-base */ /** * Resolve a url path to be relative to a `base` url. If unspecified, `base` * defaults to the element's ownerDocument url. Can be used to resolve * paths from element's in templates loaded in HTMLImports to be relative * to the document containing the element. Polymer automatically does this for * url attributes in element templates; however, if a url, for * example, contains a binding, then `resolvePath` can be used to ensure it is * relative to the element document. For example, in an element's template, * * <a href="{{resolvePath(path)}}">Resolved</a> * * @method resolvePath * @param {String} url Url path to resolve. * @param {String} base Optional base url against which to resolve, defaults * to the element's ownerDocument url. * returns {String} resolved url. */ var path = { resolveElementPaths: function(node) { Polymer.urlResolver.resolveDom(node); }, addResolvePathApi: function() { // let assetpath attribute modify the resolve path var assetPath = this.getAttribute('assetpath') || ''; var root = new URL(assetPath, this.ownerDocument.baseURI); this.prototype.resolvePath = function(urlPath, base) { var u = new URL(urlPath, base || root); return u.href; }; } }; // exports scope.api.declaration.path = path; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var api = scope.api.instance.styles; var STYLE_SCOPE_ATTRIBUTE = api.STYLE_SCOPE_ATTRIBUTE; var hasShadowDOMPolyfill = window.ShadowDOMPolyfill; // magic words var STYLE_SELECTOR = 'style'; var STYLE_LOADABLE_MATCH = '@import'; var SHEET_SELECTOR = 'link[rel=stylesheet]'; var STYLE_GLOBAL_SCOPE = 'global'; var SCOPE_ATTR = 'polymer-scope'; var styles = { // returns true if resources are loading loadStyles: function(callback) { var template = this.fetchTemplate(); var content = template && this.templateContent(); if (content) { this.convertSheetsToStyles(content); var styles = this.findLoadableStyles(content); if (styles.length) { var templateUrl = template.ownerDocument.baseURI; return Polymer.styleResolver.loadStyles(styles, templateUrl, callback); } } if (callback) { callback(); } }, convertSheetsToStyles: function(root) { var s$ = root.querySelectorAll(SHEET_SELECTOR); for (var i=0, l=s$.length, s, c; (i<l) && (s=s$[i]); i++) { c = createStyleElement(importRuleForSheet(s, this.ownerDocument.baseURI), this.ownerDocument); this.copySheetAttributes(c, s); s.parentNode.replaceChild(c, s); } }, copySheetAttributes: function(style, link) { for (var i=0, a$=link.attributes, l=a$.length, a; (a=a$[i]) && i<l; i++) { if (a.name !== 'rel' && a.name !== 'href') { style.setAttribute(a.name, a.value); } } }, findLoadableStyles: function(root) { var loadables = []; if (root) { var s$ = root.querySelectorAll(STYLE_SELECTOR); for (var i=0, l=s$.length, s; (i<l) && (s=s$[i]); i++) { if (s.textContent.match(STYLE_LOADABLE_MATCH)) { loadables.push(s); } } } return loadables; }, /** * Install external stylesheets loaded in <polymer-element> elements into the * element's template. * @param elementElement The <element> element to style. */ installSheets: function() { this.cacheSheets(); this.cacheStyles(); this.installLocalSheets(); this.installGlobalStyles(); }, /** * Remove all sheets from element and store for later use. */ cacheSheets: function() { this.sheets = this.findNodes(SHEET_SELECTOR); this.sheets.forEach(function(s) { if (s.parentNode) { s.parentNode.removeChild(s); } }); }, cacheStyles: function() { this.styles = this.findNodes(STYLE_SELECTOR + '[' + SCOPE_ATTR + ']'); this.styles.forEach(function(s) { if (s.parentNode) { s.parentNode.removeChild(s); } }); }, /** * Takes external stylesheets loaded in an <element> element and moves * their content into a <style> element inside the <element>'s template. * The sheet is then removed from the <element>. This is done only so * that if the element is loaded in the main document, the sheet does * not become active. * Note, ignores sheets with the attribute 'polymer-scope'. * @param elementElement The <element> element to style. */ installLocalSheets: function () { var sheets = this.sheets.filter(function(s) { return !s.hasAttribute(SCOPE_ATTR); }); var content = this.templateContent(); if (content) { var cssText = ''; sheets.forEach(function(sheet) { cssText += cssTextFromSheet(sheet) + '\n'; }); if (cssText) { var style = createStyleElement(cssText, this.ownerDocument); content.insertBefore(style, content.firstChild); } } }, findNodes: function(selector, matcher) { var nodes = this.querySelectorAll(selector).array(); var content = this.templateContent(); if (content) { var templateNodes = content.querySelectorAll(selector).array(); nodes = nodes.concat(templateNodes); } return matcher ? nodes.filter(matcher) : nodes; }, /** * Promotes external stylesheets and <style> elements with the attribute * polymer-scope='global' into global scope. * This is particularly useful for defining @keyframe rules which * currently do not function in scoped or shadow style elements. * (See wkb.ug/72462) * @param elementElement The <element> element to style. */ // TODO(sorvell): remove when wkb.ug/72462 is addressed. installGlobalStyles: function() { var style = this.styleForScope(STYLE_GLOBAL_SCOPE); applyStyleToScope(style, document.head); }, cssTextForScope: function(scopeDescriptor) { var cssText = ''; // handle stylesheets var selector = '[' + SCOPE_ATTR + '=' + scopeDescriptor + ']'; var matcher = function(s) { return matchesSelector(s, selector); }; var sheets = this.sheets.filter(matcher); sheets.forEach(function(sheet) { cssText += cssTextFromSheet(sheet) + '\n\n'; }); // handle cached style elements var styles = this.styles.filter(matcher); styles.forEach(function(style) { cssText += style.textContent + '\n\n'; }); return cssText; }, styleForScope: function(scopeDescriptor) { var cssText = this.cssTextForScope(scopeDescriptor); return this.cssTextToScopeStyle(cssText, scopeDescriptor); }, cssTextToScopeStyle: function(cssText, scopeDescriptor) { if (cssText) { var style = createStyleElement(cssText); style.setAttribute(STYLE_SCOPE_ATTRIBUTE, this.getAttribute('name') + '-' + scopeDescriptor); return style; } } }; function importRuleForSheet(sheet, baseUrl) { var href = new URL(sheet.getAttribute('href'), baseUrl).href; return '@import \'' + href + '\';'; } function applyStyleToScope(style, scope) { if (style) { if (scope === document) { scope = document.head; } if (hasShadowDOMPolyfill) { scope = document.head; } // TODO(sorvell): necessary for IE // see https://connect.microsoft.com/IE/feedback/details/790212/ // cloning-a-style-element-and-adding-to-document-produces // -unexpected-result#details // var clone = style.cloneNode(true); var clone = createStyleElement(style.textContent); var attr = style.getAttribute(STYLE_SCOPE_ATTRIBUTE); if (attr) { clone.setAttribute(STYLE_SCOPE_ATTRIBUTE, attr); } // TODO(sorvell): probably too brittle; try to figure out // where to put the element. var refNode = scope.firstElementChild; if (scope === document.head) { var selector = 'style[' + STYLE_SCOPE_ATTRIBUTE + ']'; var s$ = document.head.querySelectorAll(selector); if (s$.length) { refNode = s$[s$.length-1].nextElementSibling; } } scope.insertBefore(clone, refNode); } } function createStyleElement(cssText, scope) { scope = scope || document; scope = scope.createElement ? scope : scope.ownerDocument; var style = scope.createElement('style'); style.textContent = cssText; return style; } function cssTextFromSheet(sheet) { return (sheet && sheet.__resource) || ''; } function matchesSelector(node, inSelector) { if (matches) { return matches.call(node, inSelector); } } var p = HTMLElement.prototype; var matches = p.matches || p.matchesSelector || p.webkitMatchesSelector || p.mozMatchesSelector; // exports scope.api.declaration.styles = styles; scope.applyStyleToScope = applyStyleToScope; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var api = scope.api.instance.events; var EVENT_PREFIX = api.EVENT_PREFIX; var mixedCaseEventTypes = {}; [ 'webkitAnimationStart', 'webkitAnimationEnd', 'webkitTransitionEnd', 'DOMFocusOut', 'DOMFocusIn', 'DOMMouseScroll' ].forEach(function(e) { mixedCaseEventTypes[e.toLowerCase()] = e; }); // polymer-element declarative api: events feature var events = { parseHostEvents: function() { // our delegates map var delegates = this.prototype.eventDelegates; // extract data from attributes into delegates this.addAttributeDelegates(delegates); }, addAttributeDelegates: function(delegates) { // for each attribute for (var i=0, a; a=this.attributes[i]; i++) { // does it have magic marker identifying it as an event delegate? if (this.hasEventPrefix(a.name)) { // if so, add the info to delegates delegates[this.removeEventPrefix(a.name)] = a.value.replace('{{', '') .replace('}}', '').trim(); } } }, // starts with 'on-' hasEventPrefix: function (n) { return n && (n[0] === 'o') && (n[1] === 'n') && (n[2] === '-'); }, removeEventPrefix: function(n) { return n.slice(prefixLength); }, findController: function(node) { while (node.parentNode) { if (node.eventController) { return node.eventController; } node = node.parentNode; } return node.host; }, getEventHandler: function(controller, target, method) { var events = this; return function(e) { if (!controller || !controller.PolymerBase) { controller = events.findController(target); } var args = [e, e.detail, e.currentTarget]; controller.dispatchMethod(controller, method, args); }; }, prepareEventBinding: function(pathString, name, node) { if (!this.hasEventPrefix(name)) return; var eventType = this.removeEventPrefix(name); eventType = mixedCaseEventTypes[eventType] || eventType; var events = this; return function(model, node, oneTime) { var handler = events.getEventHandler(undefined, node, pathString); PolymerGestures.addEventListener(node, eventType, handler); if (oneTime) return; // TODO(rafaelw): This is really pointless work. Aside from the cost // of these allocations, NodeBind is going to setAttribute back to its // current value. Fixing this would mean changing the TemplateBinding // binding delegate API. function bindingValue() { return '{{ ' + pathString + ' }}'; } return { open: bindingValue, discardChanges: bindingValue, close: function() { PolymerGestures.removeEventListener(node, eventType, handler); } }; }; } }; var prefixLength = EVENT_PREFIX.length; // exports scope.api.declaration.events = events; })(Polymer); (function(scope) { // element api var observationBlacklist = ['attribute']; var properties = { inferObservers: function(prototype) { // called before prototype.observe is chained to inherited object var observe = prototype.observe, property; for (var n in prototype) { if (n.slice(-7) === 'Changed') { property = n.slice(0, -7); if (this.canObserveProperty(property)) { if (!observe) { observe = (prototype.observe = {}); } observe[property] = observe[property] || n; } } } }, canObserveProperty: function(property) { return (observationBlacklist.indexOf(property) < 0); }, explodeObservers: function(prototype) { // called before prototype.observe is chained to inherited object var o = prototype.observe; if (o) { var exploded = {}; for (var n in o) { var names = n.split(' '); for (var i=0, ni; ni=names[i]; i++) { exploded[ni] = o[n]; } } prototype.observe = exploded; } }, optimizePropertyMaps: function(prototype) { if (prototype.observe) { // construct name list var a = prototype._observeNames = []; for (var n in prototype.observe) { var names = n.split(' '); for (var i=0, ni; ni=names[i]; i++) { a.push(ni); } } } if (prototype.publish) { // construct name list var a = prototype._publishNames = []; for (var n in prototype.publish) { a.push(n); } } if (prototype.computed) { // construct name list var a = prototype._computedNames = []; for (var n in prototype.computed) { a.push(n); } } }, publishProperties: function(prototype, base) { // if we have any properties to publish var publish = prototype.publish; if (publish) { // transcribe `publish` entries onto own prototype this.requireProperties(publish, prototype, base); // warn and remove accessor names that are broken on some browsers this.filterInvalidAccessorNames(publish); // construct map of lower-cased property names prototype._publishLC = this.lowerCaseMap(publish); } var computed = prototype.computed; if (computed) { // warn and remove accessor names that are broken on some browsers this.filterInvalidAccessorNames(computed); } }, // Publishing/computing a property where the name might conflict with a // browser property is not currently supported to help users of Polymer // avoid browser bugs: // // https://code.google.com/p/chromium/issues/detail?id=43394 // https://bugs.webkit.org/show_bug.cgi?id=49739 // // We can lift this restriction when those bugs are fixed. filterInvalidAccessorNames: function(propertyNames) { for (var name in propertyNames) { // Check if the name is in our blacklist. if (this.propertyNameBlacklist[name]) { console.warn('Cannot define property "' + name + '" for element "' + this.name + '" because it has the same name as an HTMLElement ' + 'property, and not all browsers support overriding that. ' + 'Consider giving it a different name.'); // Remove the invalid accessor from the list. delete propertyNames[name]; } } }, // // `name: value` entries in the `publish` object may need to generate // matching properties on the prototype. // // Values that are objects may have a `reflect` property, which // signals that the value describes property control metadata. // In metadata objects, the prototype default value (if any) // is encoded in the `value` property. // // publish: { // foo: 5, // bar: {value: true, reflect: true}, // zot: {} // } // // `reflect` metadata property controls whether changes to the property // are reflected back to the attribute (default false). // // A value is stored on the prototype unless it's === `undefined`, // in which case the base chain is checked for a value. // If the basal value is also undefined, `null` is stored on the prototype. // // The reflection data is stored on another prototype object, `reflect` // which also can be specified directly. // // reflect: { // foo: true // } // requireProperties: function(propertyInfos, prototype, base) { // per-prototype storage for reflected properties prototype.reflect = prototype.reflect || {}; // ensure a prototype value for each property // and update the property's reflect to attribute status for (var n in propertyInfos) { var value = propertyInfos[n]; // value has metadata if it has a `reflect` property if (value && value.reflect !== undefined) { prototype.reflect[n] = Boolean(value.reflect); value = value.value; } // only set a value if one is specified if (value !== undefined) { prototype[n] = value; } } }, lowerCaseMap: function(properties) { var map = {}; for (var n in properties) { map[n.toLowerCase()] = n; } return map; }, createPropertyAccessor: function(name, ignoreWrites) { var proto = this.prototype; var privateName = name + '_'; var privateObservable = name + 'Observable_'; proto[privateName] = proto[name]; Object.defineProperty(proto, name, { get: function() { var observable = this[privateObservable]; if (observable) observable.deliver(); return this[privateName]; }, set: function(value) { if (ignoreWrites) { return this[privateName]; } var observable = this[privateObservable]; if (observable) { observable.setValue(value); return; } var oldValue = this[privateName]; this[privateName] = value; this.emitPropertyChangeRecord(name, value, oldValue); return value; }, configurable: true }); }, createPropertyAccessors: function(prototype) { var n$ = prototype._computedNames; if (n$ && n$.length) { for (var i=0, l=n$.length, n, fn; (i<l) && (n=n$[i]); i++) { this.createPropertyAccessor(n, true); } } var n$ = prototype._publishNames; if (n$ && n$.length) { for (var i=0, l=n$.length, n, fn; (i<l) && (n=n$[i]); i++) { // If the property is computed and published, the accessor is created // above. if (!prototype.computed || !prototype.computed[n]) { this.createPropertyAccessor(n); } } } }, // This list contains some property names that people commonly want to use, // but won't work because of Chrome/Safari bugs. It isn't an exhaustive // list. In particular it doesn't contain any property names found on // subtypes of HTMLElement (e.g. name, value). Rather it attempts to catch // some common cases. propertyNameBlacklist: { children: 1, 'class': 1, id: 1, hidden: 1, style: 1, title: 1, } }; // exports scope.api.declaration.properties = properties; })(Polymer); (function(scope) { // magic words var ATTRIBUTES_ATTRIBUTE = 'attributes'; var ATTRIBUTES_REGEX = /\s|,/; // attributes api var attributes = { inheritAttributesObjects: function(prototype) { // chain our lower-cased publish map to the inherited version this.inheritObject(prototype, 'publishLC'); // chain our instance attributes map to the inherited version this.inheritObject(prototype, '_instanceAttributes'); }, publishAttributes: function(prototype, base) { // merge names from 'attributes' attribute into the 'publish' object var attributes = this.getAttribute(ATTRIBUTES_ATTRIBUTE); if (attributes) { // create a `publish` object if needed. // the `publish` object is only relevant to this prototype, the // publishing logic in `declaration/properties.js` is responsible for // managing property values on the prototype chain. // TODO(sjmiles): the `publish` object is later chained to it's // ancestor object, presumably this is only for // reflection or other non-library uses. var publish = prototype.publish || (prototype.publish = {}); // names='a b c' or names='a,b,c' var names = attributes.split(ATTRIBUTES_REGEX); // record each name for publishing for (var i=0, l=names.length, n; i<l; i++) { // remove excess ws n = names[i].trim(); // looks weird, but causes n to exist on `publish` if it does not; // a more careful test would need expensive `in` operator if (n && publish[n] === undefined) { publish[n] = undefined; } } } }, // record clonable attributes from <element> accumulateInstanceAttributes: function() { // inherit instance attributes var clonable = this.prototype._instanceAttributes; // merge attributes from element var a$ = this.attributes; for (var i=0, l=a$.length, a; (i<l) && (a=a$[i]); i++) { if (this.isInstanceAttribute(a.name)) { clonable[a.name] = a.value; } } }, isInstanceAttribute: function(name) { return !this.blackList[name] && name.slice(0,3) !== 'on-'; }, // do not clone these attributes onto instances blackList: { name: 1, 'extends': 1, constructor: 1, noscript: 1, assetpath: 1, 'cache-csstext': 1 } }; // add ATTRIBUTES_ATTRIBUTE to the blacklist attributes.blackList[ATTRIBUTES_ATTRIBUTE] = 1; // exports scope.api.declaration.attributes = attributes; })(Polymer); (function(scope) { // imports var events = scope.api.declaration.events; var syntax = new PolymerExpressions(); var prepareBinding = syntax.prepareBinding; // Polymer takes a first crack at the binding to see if it's a declarative // event handler. syntax.prepareBinding = function(pathString, name, node) { return events.prepareEventBinding(pathString, name, node) || prepareBinding.call(syntax, pathString, name, node); }; // declaration api supporting mdv var mdv = { syntax: syntax, fetchTemplate: function() { return this.querySelector('template'); }, templateContent: function() { var template = this.fetchTemplate(); return template && template.content; }, installBindingDelegate: function(template) { if (template) { template.bindingDelegate = this.syntax; } } }; // exports scope.api.declaration.mdv = mdv; })(Polymer); (function(scope) { // imports var api = scope.api; var isBase = scope.isBase; var extend = scope.extend; var hasShadowDOMPolyfill = window.ShadowDOMPolyfill; // prototype api var prototype = { register: function(name, extendeeName) { // build prototype combining extendee, Polymer base, and named api this.buildPrototype(name, extendeeName); // register our custom element with the platform this.registerPrototype(name, extendeeName); // reference constructor in a global named by 'constructor' attribute this.publishConstructor(); }, buildPrototype: function(name, extendeeName) { // get our custom prototype (before chaining) var extension = scope.getRegisteredPrototype(name); // get basal prototype var base = this.generateBasePrototype(extendeeName); // implement declarative features this.desugarBeforeChaining(extension, base); // join prototypes this.prototype = this.chainPrototypes(extension, base); // more declarative features this.desugarAfterChaining(name, extendeeName); }, desugarBeforeChaining: function(prototype, base) { // back reference declaration element // TODO(sjmiles): replace `element` with `elementElement` or `declaration` prototype.element = this; // transcribe `attributes` declarations onto own prototype's `publish` this.publishAttributes(prototype, base); // `publish` properties to the prototype and to attribute watch this.publishProperties(prototype, base); // infer observers for `observe` list based on method names this.inferObservers(prototype); // desugar compound observer syntax, e.g. 'a b c' this.explodeObservers(prototype); }, chainPrototypes: function(prototype, base) { // chain various meta-data objects to inherited versions this.inheritMetaData(prototype, base); // chain custom api to inherited var chained = this.chainObject(prototype, base); // x-platform fixup ensurePrototypeTraversal(chained); return chained; }, inheritMetaData: function(prototype, base) { // chain observe object to inherited this.inheritObject('observe', prototype, base); // chain publish object to inherited this.inheritObject('publish', prototype, base); // chain reflect object to inherited this.inheritObject('reflect', prototype, base); // chain our lower-cased publish map to the inherited version this.inheritObject('_publishLC', prototype, base); // chain our instance attributes map to the inherited version this.inheritObject('_instanceAttributes', prototype, base); // chain our event delegates map to the inherited version this.inheritObject('eventDelegates', prototype, base); }, // implement various declarative features desugarAfterChaining: function(name, extendee) { // build side-chained lists to optimize iterations this.optimizePropertyMaps(this.prototype); this.createPropertyAccessors(this.prototype); // install mdv delegate on template this.installBindingDelegate(this.fetchTemplate()); // install external stylesheets as if they are inline this.installSheets(); // adjust any paths in dom from imports this.resolveElementPaths(this); // compile list of attributes to copy to instances this.accumulateInstanceAttributes(); // parse on-* delegates declared on `this` element this.parseHostEvents(); // // install a helper method this.resolvePath to aid in // setting resource urls. e.g. // this.$.image.src = this.resolvePath('images/foo.png') this.addResolvePathApi(); // under ShadowDOMPolyfill, transforms to approximate missing CSS features if (hasShadowDOMPolyfill) { WebComponents.ShadowCSS.shimStyling(this.templateContent(), name, extendee); } // allow custom element access to the declarative context if (this.prototype.registerCallback) { this.prototype.registerCallback(this); } }, // if a named constructor is requested in element, map a reference // to the constructor to the given symbol publishConstructor: function() { var symbol = this.getAttribute('constructor'); if (symbol) { window[symbol] = this.ctor; } }, // build prototype combining extendee, Polymer base, and named api generateBasePrototype: function(extnds) { var prototype = this.findBasePrototype(extnds); if (!prototype) { // create a prototype based on tag-name extension var prototype = HTMLElement.getPrototypeForTag(extnds); // insert base api in inheritance chain (if needed) prototype = this.ensureBaseApi(prototype); // memoize this base memoizedBases[extnds] = prototype; } return prototype; }, findBasePrototype: function(name) { return memoizedBases[name]; }, // install Polymer instance api into prototype chain, as needed ensureBaseApi: function(prototype) { if (prototype.PolymerBase) { return prototype; } var extended = Object.create(prototype); // we need a unique copy of base api for each base prototype // therefore we 'extend' here instead of simply chaining api.publish(api.instance, extended); // TODO(sjmiles): sharing methods across prototype chains is // not supported by 'super' implementation which optimizes // by memoizing prototype relationships. // Probably we should have a version of 'extend' that is // share-aware: it could study the text of each function, // look for usage of 'super', and wrap those functions in // closures. // As of now, there is only one problematic method, so // we just patch it manually. // To avoid re-entrancy problems, the special super method // installed is called `mixinSuper` and the mixin method // must use this method instead of the default `super`. this.mixinMethod(extended, prototype, api.instance.mdv, 'bind'); // return buffed-up prototype return extended; }, mixinMethod: function(extended, prototype, api, name) { var $super = function(args) { return prototype[name].apply(this, args); }; extended[name] = function() { this.mixinSuper = $super; return api[name].apply(this, arguments); } }, // ensure prototype[name] inherits from a prototype.prototype[name] inheritObject: function(name, prototype, base) { // require an object var source = prototype[name] || {}; // chain inherited properties onto a new object prototype[name] = this.chainObject(source, base[name]); }, // register 'prototype' to custom element 'name', store constructor registerPrototype: function(name, extendee) { var info = { prototype: this.prototype } // native element must be specified in extends var typeExtension = this.findTypeExtension(extendee); if (typeExtension) { info.extends = typeExtension; } // register the prototype with HTMLElement for name lookup HTMLElement.register(name, this.prototype); // register the custom type this.ctor = document.registerElement(name, info); }, findTypeExtension: function(name) { if (name && name.indexOf('-') < 0) { return name; } else { var p = this.findBasePrototype(name); if (p.element) { return this.findTypeExtension(p.element.extends); } } } }; // memoize base prototypes var memoizedBases = {}; // implementation of 'chainObject' depends on support for __proto__ if (Object.__proto__) { prototype.chainObject = function(object, inherited) { if (object && inherited && object !== inherited) { object.__proto__ = inherited; } return object; } } else { prototype.chainObject = function(object, inherited) { if (object && inherited && object !== inherited) { var chained = Object.create(inherited); object = extend(chained, object); } return object; } } // On platforms that do not support __proto__ (versions of IE), the prototype // chain of a custom element is simulated via installation of __proto__. // Although custom elements manages this, we install it here so it's // available during desugaring. function ensurePrototypeTraversal(prototype) { if (!Object.__proto__) { var ancestor = Object.getPrototypeOf(prototype); prototype.__proto__ = ancestor; if (isBase(ancestor)) { ancestor.__proto__ = Object.getPrototypeOf(ancestor); } } } // exports api.declaration.prototype = prototype; })(Polymer); (function(scope) { /* Elements are added to a registration queue so that they register in the proper order at the appropriate time. We do this for a few reasons: * to enable elements to load resources (like stylesheets) asynchronously. We need to do this until the platform provides an efficient alternative. One issue is that remote @import stylesheets are re-fetched whenever stamped into a shadowRoot. * to ensure elements loaded 'at the same time' (e.g. via some set of imports) are registered as a batch. This allows elements to be enured from upgrade ordering as long as they query the dom tree 1 task after upgrade (aka domReady). This is a performance tradeoff. On the one hand, elements that could register while imports are loading are prevented from doing so. On the other, grouping upgrades into a single task means less incremental work (for example style recalcs), Also, we can ensure the document is in a known state at the single quantum of time when elements upgrade. */ var queue = { // tell the queue to wait for an element to be ready wait: function(element) { if (!element.__queue) { element.__queue = {}; elements.push(element); } }, // enqueue an element to the next spot in the queue. enqueue: function(element, check, go) { var shouldAdd = element.__queue && !element.__queue.check; if (shouldAdd) { queueForElement(element).push(element); element.__queue.check = check; element.__queue.go = go; } return (this.indexOf(element) !== 0); }, indexOf: function(element) { var i = queueForElement(element).indexOf(element); if (i >= 0 && document.contains(element)) { i += (HTMLImports.useNative || HTMLImports.ready) ? importQueue.length : 1e9; } return i; }, // tell the queue an element is ready to be registered go: function(element) { var readied = this.remove(element); if (readied) { element.__queue.flushable = true; this.addToFlushQueue(readied); this.check(); } }, remove: function(element) { var i = this.indexOf(element); if (i !== 0) { //console.warn('queue order wrong', i); return; } return queueForElement(element).shift(); }, check: function() { // next var element = this.nextElement(); if (element) { element.__queue.check.call(element); } if (this.canReady()) { this.ready(); return true; } }, nextElement: function() { return nextQueued(); }, canReady: function() { return !this.waitToReady && this.isEmpty(); }, isEmpty: function() { for (var i=0, l=elements.length, e; (i<l) && (e=elements[i]); i++) { if (e.__queue && !e.__queue.flushable) { return; } } return true; }, addToFlushQueue: function(element) { flushQueue.push(element); }, flush: function() { // prevent re-entrance if (this.flushing) { return; } this.flushing = true; var element; while (flushQueue.length) { element = flushQueue.shift(); element.__queue.go.call(element); element.__queue = null; } this.flushing = false; }, ready: function() { // TODO(sorvell): As an optimization, turn off CE polyfill upgrading // while registering. This way we avoid having to upgrade each document // piecemeal per registration and can instead register all elements // and upgrade once in a batch. Without this optimization, upgrade time // degrades significantly when SD polyfill is used. This is mainly because // querying the document tree for elements is slow under the SD polyfill. var polyfillWasReady = CustomElements.ready; CustomElements.ready = false; this.flush(); if (!CustomElements.useNative) { CustomElements.upgradeDocumentTree(document); } CustomElements.ready = polyfillWasReady; Polymer.flush(); requestAnimationFrame(this.flushReadyCallbacks); }, addReadyCallback: function(callback) { if (callback) { readyCallbacks.push(callback); } }, flushReadyCallbacks: function() { if (readyCallbacks) { var fn; while (readyCallbacks.length) { fn = readyCallbacks.shift(); fn(); } } }, /** Returns a list of elements that have had polymer-elements created but are not yet ready to register. The list is an array of element definitions. */ waitingFor: function() { var e$ = []; for (var i=0, l=elements.length, e; (i<l) && (e=elements[i]); i++) { if (e.__queue && !e.__queue.flushable) { e$.push(e); } } return e$; }, waitToReady: true }; var elements = []; var flushQueue = []; var importQueue = []; var mainQueue = []; var readyCallbacks = []; function queueForElement(element) { return document.contains(element) ? mainQueue : importQueue; } function nextQueued() { return importQueue.length ? importQueue[0] : mainQueue[0]; } function whenReady(callback) { queue.waitToReady = true; Polymer.endOfMicrotask(function() { HTMLImports.whenReady(function() { queue.addReadyCallback(callback); queue.waitToReady = false; queue.check(); }); }); } /** Forces polymer to register any pending elements. Can be used to abort waiting for elements that are partially defined. @param timeout {Integer} Optional timeout in milliseconds */ function forceReady(timeout) { if (timeout === undefined) { queue.ready(); return; } var handle = setTimeout(function() { queue.ready(); }, timeout); Polymer.whenReady(function() { clearTimeout(handle); }); } // exports scope.elements = elements; scope.waitingFor = queue.waitingFor.bind(queue); scope.forceReady = forceReady; scope.queue = queue; scope.whenReady = scope.whenPolymerReady = whenReady; })(Polymer); (function(scope) { // imports var extend = scope.extend; var api = scope.api; var queue = scope.queue; var whenReady = scope.whenReady; var getRegisteredPrototype = scope.getRegisteredPrototype; var waitingForPrototype = scope.waitingForPrototype; // declarative implementation: <polymer-element> var prototype = extend(Object.create(HTMLElement.prototype), { createdCallback: function() { if (this.getAttribute('name')) { this.init(); } }, init: function() { // fetch declared values this.name = this.getAttribute('name'); this.extends = this.getAttribute('extends'); queue.wait(this); // initiate any async resource fetches this.loadResources(); // register when all constraints are met this.registerWhenReady(); }, // TODO(sorvell): we currently queue in the order the prototypes are // registered, but we should queue in the order that polymer-elements // are registered. We are currently blocked from doing this based on // crbug.com/395686. registerWhenReady: function() { if (this.registered || this.waitingForPrototype(this.name) || this.waitingForQueue() || this.waitingForResources()) { return; } queue.go(this); }, _register: function() { //console.log('registering', this.name); // warn if extending from a custom element not registered via Polymer if (isCustomTag(this.extends) && !isRegistered(this.extends)) { console.warn('%s is attempting to extend %s, an unregistered element ' + 'or one that was not registered with Polymer.', this.name, this.extends); } this.register(this.name, this.extends); this.registered = true; }, waitingForPrototype: function(name) { if (!getRegisteredPrototype(name)) { // then wait for a prototype waitingForPrototype(name, this); // emulate script if user is not supplying one this.handleNoScript(name); // prototype not ready yet return true; } }, handleNoScript: function(name) { // if explicitly marked as 'noscript' if (this.hasAttribute('noscript') && !this.noscript) { this.noscript = true; // imperative element registration Polymer(name); } }, waitingForResources: function() { return this._needsResources; }, // NOTE: Elements must be queued in proper order for inheritance/composition // dependency resolution. Previously this was enforced for inheritance, // and by rule for composition. It's now entirely by rule. waitingForQueue: function() { return queue.enqueue(this, this.registerWhenReady, this._register); }, loadResources: function() { this._needsResources = true; this.loadStyles(function() { this._needsResources = false; this.registerWhenReady(); }.bind(this)); } }); // semi-pluggable APIs // TODO(sjmiles): should be fully pluggable (aka decoupled, currently // the various plugins are allowed to depend on each other directly) api.publish(api.declaration, prototype); // utility and bookkeeping function isRegistered(name) { return Boolean(HTMLElement.getPrototypeForTag(name)); } function isCustomTag(name) { return (name && name.indexOf('-') >= 0); } // boot tasks whenReady(function() { document.body.removeAttribute('unresolved'); document.dispatchEvent( new CustomEvent('polymer-ready', {bubbles: true}) ); }); // register polymer-element with document document.registerElement('polymer-element', {prototype: prototype}); })(Polymer); (function(scope) { /** * @class Polymer */ var whenReady = scope.whenReady; /** * Loads the set of HTMLImports contained in `node`. Notifies when all * the imports have loaded by calling the `callback` function argument. * This method can be used to lazily load imports. For example, given a * template: * * <template> * <link rel="import" href="my-import1.html"> * <link rel="import" href="my-import2.html"> * </template> * * Polymer.importElements(template.content, function() { * console.log('imports lazily loaded'); * }); * * @method importElements * @param {Node} node Node containing the HTMLImports to load. * @param {Function} callback Callback called when all imports have loaded. */ function importElements(node, callback) { if (node) { document.head.appendChild(node); whenReady(callback); } else if (callback) { callback(); } } /** * Loads an HTMLImport for each url specified in the `urls` array. * Notifies when all the imports have loaded by calling the `callback` * function argument. This method can be used to lazily load imports. * For example, * * Polymer.import(['my-import1.html', 'my-import2.html'], function() { * console.log('imports lazily loaded'); * }); * * @method import * @param {Array} urls Array of urls to load as HTMLImports. * @param {Function} callback Callback called when all imports have loaded. */ function _import(urls, callback) { if (urls && urls.length) { var frag = document.createDocumentFragment(); for (var i=0, l=urls.length, url, link; (i<l) && (url=urls[i]); i++) { link = document.createElement('link'); link.rel = 'import'; link.href = url; frag.appendChild(link); } importElements(frag, callback); } else if (callback) { callback(); } } // exports scope.import = _import; scope.importElements = importElements; })(Polymer); /** * The `auto-binding` element extends the template element. It provides a quick * and easy way to do data binding without the need to setup a model. * The `auto-binding` element itself serves as the model and controller for the * elements it contains. Both data and event handlers can be bound. * * The `auto-binding` element acts just like a template that is bound to * a model. It stamps its content in the dom adjacent to itself. When the * content is stamped, the `template-bound` event is fired. * * Example: * * <template is="auto-binding"> * <div>Say something: <input value="{{value}}"></div> * <div>You said: {{value}}</div> * <button on-tap="{{buttonTap}}">Tap me!</button> * </template> * <script> * var template = document.querySelector('template'); * template.value = 'something'; * template.buttonTap = function() { * console.log('tap!'); * }; * </script> * * @module Polymer * @status stable */ (function() { var element = document.createElement('polymer-element'); element.setAttribute('name', 'auto-binding'); element.setAttribute('extends', 'template'); element.init(); Polymer('auto-binding', { createdCallback: function() { this.syntax = this.bindingDelegate = this.makeSyntax(); // delay stamping until polymer-ready so that auto-binding is not // required to load last. Polymer.whenPolymerReady(function() { this.model = this; this.setAttribute('bind', ''); // we don't bother with an explicit signal here, we could ust a MO // if necessary this.async(function() { // note: this will marshall *all* the elements in the parentNode // rather than just stamped ones. We'd need to use createInstance // to fix this or something else fancier. this.marshalNodeReferences(this.parentNode); // template stamping is asynchronous so stamping isn't complete // by polymer-ready; fire an event so users can use stamped elements this.fire('template-bound'); }); }.bind(this)); }, makeSyntax: function() { var events = Object.create(Polymer.api.declaration.events); var self = this; events.findController = function() { return self.model; }; var syntax = new PolymerExpressions(); var prepareBinding = syntax.prepareBinding; syntax.prepareBinding = function(pathString, name, node) { return events.prepareEventBinding(pathString, name, node) || prepareBinding.call(syntax, pathString, name, node); }; return syntax; } }); })();
examples/webrx/node_modules/rx/dist/rx.all.js
startersacademy/todomvc
// 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'; }, 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 = 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); }, 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) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(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 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; } 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; } // 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(); } }; // 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; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; 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(); 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)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); 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; }()); /** 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 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 = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && 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 MSG_PREFIX = 'ms.rx.schedule' + Math.random(); 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)); } } 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); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * 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 a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * 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); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * 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 CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); 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 ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); 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)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * 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); }); }); }; 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); }); }; 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); return sink.run(); }; function EmptySink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { state.onCompleted(); } EmptySink.prototype.run = function () { return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); }; return EmptyObservable; }(ObservableBase)); /** * 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 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 (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) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { return o.onError(e); } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; 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); }; /** * Creates an Observable sequence from changes to an array using Array.observe. * @param {Array} array An array to observe changes. * @returns {Observable} An observable sequence containing changes to an array from Array.observe. */ Observable.ofArrayChanges = function(array) { if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); } if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Array.observe(array, observerFn); return function () { Array.unobserve(array, observerFn); }; }); }; /** * Creates an Observable sequence from changes to an object using Object.observe. * @param {Object} obj An object to observe changes. * @returns {Observable} An observable sequence containing changes to an object from Object.observe. */ Observable.ofObjectChanges = function(obj) { if (obj == null) { throw new TypeError('object must not be null or undefined.'); } if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Object.observe(obj, observerFn); return function () { Object.unobserve(obj, observerFn); }; }); }; var NeverObservable = (function(__super__) { inherits(NeverObservable, __super__); function NeverObservable() { __super__.call(this); } NeverObservable.prototype.subscribeCore = function (observer) { return disposableEmpty; }; return NeverObservable; }(ObservableBase)); /** * 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 NeverObservable(); }; 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.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); }; 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); return sink.run(); }; function JustSink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { var value = state[0], observer = state[1]; observer.onNext(value); observer.onCompleted(); } JustSink.prototype.run = function () { return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], 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 = Observable.returnValue = 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 (observer) { var sink = new ThrowSink(observer, this); return sink.run(); }; function ThrowSink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { var error = state[0], observer = state[1]; observer.onError(error); } ThrowSink.prototype.run = function () { return this.parent.scheduler.scheduleWithState([this.parent.error, this.observer], 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'] = Observable.throwError = Observable.throwException = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new ThrowObservable(error, scheduler); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; 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; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * 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); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * 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; return new AnonymousObservable(function (observer) { var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; 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); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { 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 () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, 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; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }, source); }; 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.call(this, 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); }; 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 notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * 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.call(this, 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); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (o) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { o.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { o.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, function (e) { o.onError(e); }, function () { o.onNext(list); o.onCompleted(); }); }, source); } function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @deprecated Use #reduce instead * @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 a single element with the final accumulator value. */ observableProto.aggregate = function () { var hasSeed = false, accumulator, seed, 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) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var hasSeed = false, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } 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) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, function (e) { observer.onError(e); }, function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); }; /** @deprecated use #every instead */ observableProto.all = function () { //deprecate('all', 'every'); return this.every.apply(this, arguments); }; /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ observableProto.includes = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(false); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { o.onNext(true); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onNext(false); o.onCompleted(); }); }, this); }; /** * @deprecated use #includes instead. */ observableProto.contains = function (searchElement, fromIndex) { //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { o.onNext(i); o.onCompleted(); } i++; }, function (e) { o.onError(e); }, function () { o.onNext(-1); o.onCompleted(); }); }, source); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).average() : this.reduce(function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }, {sum: 0, count: 0 }).map(function (s) { if (s.count === 0) { throw new EmptyError(); } return s.sum / s.count; }); }; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { o.onError(e); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { o.onError(exception); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }, first); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (o) { var i = index; return source.subscribe(function (x) { if (i-- === 0) { o.onNext(x); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new ArgumentOutOfRangeError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate && isFunction(predicate) ? this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { return source.subscribe(function (x) { o.onNext(x); o.onCompleted(); }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new EmptyError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = callback(x, i, source); } catch (e) { o.onError(e); return; } if (shouldRun) { o.onNext(yieldIndex ? i : x); o.onCompleted(); } else { i++; } }, function (e) { o.onError(e); }, function () { o.onNext(yieldIndex ? -1 : undefined); o.onCompleted(); }); }, source); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { if (typeof root.Set === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var s = new root.Set(); return source.subscribe( function (x) { s.add(x); }, function (e) { o.onError(e); }, function () { o.onNext(s); o.onCompleted(); }); }, source); }; /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { if (typeof root.Map === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { o.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { o.onError(e); return; } } m.set(key, element); }, function (e) { o.onError(e); }, function () { o.onNext(m); o.onCompleted(); }); }, source); }; var fnString = 'function', throwString = 'throw', isObject = Rx.internals.isObject; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res) { if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThunk(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn) { promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && typeof obj.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fn; if (isGenFun) { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : handleError; gen = fn.apply(this, args); } else { done = done || handleError; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) { for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } } if (err) { try { ret = gen[throwString](err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function() { if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; function handleError(err) { if (!err) { return; } timeoutScheduler.schedule(function() { throw err; }); } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * 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 () { 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() { var len = arguments.length, results = new Array(len); for(var i = 0; i < len; i++) { results[i] = arguments[i]; } if (selector) { try { results = selector.apply(context, 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.apply(context, 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 createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } 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(); }; /** * 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); } 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, 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 = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.scheduler = scheduler || currentThreadScheduler; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } else { this.queue.push(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(Notification.createOnError(error)); } }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(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}; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this; this.requestedDisposable = this.scheduler.scheduleWithState(number, function(s, i) { var r = self._processRequest(i), remaining = r.numberOfItems; if (!r.returnValue) { self.requestedCount = remaining; self.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); } }); return this.requestedDisposable; }, 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 {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 is paused based upon the pauser. */ observableProto.controlled = function (enableQueue, scheduler) { if (enableQueue && isScheduler(enableQueue)) { scheduler = enableQueue; enableQueue = true; } if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue, scheduler); }; var StopAndWaitObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(1); }); return this.subscription; } inherits(StopAndWaitObservable, __super__); function StopAndWaitObservable (source) { __super__.call(this, subscribe, source); this.source = source; } var StopAndWaitObserver = (function (__sub__) { inherits(StopAndWaitObserver, __sub__); function StopAndWaitObserver (observer, observable, cancel) { __sub__.call(this); this.observer = observer; this.observable = observable; this.cancel = cancel; } var stopAndWaitObserverProto = StopAndWaitObserver.prototype; stopAndWaitObserverProto.completed = function () { this.observer.onCompleted(); this.dispose(); }; stopAndWaitObserverProto.error = function (error) { this.observer.onError(error); this.dispose(); } stopAndWaitObserverProto.next = function (value) { this.observer.onNext(value); var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(1); }); }; stopAndWaitObserverProto.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return StopAndWaitObserver; }(AbstractObserver)); return StopAndWaitObservable; }(Observable)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait observable. */ ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; var WindowedObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(self.windowSize); }); return this.subscription; } inherits(WindowedObservable, __super__); function WindowedObservable(source, windowSize) { __super__.call(this, subscribe, source); this.source = source; this.windowSize = windowSize; } var WindowedObserver = (function (__sub__) { inherits(WindowedObserver, __sub__); function WindowedObserver(observer, observable, cancel) { this.observer = observer; this.observable = observable; this.cancel = cancel; this.received = 0; } var windowedObserverPrototype = WindowedObserver.prototype; windowedObserverPrototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; windowedObserverPrototype.error = function (error) { this.observer.onError(error); this.dispose(); }; windowedObserverPrototype.next = function (value) { this.observer.onNext(value); this.received = ++this.received % this.observable.windowSize; if (this.received === 0) { var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(self.observable.windowSize); }); } }; windowedObserverPrototype.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return WindowedObserver; }(AbstractObserver)); return WindowedObservable; }(Observable)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * 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; }; /** * 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 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 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)); 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)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if ((candidate & 1) === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash << 5) - hash) + character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof valueOf === 'string') { return stringHashFn(valueOf); } } if (obj.hashCode) { return obj.hashCode(); } var id = 17 * uniqueIdCounter++; obj.hashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new ArgumentOutOfRangeError(); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }, left); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }, left); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBoundaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }, source); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }, source); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { return [ this.filter(predicate, thisArg), this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }, this); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = []; if (Array.isArray(arguments[0])) { allSources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } } return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }, first); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }, source); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeAll().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwError(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { return this.onError(notification.exception); } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param {Function} selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var len = arguments.length, plans; if (Array.isArray(arguments[0])) { plans = arguments[0]; } else { plans = new Array(len); for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( function (x) { o.onNext(x); }, function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); o.onError(err); }, function (x) { o.onCompleted(); } ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && o.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(o); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; 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); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * 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 (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); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds * * @param {Number} dueTime Relative or absolute time shift of the subscription. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var d = new SerialDisposable(); d.setDisposable(scheduler[scheduleMethod](dueTime, function() { d.setDisposable(source.subscribe(o)); })); return d; }, this); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (isFunction(subscriptionDelay)) { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable(); function start() { subscription.setDisposable(source.subscribe( function (x) { var delay = tryCatch(selector)(x); if (delay === errorObj) { return observer.onError(delay.e); } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe( function () { observer.onNext(x); delays.remove(d); done(); }, function (e) { observer.onError(e); }, function () { observer.onNext(x); delays.remove(d); done(); } )) }, function (e) { observer.onError(e); }, function () { atEnd = true; subscription.dispose(); done(); } )) } function done () { atEnd && delays.length === 0 && observer.onCompleted(); } if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); } return new CompositeDisposable(subscription, delays); }, this); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The debounced sequence. */ observableProto.debounceWithSelector = function (durationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = durationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, 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); }, source); }; /** * @deprecated use #debounceWithSelector instead. */ observableProto.throttleWithSelector = function (durationSelector) { //deprecate('throttleWithSelector', 'debounceWithSelector'); return this.debounceWithSelector(durationSelector); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } o.onCompleted(); }); }, source); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { o.onNext(next.value); } } o.onCompleted(); }); }, source); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }, source); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); })); }, source); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), source.subscribe(o)); }, 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); }; /** * 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(o) { return { '@@transducer/init': function() { return o; }, '@@transducer/step': function(obs, input) { return obs.onNext(input); }, '@@transducer/result': function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(o) { var xform = transducer(transformForObserver(o)); return source.subscribe( function(v) { try { xform['@@transducer/step'](o, v); } catch (e) { o.onError(e); } }, function (e) { o.onError(e); }, function() { xform['@@transducer/result'](o); } ); }, source); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }, this); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this, selectorFunc = bindCallback(selector, thisArg, 3); return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selectorFunc(x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (e) { observer.onError(e); }, function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, function (e) { observer.onError(e); }, function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }, this); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @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). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); 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 GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * 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)); /** * 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));
src/containers/Onboarding/Registration.js
LedgerHQ/ledger-vault-front
//@flow import { connect } from "react-redux"; import type { Translate } from "data/types"; import { translate } from "react-i18next"; import React, { Component } from "react"; import { withStyles } from "@material-ui/core/styles"; import BlurDialog from "components/BlurDialog"; import Plus from "../../components/icons/full/Plus"; import AddMember from "./AddMember"; import { Title, Introduction } from "../../components/Onboarding.js"; import People from "../../components/icons/thin/People"; import DialogButton from "components/buttons/DialogButton"; import Footer from "./Footer"; import { addMessage } from "redux/modules/alerts"; import { getRegistrationChallenge, addMember, editMember, toggleMemberModal } from "redux/modules/onboarding"; import MemberRow from "components/MemberRow"; import SpinnerCard from "components/spinners/SpinnerCard"; import type { Member } from "data/types"; const styles = { add: { color: "#27d0e2", textDecoration: "none", textTransform: "uppercase", fontSize: 11, fontWeight: 600, position: "absolute", cursor: "pointer", top: 8, right: 0 }, plus: { width: 11, marginRight: 10, verticalAlign: "middle" } }; const noMembers = { base: { fontSize: 11, lineHeight: 1.82, textAlign: "center", width: 264, margin: "auto", marginTop: 110 }, label: { fontSize: 11, fontWeight: 600, margin: 0, marginBottom: 5, textAlign: "center", textTransform: "uppercase" }, info: { fontSize: 11, textAlign: "center", lineHeight: 1.82, margin: 0 } }; const NoMembers = translate()( withStyles( noMembers )( ({ classes, t }: { classes: { [$Keys<typeof noMembers>]: string }, t: Translate }) => { return ( <div className={classes.base}> <People color="#cccccc" style={{ height: 29, display: "block", margin: "auto", marginBottom: 21 }} /> <div className={classes.label}> {t("onboarding:administrators_registration.add_member_title")} </div> <div className={classes.info}> {t("onboarding:administrators_registration.at_least")} </div> </div> ); } ) ); const membersList = { base: { maxHeight: 272, overflow: "auto" }, row: { cursor: "pointer" } }; const MembersList = withStyles( membersList )( ({ classes, members, editMember }: { classes: { [$Keys<typeof membersList>]: string }, members: Array<Member>, editMember: Function }) => { return ( <div className={classes.base}> {members.map((member, k) => ( <MemberRow key={k} onSelect={() => editMember(member)} editable member={member} /> ))} </div> ); } ); const mapStateToProps = state => ({ onboarding: state.onboarding }); const mapDispatch = (dispatch: *) => ({ onToggleModalProfile: member => dispatch(toggleMemberModal(member)), onAddMember: data => dispatch(addMember(data)), onEditMember: data => dispatch(editMember(data)), onGetChallenge: () => dispatch(getRegistrationChallenge()), onAddMessage: (title, message, type) => dispatch(addMessage(title, message, type)) }); type Props = { classes: { [$Keys<typeof styles>]: string }, onToggleModalProfile: Function, onAddMember: Function, onGetChallenge: Function, onEditMember: Function, onAddMessage: Function, onboarding: *, t: Translate }; class Registration extends Component<Props, *> { componentDidMount() { // make an API call to get the challenge needed to register all the new members const { onGetChallenge } = this.props; onGetChallenge(); } addMember = data => { this.props.onAddMember(data); this.props.onToggleModalProfile(); }; editMember = member => { this.props.onToggleModalProfile(member); }; render() { const { classes, onboarding, onToggleModalProfile, onEditMember, onAddMessage, t } = this.props; if (!onboarding.registering || !onboarding.registering.challenge) { return <SpinnerCard />; } return ( <div> <Title>{t("onboarding:administrators_registration.title")}</Title> <BlurDialog open={onboarding.member_modal} onClose={onToggleModalProfile} > <AddMember close={onToggleModalProfile} finish={this.addMember} member={onboarding.editMember} editMember={onEditMember} setAlert={onAddMessage} challenge={onboarding.registering.challenge} /> </BlurDialog> <div onClick={() => onToggleModalProfile()} className={classes.add}> <Plus className={classes.plus} /> {t("onboarding:administrators_registration.add_member")} </div> <Introduction> {t("onboarding:administrators_registration.description")} <p> <strong> {t("onboarding:administrators_registration.description_strong")} </strong> </p> </Introduction> {onboarding.registering.admins.length === 0 ? ( <NoMembers /> ) : ( <MembersList members={onboarding.registering.admins} editMember={this.editMember} /> )} <Footer nextState render={onNext => ( <DialogButton highlight onTouchTap={onNext} disabled={onboarding.registering.admins.length < 3} > {t("common:continue")} </DialogButton> )} /> </div> ); } } export default connect(mapStateToProps, mapDispatch)( withStyles(styles)(translate()(Registration)) );
src/containers/DevTools/createDevToolsWindow.js
Viral-MediaLab/viralSitePubPub
import React from 'react'; import { render } from 'react-dom'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; /* * Puts Redux DevTools into a separate window. * Based on https://gist.github.com/tlrobinson/1e63d15d3e5f33410ef7#gistcomment-1560218. */ export default function createDevToolsWindow(store) { // Give it a name so it reuses the same window const name = 'Redux DevTools'; const win = window.open( null, name, 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no,width=450,height=5000' ); if (!win) { console.error( // eslint-disable-line no-console 'Couldn\'t open Redux DevTools due to a popup blocker. ' + 'Please disable the popup blocker for the current page.' ); return; } // Reload in case it's reusing the same window with the old content. win.location.reload(); // Set visible Window title. win.document.title = name; // Wait a little bit for it to reload, then render. setTimeout(() => render( <DebugPanel top right bottom left> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel>, win.document.body.appendChild(document.createElement('div')) ), 10); }
ajax/libs/yui/3.13.0/event-custom-base/event-custom-base-debug.js
marxo/cdnjs
YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor === DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor === DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} defaults configuration object. * @class CustomEvent * @constructor */ /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ Y.CustomEvent = function(type, defaults) { this._kds = Y.CustomEvent.keepDeprecatedSubs; this.id = Y.guid(); this.type = type; this.silent = this.logSystem = (type === YUI_LOG); if (this._kds) { /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ /** * 'After' subscribers * @property afters * @type Subscriber {} * @deprecated */ this.subscribers = {}; this.afters = {}; } if (defaults) { mixConfigs(this, defaults, true); } }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ /** * This event has fired if true * * @property fired * @type boolean * @default false; */ /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ signature : YUI3_SIGNATURE, /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ context : Y, /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ preventable : true, /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ bubbles : true, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = 0, a = 0, subs = this._subscribers, afters = this._afters, sib = this.sibling; if (subs) { s = subs.length; } if (afters) { a = afters.length; } if (sib) { subs = sib._subscribers; afters = sib._afters; if (subs) { s += subs.length; } if (afters) { a += afters.length; } } if (when) { return (when === 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var sibling = this.sibling, subs = this._subscribers, afters = this._afters, siblingSubs, siblingAfters; if (sibling) { siblingSubs = sibling._subscribers; siblingAfters = sibling._afters; } if (siblingSubs) { if (subs) { subs = subs.concat(siblingSubs); } else { subs = siblingSubs.concat(); } } else { if (subs) { subs = subs.concat(); } else { subs = []; } } if (siblingAfters) { if (afters) { afters = afters.concat(siblingAfters); } else { afters = siblingAfters.concat(); } } else { if (afters) { afters = afters.concat(); } else { afters = []; } } return [subs, afters]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when), firedWith; if (this.fireOnce && this.fired) { firedWith = this.firedWith; // It's a little ugly for this to know about facades, // but given the current breakup, not much choice without // moving a whole lot of stuff around. if (this.emitFacade && this._addFacadeToArgs) { this._addFacadeToArgs(firedWith); } if (this.async) { setTimeout(Y.bind(this._notify, this, s, firedWith), 0); } else { this._notify(s, firedWith); } } if (when === AFTER) { if (!this._afters) { this._afters = []; } this._afters.push(s); } else { if (!this._subscribers) { this._subscribers = []; } this._subscribers.push(s); } if (this._kds) { if (when === AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; if (subs) { for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } } if (afters) { for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { // push is the fastest way to go from arguments to arrays // for most browsers currently // http://jsperf.com/push-vs-concat-vs-slice/2 var args = []; args.push.apply(args, arguments); return this._fire(args); }, /** * Private internal implementation for `fire`, which is can be used directly by * `EventTarget` and other event module classes which have already converted from * an `arguments` list to an array, to avoid the repeated overhead. * * @method _fire * @private * @param {Array} args The array of arguments passed to be passed to handlers. * @return {boolean} false if one of the subscribers returned false, true otherwise. */ _fire: function(args) { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } if (this.broadcast) { this._broadcast(args); } return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped === 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast === 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; } if (subs) { i = YArray.indexOf(subs, s, 0); if (s && subs[i] === s) { subs.splice(i, 1); } } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.guid(); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn === fn) && this.context === context); } else { return (this.fn === fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = function(type, pre) { if (!pre || !type || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }, /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t === '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var etState = this._yuievt, etConfig; if (!etState) { etState = this._yuievt = { events: {}, // PERF: Not much point instantiating lazily. We're bound to have events targets: null, // PERF: Instantiate lazily, if user actually adds target, config: { host: this, context: this }, chain: Y.config.chain }; } etConfig = etState.config; if (opts) { mixConfigs(etConfig, opts, true); if (opts.chain !== undefined) { etState.chain = opts.chain; } if (opts.prefix) { etConfig.prefix = opts.prefix; } } }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); // TODO: More robust regex, accounting for category if (type.indexOf("*:") !== -1) { this._hasSiblings = true; } } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var ret, etState = this._yuievt, etConfig = etState.config, pre = etConfig.prefix; if (typeof type === "string") { if (pre) { type = _getType(type, pre); } ret = this._publish(type, etConfig, opts); } else { ret = {}; Y.each(type, function(v, k) { if (pre) { k = _getType(k, pre); } ret[k] = this._publish(k, etConfig, v || opts); }, this); } return ret; }, /** * Returns the fully qualified type, given a short type string. * That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix. * * NOTE: This method, unlike _getType, does no checking of the value passed in, and * is designed to be used with the low level _publish() method, for critical path * implementations which need to fast-track publish for performance reasons. * * @method _getFullType * @private * @param {String} type The short type to prefix * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in */ _getFullType : function(type) { var pre = this._yuievt.config.prefix; if (pre) { return pre + PREFIX_DELIMITER + type; } else { return type; } }, /** * The low level event publish implementation. It expects all the massaging to have been done * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast * path publish, which can be used by critical code paths to improve performance. * * @method _publish * @private * @param {String} fullType The prefixed type of the event to publish. * @param {Object} etOpts The EventTarget specific configuration to mix into the published event. * @param {Object} ceOpts The publish specific configuration to mix into the published event. * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will * be the default `CustomEvent` instance, and can be configured independently. */ _publish : function(fullType, etOpts, ceOpts) { var ce, etState = this._yuievt, etConfig = etState.config, host = etConfig.host, context = etConfig.context, events = etState.events; ce = events[fullType]; // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight. if ((etConfig.monitored && !ce) || (ce && ce.monitored)) { this._monitor('publish', fullType, { args: arguments }); } if (!ce) { // Publish event ce = events[fullType] = new Y.CustomEvent(fullType, etOpts); if (!etOpts) { ce.host = host; ce.context = context; } } if (ceOpts) { mixConfigs(ce, ceOpts, true); } return ce; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {Boolean} True if the whole lifecycle of the event went through, * false if at any point the event propagation was halted. */ fire: function(type) { var typeIncluded = (typeof type === "string"), argCount = arguments.length, t = type, yuievt = this._yuievt, etConfig = yuievt.config, pre = etConfig.prefix, ret, ce, ce2, args; if (typeIncluded && argCount <= 3) { // PERF: Try to avoid slice/iteration for the common signatures // Most common if (argCount === 2) { args = [arguments[1]]; // fire("foo", {}) } else if (argCount === 3) { args = [arguments[1], arguments[2]]; // fire("foo", {}, opts) } else { args = []; // fire("foo") } } else { args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0)); } if (!typeIncluded) { t = (type && type.type); } if (pre) { t = _getType(t, pre); } ce = yuievt.events[t]; if (this._hasSiblings) { ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } } // PERF: trying to avoid function call, since this is a critical path if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { this._monitor('fire', (ce || t), { args: args }); } // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { if (ce2) { ce.sibling = ce2; } ret = ce._fire(args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); ce2 = this.getEvent(type, true); if (ce2) { ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]});
view/src/components/FileTable.js
reliablejs/reliable-master
'use strict'; import React from 'react'; import { List } from 'antd'; export default class DepTable extends React.Component { state = { loading: false, }; render () { return ( <List size="small" bordered dataSource={this.props.data} renderItem={item => ( <List.Item> <a href={item.fileAddress} target="_blank">{item.fileName}</a> </List.Item> )} /> ); } }
src/pages/Game/index.js
alimek/scrum-poker-react
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import styles from './styles.css'; import { Loader } from '../../components'; import GameSideMenu from '../../containers/GameSideMenu'; import GameContext from '../../containers/GameContext'; import { getGame } from '../../actions/game'; class Game extends React.Component { static propTypes = { game: PropTypes.shape({ id: PropTypes.string, }).isRequired, match: PropTypes.shape({ params: PropTypes.shape().isRequired, }).isRequired, history: PropTypes.shape({ push: PropTypes.func.isRequired, }).isRequired, actions: PropTypes.shape({ getGame: PropTypes.func.isRequired, }).isRequired, }; constructor(props) { super(props); const { actions, match, history, } = this.props; actions .getGame(match.params.gameId) .catch(() => history.push('/login')); } render() { const { game } = this.props; const { isLoaded } = game; if (!isLoaded) return <Loader />; return ( <div className={styles.game}> <GameSideMenu /> <GameContext /> </div> ); } } export default connect( store => ({ game: store.game, user: store.user, }), dispatch => ({ actions: bindActionCreators({ getGame }, dispatch), }), )(Game);
src/Preloader.js
jareth/react-materialize
import React from 'react'; import cx from 'classnames'; const Spinner = () => { let {color, only} = this.props; let spinnerClasses = { 'spinner-layer': true }; if (only) { spinnerClasses['spinner-' + color + '-only'] = true; } else { spinnerClasses['spinner-' + color] = true; } return ( <div className={cx(spinnerClasses)}> <div className="circle-clipper left"> <div className="circle"></div> </div> <div className="gap-patch"> <div className="circle"></div> </div> <div className="circle-clipper right"> <div className="circle"></div> </div> </div> ); } Spinner.defaultProps = { only: true, }; let colors = ['blue', 'red', 'yellow', 'green']; class Preloader extends React.Component { render() { let classes = { 'preloader-wrapper': true, active: this.props.active }; if (this.props.size) { classes[this.props.size] = true; } let spinners; if (this.props.flashing) { spinners = []; colors.map(color => { spinners.push(<Spinner color={color} only={false} key={color}/>); }); } else { spinners = <Spinner color={this.props.color} />; } return ( <div className={cx(this.props.className, classes)}> {spinners} </div> ); } } Preloader.propTypes = { /** * The scale of the circle * @default 'medium' */ size: React.PropTypes.oneOf(['big', 'small', 'medium']), /** * Whether to spin * @default true */ active: React.PropTypes.bool, /** * The color of the circle, if not flashing * @default 'blue' */ color: React.PropTypes.oneOf(['blue', 'red', 'yellow', 'green']), /** * Wheter to circle four different colors * @default false */ flashing: React.PropTypes.bool, }; Preloader.defaultProps = { active: true, flashing: false, color: 'blue', }; export default Preloader;
v7/development/src/templates/archive/archive.js
BigBoss424/portfolio
/* Vendor imports */ import React from 'react' import PropTypes from 'prop-types' import { graphql } from 'gatsby' /* App imports */ import Layout from '../../components/layout' import SEO from '../../components/seo' import PostList from '../../components/post-list' import ArchivePagination from '../../components/archive-pagination' import Config from '../../../config' const Archive = ({ data, pageContext }) => { const { archivePage, lastArchivePage } = pageContext const prevPage = archivePage > 1 ? archivePage - 1 : null const nextPage = archivePage < lastArchivePage ? archivePage + 1 : null return ( <Layout title="Archive"> <SEO title={`Archive | Page ${archivePage}`} description="Old posts" path={Config.pages.archive} /> <PostList posts={data.allMarkdownRemark.edges} /> <ArchivePagination prevPage={prevPage} nextPage={nextPage} /> </Layout> ) } Archive.propTypes = { data: PropTypes.shape({ allMarkdownRemark: PropTypes.shape({ edges: PropTypes.arrayOf(PropTypes.object.isRequired).isRequired, }).isRequired, }).isRequired, pageContext: PropTypes.shape({ archivePage: PropTypes.number.isRequired, lastArchivePage: PropTypes.number.isRequired, }).isRequired, } export const query = graphql` query($postPaths: [String!]) { allMarkdownRemark( filter: { frontmatter: { path: { in: $postPaths } } fileAbsolutePath: { regex: "/index.md$/" } } sort: { fields: [frontmatter___date], order: DESC } ) { edges { node { frontmatter { path title tags date(formatString: "MMMM DD, YYYY") excerpt cover { childImageSharp { fluid(maxWidth: 600) { ...GatsbyImageSharpFluid_tracedSVG } } } } } } } } ` export default Archive
src/svg-icons/action/picture-in-picture-alt.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPictureInPictureAlt = (props) => ( <SvgIcon {...props}> <path d="M19 11h-8v6h8v-6zm4 8V4.98C23 3.88 22.1 3 21 3H3c-1.1 0-2 .88-2 1.98V19c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2zm-2 .02H3V4.97h18v14.05z"/> </SvgIcon> ); ActionPictureInPictureAlt = pure(ActionPictureInPictureAlt); ActionPictureInPictureAlt.displayName = 'ActionPictureInPictureAlt'; ActionPictureInPictureAlt.muiName = 'SvgIcon'; export default ActionPictureInPictureAlt;
ajax/libs/elfinder/2.1.18/js/i18n/elfinder.nl.js
kennynaoh/cdnjs
/** * Dutch translation * @author Barry vd. Heuvel <[email protected]> * @version 2015-12-01 */ if (elFinder && elFinder.prototype && typeof(elFinder.prototype.i18) == 'object') { elFinder.prototype.i18.nl = { translator : 'Barry vd. Heuvel &lt;[email protected]&gt;', language : 'Nederlands', direction : 'ltr', dateFormat : 'd-m-Y H:i', // Mar 13, 2012 05:27 PM fancyDateFormat : '$1 H:i', // will produce smth like: Today 12:25 PM messages : { /********************************** errors **********************************/ 'error' : 'Fout', 'errUnknown' : 'Onbekend fout.', 'errUnknownCmd' : 'Onbekend commando.', 'errJqui' : 'Ongeldige jQuery UI configuratie. Selectable, draggable en droppable componenten moeten aanwezig zijn.', 'errNode' : 'Voor elFinder moet een DOM Element gemaakt worden.', 'errURL' : 'Ongeldige elFinder configuratie! URL optie is niet ingesteld.', 'errAccess' : 'Toegang geweigerd.', 'errConnect' : 'Kan geen verbinding met de backend maken.', 'errAbort' : 'Verbinding afgebroken.', 'errTimeout' : 'Verbinding time-out.', 'errNotFound' : 'Backend niet gevonden.', 'errResponse' : 'Ongeldige reactie van de backend.', 'errConf' : 'Ongeldige backend configuratie.', 'errJSON' : 'PHP JSON module niet geïnstalleerd.', 'errNoVolumes' : 'Leesbaar volume is niet beschikbaar.', 'errCmdParams' : 'Ongeldige parameters voor commando "$1".', 'errDataNotJSON' : 'Data is niet JSON.', 'errDataEmpty' : 'Data is leeg.', 'errCmdReq' : 'Backend verzoek heeft een commando naam nodig.', 'errOpen' : 'Kan "$1" niet openen.', 'errNotFolder' : 'Object is geen map.', 'errNotFile' : 'Object is geen bestand.', 'errRead' : 'Kan "$1" niet lezen.', 'errWrite' : 'Kan niet schrijven in "$1".', 'errPerm' : 'Toegang geweigerd.', 'errLocked' : '"$1" is vergrendeld en kan niet hernoemd, verplaats of verwijderd worden.', 'errExists' : 'Bestand "$1" bestaat al.', 'errInvName' : 'Ongeldige bestandsnaam.', 'errFolderNotFound' : 'Map niet gevonden.', 'errFileNotFound' : 'Bestand niet gevonden.', 'errTrgFolderNotFound' : 'Doelmap"$1" niet gevonden.', 'errPopup' : 'De browser heeft voorkomen dat de pop-up is geopend. Pas de browser instellingen aan om de popup te kunnen openen.', 'errMkdir' : 'Kan map "$1" niet aanmaken.', 'errMkfile' : 'Kan bestand "$1" niet aanmaken.', 'errRename' : 'Kan "$1" niet hernoemen.', 'errCopyFrom' : 'Bestanden kopiëren van "$1" is niet toegestaan.', 'errCopyTo' : 'Bestanden kopiëren naar "$1" is niet toegestaan.', 'errMkOutLink' : 'Kan geen link maken buiten de hoofdmap.', // from v2.1 added 03.10.2015 'errUpload' : 'Upload fout.', // old name - errUploadCommon 'errUploadFile' : 'Kan "$1" niet uploaden.', // old name - errUpload 'errUploadNoFiles' : 'Geen bestanden gevonden om te uploaden.', 'errUploadTotalSize' : 'Data overschrijdt de maximale grootte.', // old name - errMaxSize 'errUploadFileSize' : 'Bestand overschrijdt de maximale grootte.', // old name - errFileMaxSize 'errUploadMime' : 'Bestandstype niet toegestaan.', 'errUploadTransfer' : '"$1" overdrachtsfout.', 'errUploadTemp' : 'Kan geen tijdelijk bestand voor de upload maken.', // from v2.1 added 26.09.2015 'errNotReplace' : 'Object "$1" bestaat al op deze locatie en kan niet vervangen worden door een ander type object.', // new 'errReplace' : 'Kan "$1" niet vervangen.', 'errSave' : 'Kan "$1" niet opslaan.', 'errCopy' : 'Kan "$1" niet kopiëren.', 'errMove' : 'Kan "$1" niet verplaatsen.', 'errCopyInItself' : 'Kan "$1" niet in zichzelf kopiëren.', 'errRm' : 'Kan "$1" niet verwijderen.', 'errRmSrc' : 'Kan bronbestanden niet verwijderen.', 'errExtract' : 'Kan de bestanden van "$1" niet uitpakken.', 'errArchive' : 'Kan het archief niet maken.', 'errArcType' : 'Archief type is niet ondersteund.', 'errNoArchive' : 'Bestand is geen archief of geen ondersteund archief type.', 'errCmdNoSupport' : 'Backend ondersteund dit commando niet.', 'errReplByChild' : 'De map "$1" kan niet vervangen worden door een item uit die map.', 'errArcSymlinks' : 'Om veiligheidsredenen kan een bestand met symlinks of bestanden met niet toegestane namen niet worden uitgepakt .', // edited 24.06.2012 'errArcMaxSize' : 'Archief overschrijdt de maximale bestandsgrootte.', 'errResize' : 'Kan het formaat van "$1" niet wijzigen.', 'errResizeDegree' : 'Ongeldig aantal graden om te draaien.', // added 7.3.2013 'errResizeRotate' : 'Afbeelding kan niet gedraaid worden.', // added 7.3.2013 'errResizeSize' : 'Ongeldig afbeelding formaat.', // added 7.3.2013 'errResizeNoChange' : 'Afbeelding formaat is niet veranderd.', // added 7.3.2013 'errUsupportType' : 'Bestandstype wordt niet ondersteund.', 'errNotUTF8Content' : 'Bestand "$1" is niet in UTF-8 and kan niet aangepast worden.', // added 9.11.2011 'errNetMount' : 'Kan "$1" niet mounten.', // added 17.04.2012 'errNetMountNoDriver' : 'Niet ondersteund protocol.', // added 17.04.2012 'errNetMountFailed' : 'Mount mislukt.', // added 17.04.2012 'errNetMountHostReq' : 'Host is verplicht.', // added 18.04.2012 'errSessionExpires' : 'Uw sessie is verlopen vanwege inactiviteit.', 'errCreatingTempDir' : 'Kan de tijdelijke map niet aanmaken: "$1" ', 'errFtpDownloadFile' : 'Kan het bestand niet downloaden vanaf FTP: "$1"', 'errFtpUploadFile' : 'Kan het bestand niet uploaden naar FTP: "$1"', 'errFtpMkdir' : 'Kan het externe map niet aanmaken op de FTP-server: "$1"', 'errArchiveExec' : 'Er is een fout opgetreden bij het archivering van de bestanden: "$1" ', 'errExtractExec' : 'Er is een fout opgetreden bij het uitpakken van de bestanden: "$1" ', 'errNetUnMount' : 'Kan niet unmounten', // from v2.1 added 30.04.2012 'errConvUTF8' : 'Kan niet converteren naar UTF-8', // from v2.1 added 08.04.2014 'errFolderUpload' : 'Probeer Google Chrome, als je de map wil uploaden.', // from v2.1 added 26.6.2015 /******************************* commands names ********************************/ 'cmdarchive' : 'Maak archief', 'cmdback' : 'Vorige', 'cmdcopy' : 'Kopieer', 'cmdcut' : 'Knip', 'cmddownload' : 'Download', 'cmdduplicate' : 'Dupliceer', 'cmdedit' : 'Pas bestand aan', 'cmdextract' : 'Bestanden uit archief uitpakken', 'cmdforward' : 'Volgende', 'cmdgetfile' : 'Kies bestanden', 'cmdhelp' : 'Over deze software', 'cmdhome' : 'Home', 'cmdinfo' : 'Bekijk info', 'cmdmkdir' : 'Nieuwe map', 'cmdmkfile' : 'Nieuw tekstbestand', 'cmdopen' : 'Open', 'cmdpaste' : 'Plak', 'cmdquicklook' : 'Voorbeeld', 'cmdreload' : 'Vernieuwen', 'cmdrename' : 'Naam wijzigen', 'cmdrm' : 'Verwijder', 'cmdsearch' : 'Zoek bestanden', 'cmdup' : 'Ga een map hoger', 'cmdupload' : 'Upload bestanden', 'cmdview' : 'Bekijk', 'cmdresize' : 'Formaat wijzigen', 'cmdsort' : 'Sorteren', 'cmdnetmount' : 'Mount netwerk volume', // added 18.04.2012 'cmdnetunmount': 'Unmount', // from v2.1 added 30.04.2012 'cmdplaces' : 'Naar Plaatsen', // added 28.12.2014 'cmdchmod' : 'Wijzig modus', // from v2.1 added 20.6.2015 /*********************************** buttons ***********************************/ 'btnClose' : 'Sluit', 'btnSave' : 'Opslaan', 'btnRm' : 'Verwijder', 'btnApply' : 'Toepassen', 'btnCancel' : 'Annuleren', 'btnNo' : 'Nee', 'btnYes' : 'Ja', 'btnMount' : 'Mount', // added 18.04.2012 'btnApprove': 'Ga naar $1 & keur goed', // from v2.1 added 26.04.2012 'btnUnmount': 'Unmount', // from v2.1 added 30.04.2012 'btnConv' : 'Converteer', // from v2.1 added 08.04.2014 'btnCwd' : 'Hier', // from v2.1 added 22.5.2015 'btnVolume' : 'Volume', // from v2.1 added 22.5.2015 'btnAll' : 'Alles', // from v2.1 added 22.5.2015 'btnMime' : 'MIME Type', // from v2.1 added 22.5.2015 'btnFileName':'Bestandsnaam', // from v2.1 added 22.5.2015 'btnSaveClose': 'Opslaan & Sluiten', // from v2.1 added 12.6.2015 'btnBackup' : 'Back-up', // fromv2.1 added 28.11.2015 /******************************** notifications ********************************/ 'ntfopen' : 'Bezig met openen van map', 'ntffile' : 'Bezig met openen bestand', 'ntfreload' : 'Herladen map inhoud', 'ntfmkdir' : 'Bezig met map maken', 'ntfmkfile' : 'Bezig met Bestanden maken', 'ntfrm' : 'Verwijderen bestanden', 'ntfcopy' : 'Kopieer bestanden', 'ntfmove' : 'Verplaats bestanden', 'ntfprepare' : 'Voorbereiden kopiëren', 'ntfrename' : 'Hernoem bestanden', 'ntfupload' : 'Bestanden uploaden actief', 'ntfdownload' : 'Bestanden downloaden actief', 'ntfsave' : 'Bestanden opslaan', 'ntfarchive' : 'Archief aan het maken', 'ntfextract' : 'Bestanden uitpakken actief', 'ntfsearch' : 'Zoeken naar bestanden', 'ntfresize' : 'Formaat wijzigen van afbeeldingen', 'ntfsmth' : 'Iets aan het doen', 'ntfloadimg' : 'Laden van plaatje', 'ntfnetmount' : 'Mounten van netwerk volume', // added 18.04.2012 'ntfnetunmount': 'Unmounten van netwerk volume', // from v2.1 added 30.04.2012 'ntfdim' : 'Opvragen afbeeldingen dimensies', // added 20.05.2013 'ntfreaddir' : 'Map informatie lezen', // from v2.1 added 01.07.2013 'ntfurl' : 'URL van link ophalen', // from v2.1 added 11.03.2014 'ntfchmod' : 'Bestandsmodus wijzigen', // from v2.1 added 20.6.2015 'ntfpreupload': 'Upload bestandsnaam verifiëren', // from v2.1 added 31.11.2015 /************************************ dates **********************************/ 'dateUnknown' : 'onbekend', 'Today' : 'Vandaag', 'Yesterday' : 'Gisteren', 'msJan' : 'Jan', 'msFeb' : 'Feb', 'msMar' : 'Mar', 'msApr' : 'Apr', 'msMay' : 'Mei', 'msJun' : 'Jun', 'msJul' : 'Jul', 'msAug' : 'Aug', 'msSep' : 'Sep', 'msOct' : 'Okt', 'msNov' : 'Nov', 'msDec' : 'Dec', 'January' : 'Januari', 'February' : 'Februari', 'March' : 'Maart', 'April' : 'April', 'May' : 'Mei', 'June' : 'Juni', 'July' : 'Juli', 'August' : 'Augustus', 'September' : 'September', 'October' : 'Oktober', 'November' : 'November', 'December' : 'December', 'Sunday' : 'Zondag', 'Monday' : 'Maandag', 'Tuesday' : 'Dinsdag', 'Wednesday' : 'Woensdag', 'Thursday' : 'Donderdag', 'Friday' : 'Vrijdag', 'Saturday' : 'Zaterdag', 'Sun' : 'Zo', 'Mon' : 'Ma', 'Tue' : 'Di', 'Wed' : 'Wo', 'Thu' : 'Do', 'Fri' : 'Vr', 'Sat' : 'Za', /******************************** sort variants ********************************/ 'sortname' : 'op naam', 'sortkind' : 'op type', 'sortsize' : 'op grootte', 'sortdate' : 'op datum', 'sortFoldersFirst' : 'Mappen eerst', /********************************** new items **********************************/ 'untitled file.txt' : 'NieuwBestand.txt', // added 10.11.2015 'untitled folder' : 'NieuweMap', // added 10.11.2015 'Archive' : 'NieuwArchief', // from v2.1 added 10.11.2015 /********************************** messages **********************************/ 'confirmReq' : 'Bevestiging nodig', 'confirmRm' : 'Weet u zeker dat u deze bestanden wil verwijderen?<br/>Deze actie kan niet ongedaan gemaakt worden!', 'confirmRepl' : 'Oud bestand vervangen door het nieuwe bestand?', 'confirmConvUTF8' : 'Niet in UTF-8<br/>Converteren naar UTF-8?<br/>De inhoud wordt UTF-8 door op te slaan na de conversie.', // from v2.1 added 08.04.2014 'confirmNotSave' : 'Het is aangepast.<br/>Wijzigingen gaan verloren als je niet opslaat.', // from v2.1 added 15.7.2015 'apllyAll' : 'Toepassen op alles', 'name' : 'Naam', 'size' : 'Grootte', 'perms' : 'Rechten', 'modify' : 'Aangepast', 'kind' : 'Type', 'read' : 'lees', 'write' : 'schrijf', 'noaccess' : 'geen toegang', 'and' : 'en', 'unknown' : 'onbekend', 'selectall' : 'Selecteer alle bestanden', 'selectfiles' : 'Selecteer bestand(en)', 'selectffile' : 'Selecteer eerste bestand', 'selectlfile' : 'Selecteer laatste bestand', 'viewlist' : 'Lijst weergave', 'viewicons' : 'Icoon weergave', 'places' : 'Plaatsen', 'calc' : 'Bereken', 'path' : 'Pad', 'aliasfor' : 'Alias voor', 'locked' : 'Vergrendeld', 'dim' : 'Dimensies', 'files' : 'Bestanden', 'folders' : 'Mappen', 'items' : 'Items', 'yes' : 'ja', 'no' : 'nee', 'link' : 'Link', 'searcresult' : 'Zoek resultaten', 'selected' : 'geselecteerde items', 'about' : 'Over', 'shortcuts' : 'Snelkoppelingen', 'help' : 'Help', 'webfm' : 'Web bestandsmanager', 'ver' : 'Versie', 'protocolver' : 'protocol versie', 'homepage' : 'Project home', 'docs' : 'Documentatie', 'github' : 'Fork ons op Github', 'twitter' : 'Volg ons op twitter', 'facebook' : 'Wordt lid op facebook', 'team' : 'Team', 'chiefdev' : 'Hoofd ontwikkelaar', 'developer' : 'ontwikkelaar', 'contributor' : 'bijdrager', 'maintainer' : 'onderhouder', 'translator' : 'vertaler', 'icons' : 'Iconen', 'dontforget' : 'En vergeet je handdoek niet!', 'shortcutsof' : 'Snelkoppelingen uitgeschakeld', 'dropFiles' : 'Sleep hier uw bestanden heen', 'or' : 'of', 'selectForUpload' : 'Selecteer bestanden om te uploaden', 'moveFiles' : 'Verplaats bestanden', 'copyFiles' : 'Kopieer bestanden', 'rmFromPlaces' : 'Verwijder uit Plaatsen', 'aspectRatio' : 'Aspect ratio', 'scale' : 'Schaal', 'width' : 'Breedte', 'height' : 'Hoogte', 'resize' : 'Verkleinen', 'crop' : 'Bijsnijden', 'rotate' : 'Draaien', 'rotate-cw' : 'Draai 90 graden rechtsom', 'rotate-ccw' : 'Draai 90 graden linksom', 'degree' : '°', 'netMountDialogTitle' : 'Mount netwerk volume', // added 18.04.2012 'protocol' : 'Protocol', // added 18.04.2012 'host' : 'Host', // added 18.04.2012 'port' : 'Poort', // added 18.04.2012 'user' : 'Gebruikersnaams', // added 18.04.2012 'pass' : 'Wachtwoord', // added 18.04.2012 'confirmUnmount' : 'Weet u zeker dat u $1 wil unmounten?', // from v2.1 added 30.04.2012 'dropFilesBrowser': 'Sleep of plak bestanden vanuit de browser', // from v2.1 added 30.05.2012 'dropPasteFiles' : 'Sleep of plak bestanden hier', // from v2.1 added 07.04.2014 'encoding' : 'Encodering', // from v2.1 added 19.12.2014 'locale' : 'Locale', // from v2.1 added 19.12.2014 'searchTarget' : 'Doel: $1', // from v2.1 added 22.5.2015 'searchMime' : 'Zoek op invoer MIME Type', // from v2.1 added 22.5.2015 'owner' : 'Eigenaar', // from v2.1 added 20.6.2015 'group' : 'Groep', // from v2.1 added 20.6.2015 'other' : 'Overig', // from v2.1 added 20.6.2015 'execute' : 'Uitvoeren', // from v2.1 added 20.6.2015 'perm' : 'Rechten', // from v2.1 added 20.6.2015 'mode' : 'Modus', // from v2.1 added 20.6.2015 /********************************** mimetypes **********************************/ 'kindUnknown' : 'Onbekend', 'kindFolder' : 'Map', 'kindAlias' : 'Alias', 'kindAliasBroken' : 'Kapot alias', // applications 'kindApp' : 'Applicatie', 'kindPostscript' : 'Postscript document', 'kindMsOffice' : 'Microsoft Office document', 'kindMsWord' : 'Microsoft Word document', 'kindMsExcel' : 'Microsoft Excel document', 'kindMsPP' : 'Microsoft Powerpoint presentation', 'kindOO' : 'Open Office document', 'kindAppFlash' : 'Flash applicatie', 'kindPDF' : 'Portable Document Format (PDF)', 'kindTorrent' : 'Bittorrent bestand', 'kind7z' : '7z archief', 'kindTAR' : 'TAR archief', 'kindGZIP' : 'GZIP archief', 'kindBZIP' : 'BZIP archief', 'kindXZ' : 'XZ archief', 'kindZIP' : 'ZIP archief', 'kindRAR' : 'RAR archief', 'kindJAR' : 'Java JAR bestand', 'kindTTF' : 'True Type font', 'kindOTF' : 'Open Type font', 'kindRPM' : 'RPM package', // texts 'kindText' : 'Tekst bestand', 'kindTextPlain' : 'Tekst', 'kindPHP' : 'PHP bronbestand', 'kindCSS' : 'Cascading style sheet', 'kindHTML' : 'HTML document', 'kindJS' : 'Javascript bronbestand', 'kindRTF' : 'Rich Text Format', 'kindC' : 'C bronbestand', 'kindCHeader' : 'C header bronbestand', 'kindCPP' : 'C++ bronbestand', 'kindCPPHeader' : 'C++ header bronbestand', 'kindShell' : 'Unix shell script', 'kindPython' : 'Python bronbestand', 'kindJava' : 'Java bronbestand', 'kindRuby' : 'Ruby bronbestand', 'kindPerl' : 'Perl bronbestand', 'kindSQL' : 'SQL bronbestand', 'kindXML' : 'XML document', 'kindAWK' : 'AWK bronbestand', 'kindCSV' : 'Komma gescheiden waardes', 'kindDOCBOOK' : 'Docbook XML document', 'kindMarkdown' : 'Markdown tekst', // added 20.7.2015 // images 'kindImage' : 'Afbeelding', 'kindBMP' : 'BMP afbeelding', 'kindJPEG' : 'JPEG afbeelding', 'kindGIF' : 'GIF afbeelding', 'kindPNG' : 'PNG afbeelding', 'kindTIFF' : 'TIFF afbeelding', 'kindTGA' : 'TGA afbeelding', 'kindPSD' : 'Adobe Photoshop afbeelding', 'kindXBITMAP' : 'X bitmap afbeelding', 'kindPXM' : 'Pixelmator afbeelding', // media 'kindAudio' : 'Audio media', 'kindAudioMPEG' : 'MPEG audio', 'kindAudioMPEG4' : 'MPEG-4 audio', 'kindAudioMIDI' : 'MIDI audio', 'kindAudioOGG' : 'Ogg Vorbis audio', 'kindAudioWAV' : 'WAV audio', 'AudioPlaylist' : 'MP3 playlist', 'kindVideo' : 'Video media', 'kindVideoDV' : 'DV video', 'kindVideoMPEG' : 'MPEG video', 'kindVideoMPEG4' : 'MPEG-4 video', 'kindVideoAVI' : 'AVI video', 'kindVideoMOV' : 'Quick Time video', 'kindVideoWM' : 'Windows Media video', 'kindVideoFlash' : 'Flash video', 'kindVideoMKV' : 'Matroska video', 'kindVideoOGG' : 'Ogg video' } }; }
ajax/libs/react-virtualized/7.11.3/react-virtualized.js
Piicksarn/cdnjs
!function(root, factory) { "object" == typeof exports && "object" == typeof module ? module.exports = factory(require("React"), require("React.addons.shallowCompare"), require("ReactDOM")) : "function" == typeof define && define.amd ? define([ "React", "React.addons.shallowCompare", "ReactDOM" ], factory) : "object" == typeof exports ? exports.ReactVirtualized = factory(require("React"), require("React.addons.shallowCompare"), require("ReactDOM")) : root.ReactVirtualized = factory(root.React, root["React.addons.shallowCompare"], root.ReactDOM); }(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_10__) { /******/ return function(modules) { /******/ /******/ // 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: !1 }; /******/ /******/ // Return the exports of the module /******/ /******/ /******/ // Execute the module function /******/ /******/ /******/ // Flag the module as loaded /******/ return modules[moduleId].call(module.exports, module, module.exports, __webpack_require__), module.loaded = !0, module.exports; } // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // Load entry module and return exports /******/ /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ /******/ /******/ // expose the module cache /******/ /******/ /******/ // __webpack_public_path__ /******/ return __webpack_require__.m = modules, __webpack_require__.c = installedModules, __webpack_require__.p = "", __webpack_require__(0); }([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var _ArrowKeyStepper = __webpack_require__(1); Object.defineProperty(exports, "ArrowKeyStepper", { enumerable: !0, get: function() { return _ArrowKeyStepper.ArrowKeyStepper; } }); var _AutoSizer = __webpack_require__(5); Object.defineProperty(exports, "AutoSizer", { enumerable: !0, get: function() { return _AutoSizer.AutoSizer; } }); var _CellMeasurer = __webpack_require__(8); Object.defineProperty(exports, "CellMeasurer", { enumerable: !0, get: function() { return _CellMeasurer.CellMeasurer; } }); var _Collection = __webpack_require__(169); Object.defineProperty(exports, "Collection", { enumerable: !0, get: function() { return _Collection.Collection; } }); var _ColumnSizer = __webpack_require__(182); Object.defineProperty(exports, "ColumnSizer", { enumerable: !0, get: function() { return _ColumnSizer.ColumnSizer; } }); var _FlexTable = __webpack_require__(192); Object.defineProperty(exports, "FlexTable", { enumerable: !0, get: function() { return _FlexTable.FlexTable; } }), Object.defineProperty(exports, "FlexColumn", { enumerable: !0, get: function() { return _FlexTable.FlexColumn; } }), Object.defineProperty(exports, "SortDirection", { enumerable: !0, get: function() { return _FlexTable.SortDirection; } }), Object.defineProperty(exports, "SortIndicator", { enumerable: !0, get: function() { return _FlexTable.SortIndicator; } }); var _Grid = __webpack_require__(184); Object.defineProperty(exports, "defaultCellRangeRenderer", { enumerable: !0, get: function() { return _Grid.defaultCellRangeRenderer; } }), Object.defineProperty(exports, "Grid", { enumerable: !0, get: function() { return _Grid.Grid; } }); var _InfiniteLoader = __webpack_require__(200); Object.defineProperty(exports, "InfiniteLoader", { enumerable: !0, get: function() { return _InfiniteLoader.InfiniteLoader; } }); var _ScrollSync = __webpack_require__(202); Object.defineProperty(exports, "ScrollSync", { enumerable: !0, get: function() { return _ScrollSync.ScrollSync; } }); var _VirtualScroll = __webpack_require__(204); Object.defineProperty(exports, "VirtualScroll", { enumerable: !0, get: function() { return _VirtualScroll.VirtualScroll; } }); var _WindowScroller = __webpack_require__(206); Object.defineProperty(exports, "WindowScroller", { enumerable: !0, get: function() { return _WindowScroller.WindowScroller; } }); }, /* 1 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ArrowKeyStepper = exports["default"] = void 0; var _ArrowKeyStepper2 = __webpack_require__(2), _ArrowKeyStepper3 = _interopRequireDefault(_ArrowKeyStepper2); exports["default"] = _ArrowKeyStepper3["default"], exports.ArrowKeyStepper = _ArrowKeyStepper3["default"]; }, /* 2 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ArrowKeyStepper = function(_Component) { function ArrowKeyStepper(props, context) { _classCallCheck(this, ArrowKeyStepper); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ArrowKeyStepper).call(this, props, context)); return _this.state = { scrollToColumn: 0, scrollToRow: 0 }, _this._columnStartIndex = 0, _this._columnStopIndex = 0, _this._rowStartIndex = 0, _this._rowStopIndex = 0, _this._onKeyDown = _this._onKeyDown.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this), _this; } return _inherits(ArrowKeyStepper, _Component), _createClass(ArrowKeyStepper, [ { key: "render", value: function() { var _props = this.props, className = _props.className, children = _props.children, _state = this.state, scrollToColumn = _state.scrollToColumn, scrollToRow = _state.scrollToRow; return _react2["default"].createElement("div", { className: className, onKeyDown: this._onKeyDown }, children({ onSectionRendered: this._onSectionRendered, scrollToColumn: scrollToColumn, scrollToRow: scrollToRow })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onKeyDown", value: function(event) { var _props2 = this.props, columnCount = _props2.columnCount, rowCount = _props2.rowCount; switch (event.key) { case "ArrowDown": event.preventDefault(), this.setState({ scrollToRow: Math.min(this._rowStopIndex + 1, rowCount - 1) }); break; case "ArrowLeft": event.preventDefault(), this.setState({ scrollToColumn: Math.max(this._columnStartIndex - 1, 0) }); break; case "ArrowRight": event.preventDefault(), this.setState({ scrollToColumn: Math.min(this._columnStopIndex + 1, columnCount - 1) }); break; case "ArrowUp": event.preventDefault(), this.setState({ scrollToRow: Math.max(this._rowStartIndex - 1, 0) }); } } }, { key: "_onSectionRendered", value: function(_ref) { var columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex; this._columnStartIndex = columnStartIndex, this._columnStopIndex = columnStopIndex, this._rowStartIndex = rowStartIndex, this._rowStopIndex = rowStopIndex; } } ]), ArrowKeyStepper; }(_react.Component); ArrowKeyStepper.propTypes = { children: _react.PropTypes.func.isRequired, className: _react.PropTypes.string, columnCount: _react.PropTypes.number.isRequired, rowCount: _react.PropTypes.number.isRequired }, exports["default"] = ArrowKeyStepper; }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; }, /* 4 */ /***/ function(module, exports) { module.exports = React.addons.shallowCompare; }, /* 5 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.AutoSizer = exports["default"] = void 0; var _AutoSizer2 = __webpack_require__(6), _AutoSizer3 = _interopRequireDefault(_AutoSizer2); exports["default"] = _AutoSizer3["default"], exports.AutoSizer = _AutoSizer3["default"]; }, /* 6 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), AutoSizer = function(_Component) { function AutoSizer(props) { _classCallCheck(this, AutoSizer); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(AutoSizer).call(this, props)); return _this.state = { height: 0, width: 0 }, _this._onResize = _this._onResize.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._setRef = _this._setRef.bind(_this), _this; } return _inherits(AutoSizer, _Component), _createClass(AutoSizer, [ { key: "componentDidMount", value: function() { this._detectElementResize = __webpack_require__(7), this._detectElementResize.addResizeListener(this._parentNode, this._onResize), this._onResize(); } }, { key: "componentWillUnmount", value: function() { this._detectElementResize && this._detectElementResize.removeResizeListener(this._parentNode, this._onResize); } }, { key: "render", value: function() { var _props = this.props, children = _props.children, disableHeight = _props.disableHeight, disableWidth = _props.disableWidth, _state = this.state, height = _state.height, width = _state.width, outerStyle = { overflow: "visible" }; return disableHeight || (outerStyle.height = 0), disableWidth || (outerStyle.width = 0), _react2["default"].createElement("div", { ref: this._setRef, onScroll: this._onScroll, style: outerStyle }, children({ height: height, width: width })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onResize", value: function() { var onResize = this.props.onResize, boundingRect = this._parentNode.getBoundingClientRect(), height = boundingRect.height || 0, width = boundingRect.width || 0, style = getComputedStyle(this._parentNode), paddingLeft = parseInt(style.paddingLeft, 10) || 0, paddingRight = parseInt(style.paddingRight, 10) || 0, paddingTop = parseInt(style.paddingTop, 10) || 0, paddingBottom = parseInt(style.paddingBottom, 10) || 0; this.setState({ height: height - paddingTop - paddingBottom, width: width - paddingLeft - paddingRight }), onResize({ height: height, width: width }); } }, { key: "_onScroll", value: function(event) { event.stopPropagation(); } }, { key: "_setRef", value: function(autoSizer) { this._parentNode = autoSizer && autoSizer.parentNode; } } ]), AutoSizer; }(_react.Component); AutoSizer.propTypes = { children: _react.PropTypes.func.isRequired, disableHeight: _react.PropTypes.bool, disableWidth: _react.PropTypes.bool, onResize: _react.PropTypes.func.isRequired }, AutoSizer.defaultProps = { onResize: function() {} }, exports["default"] = AutoSizer; }, /* 7 */ /***/ function(module, exports) { "use strict"; var _window; _window = "undefined" != typeof window ? window : "undefined" != typeof self ? self : void 0; var attachEvent = "undefined" != typeof document && document.attachEvent, stylesCreated = !1; if (!attachEvent) { var requestFrame = function() { var raf = _window.requestAnimationFrame || _window.mozRequestAnimationFrame || _window.webkitRequestAnimationFrame || function(fn) { return _window.setTimeout(fn, 20); }; return function(fn) { return raf(fn); }; }(), cancelFrame = function() { var cancel = _window.cancelAnimationFrame || _window.mozCancelAnimationFrame || _window.webkitCancelAnimationFrame || _window.clearTimeout; return function(id) { return cancel(id); }; }(), resetTriggers = function(element) { var triggers = element.__resizeTriggers__, expand = triggers.firstElementChild, contract = triggers.lastElementChild, expandChild = expand.firstElementChild; contract.scrollLeft = contract.scrollWidth, contract.scrollTop = contract.scrollHeight, expandChild.style.width = expand.offsetWidth + 1 + "px", expandChild.style.height = expand.offsetHeight + 1 + "px", expand.scrollLeft = expand.scrollWidth, expand.scrollTop = expand.scrollHeight; }, checkTriggers = function(element) { return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height; }, scrollListener = function(e) { var element = this; resetTriggers(this), this.__resizeRAF__ && cancelFrame(this.__resizeRAF__), this.__resizeRAF__ = requestFrame(function() { checkTriggers(element) && (element.__resizeLast__.width = element.offsetWidth, element.__resizeLast__.height = element.offsetHeight, element.__resizeListeners__.forEach(function(fn) { fn.call(element, e); })); }); }, animation = !1, animationstring = "animation", keyframeprefix = "", animationstartevent = "animationstart", domPrefixes = "Webkit Moz O ms".split(" "), startEvents = "webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "), pfx = "", elm = document.createElement("fakeelement"); if (void 0 !== elm.style.animationName && (animation = !0), animation === !1) for (var i = 0; i < domPrefixes.length; i++) if (void 0 !== elm.style[domPrefixes[i] + "AnimationName"]) { pfx = domPrefixes[i], animationstring = pfx + "Animation", keyframeprefix = "-" + pfx.toLowerCase() + "-", animationstartevent = startEvents[i], animation = !0; break; } var animationName = "resizeanim", animationKeyframes = "@" + keyframeprefix + "keyframes " + animationName + " { from { opacity: 0; } to { opacity: 0; } } ", animationStyle = keyframeprefix + "animation: 1ms " + animationName + "; "; } var createStyles = function() { if (!stylesCreated) { var css = (animationKeyframes ? animationKeyframes : "") + ".resize-triggers { " + (animationStyle ? animationStyle : "") + 'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }', head = document.head || document.getElementsByTagName("head")[0], style = document.createElement("style"); style.type = "text/css", style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)), head.appendChild(style), stylesCreated = !0; } }, addResizeListener = function(element, fn) { attachEvent ? element.attachEvent("onresize", fn) : (element.__resizeTriggers__ || ("static" == getComputedStyle(element).position && (element.style.position = "relative"), createStyles(), element.__resizeLast__ = {}, element.__resizeListeners__ = [], (element.__resizeTriggers__ = document.createElement("div")).className = "resize-triggers", element.__resizeTriggers__.innerHTML = '<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>', element.appendChild(element.__resizeTriggers__), resetTriggers(element), element.addEventListener("scroll", scrollListener, !0), animationstartevent && element.__resizeTriggers__.addEventListener(animationstartevent, function(e) { e.animationName == animationName && resetTriggers(element); })), element.__resizeListeners__.push(fn)); }, removeResizeListener = function(element, fn) { attachEvent ? element.detachEvent("onresize", fn) : (element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1), element.__resizeListeners__.length || (element.removeEventListener("scroll", scrollListener, !0), element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__))); }; module.exports = { addResizeListener: addResizeListener, removeResizeListener: removeResizeListener }; }, /* 8 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.CellMeasurer = exports["default"] = void 0; var _CellMeasurer2 = __webpack_require__(9), _CellMeasurer3 = _interopRequireDefault(_CellMeasurer2); exports["default"] = _CellMeasurer3["default"], exports.CellMeasurer = _CellMeasurer3["default"]; }, /* 9 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(10), _reactDom2 = _interopRequireDefault(_reactDom), _server = __webpack_require__(11), _server2 = _interopRequireDefault(_server), CellMeasurer = function(_Component) { function CellMeasurer(props, state) { _classCallCheck(this, CellMeasurer); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(CellMeasurer).call(this, props, state)); return _this._cachedColumnWidths = {}, _this._cachedRowHeights = {}, _this.getColumnWidth = _this.getColumnWidth.bind(_this), _this.getRowHeight = _this.getRowHeight.bind(_this), _this.resetMeasurements = _this.resetMeasurements.bind(_this), _this; } return _inherits(CellMeasurer, _Component), _createClass(CellMeasurer, [ { key: "getColumnWidth", value: function(_ref) { var index = _ref.index; if (this._cachedColumnWidths[index]) return this._cachedColumnWidths[index]; for (var rowCount = this.props.rowCount, maxWidth = 0, rowIndex = 0; rowCount > rowIndex; rowIndex++) { var _measureCell2 = this._measureCell({ clientWidth: !0, columnIndex: index, rowIndex: rowIndex }), width = _measureCell2.width; maxWidth = Math.max(maxWidth, width); } return this._cachedColumnWidths[index] = maxWidth, maxWidth; } }, { key: "getRowHeight", value: function(_ref2) { var index = _ref2.index; if (this._cachedRowHeights[index]) return this._cachedRowHeights[index]; for (var columnCount = this.props.columnCount, maxHeight = 0, columnIndex = 0; columnCount > columnIndex; columnIndex++) { var _measureCell3 = this._measureCell({ clientHeight: !0, columnIndex: columnIndex, rowIndex: index }), height = _measureCell3.height; maxHeight = Math.max(maxHeight, height); } return this._cachedRowHeights[index] = maxHeight, maxHeight; } }, { key: "resetMeasurements", value: function() { this._cachedColumnWidths = {}, this._cachedRowHeights = {}; } }, { key: "componentDidMount", value: function() { this._renderAndMount(); } }, { key: "componentWillReceiveProps", value: function(nextProps) { this._updateDivDimensions(nextProps); } }, { key: "componentWillUnmount", value: function() { this._unmountContainer(); } }, { key: "render", value: function() { var children = this.props.children; return children({ getColumnWidth: this.getColumnWidth, getRowHeight: this.getRowHeight, resetMeasurements: this.resetMeasurements }); } }, { key: "_getContainerNode", value: function(props) { var container = props.container; return container ? _reactDom2["default"].findDOMNode("function" == typeof container ? container() : container) : document.body; } }, { key: "_measureCell", value: function(_ref3) { var _ref3$clientHeight = _ref3.clientHeight, clientHeight = void 0 === _ref3$clientHeight ? !1 : _ref3$clientHeight, _ref3$clientWidth = _ref3.clientWidth, clientWidth = void 0 === _ref3$clientWidth ? !0 : _ref3$clientWidth, columnIndex = _ref3.columnIndex, rowIndex = _ref3.rowIndex, cellRenderer = this.props.cellRenderer, rendered = cellRenderer({ columnIndex: columnIndex, rowIndex: rowIndex }); return this._renderAndMount(), this._div.innerHTML = _server2["default"].renderToString(rendered), { height: clientHeight && this._div.clientHeight, width: clientWidth && this._div.clientWidth }; } }, { key: "_renderAndMount", value: function() { this._div || (this._div = document.createElement("div"), this._div.style.display = "inline-block", this._div.style.position = "absolute", this._div.style.visibility = "hidden", this._div.style.zIndex = -1, this._updateDivDimensions(this.props), this._containerNode = this._getContainerNode(this.props), this._containerNode.appendChild(this._div)); } }, { key: "_unmountContainer", value: function() { this._div && (this._containerNode.removeChild(this._div), this._div = null), this._containerNode = null; } }, { key: "_updateDivDimensions", value: function(props) { var height = props.height, width = props.width; height && height !== this._divHeight && (this._divHeight = height, this._div.style.height = height + "px"), width && width !== this._divWidth && (this._divWidth = width, this._div.style.width = width + "px"); } } ]), CellMeasurer; }(_react.Component); CellMeasurer.propTypes = { cellRenderer: _react.PropTypes.func.isRequired, children: _react.PropTypes.func.isRequired, columnCount: _react.PropTypes.number.isRequired, container: _react2["default"].PropTypes.oneOfType([ _react2["default"].PropTypes.func, _react2["default"].PropTypes.node ]), height: _react.PropTypes.number, rowCount: _react.PropTypes.number.isRequired, width: _react.PropTypes.number }, exports["default"] = CellMeasurer; }, /* 10 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_10__; }, /* 11 */ /***/ function(module, exports, __webpack_require__) { "use strict"; module.exports = __webpack_require__(12); }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMServer */ "use strict"; var ReactDefaultInjection = __webpack_require__(13), ReactServerRendering = __webpack_require__(163), ReactVersion = __webpack_require__(168); ReactDefaultInjection.inject(); var ReactDOMServer = { renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, version: ReactVersion }; module.exports = ReactDOMServer; }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ "use strict"; function inject() { alreadyInjected || (alreadyInjected = !0, ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener), ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder), ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree), ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal), ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }), ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent), ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent), ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig), ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig), ReactInjection.EmptyComponent.injectEmptyComponentFactory(function(instantiate) { return new ReactDOMEmptyComponent(instantiate); }), ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction), ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy), ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment)); } var BeforeInputEventPlugin = __webpack_require__(14), ChangeEventPlugin = __webpack_require__(37), DefaultEventPluginOrder = __webpack_require__(58), EnterLeaveEventPlugin = __webpack_require__(59), HTMLDOMPropertyConfig = __webpack_require__(64), ReactComponentBrowserEnvironment = __webpack_require__(65), ReactDOMComponent = __webpack_require__(79), ReactDOMComponentTree = __webpack_require__(38), ReactDOMEmptyComponent = __webpack_require__(131), ReactDOMTreeTraversal = __webpack_require__(132), ReactDOMTextComponent = __webpack_require__(133), ReactDefaultBatchingStrategy = __webpack_require__(134), ReactEventListener = __webpack_require__(135), ReactInjection = __webpack_require__(138), ReactReconcileTransaction = __webpack_require__(142), SVGDOMPropertyConfig = __webpack_require__(150), SelectEventPlugin = __webpack_require__(151), SimpleEventPlugin = __webpack_require__(152), alreadyInjected = !1; module.exports = { inject: inject }; }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin */ "use strict"; /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return "object" == typeof opera && "function" == typeof opera.version && parseInt(opera.version(), 10) <= 12; } /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { // ctrlKey && altKey is equivalent to AltGr, and is not a command. return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return -1 !== END_KEYCODES.indexOf(nativeEvent.keyCode); case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return !0; default: return !1; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; return "object" == typeof detail && "data" in detail ? detail.data : null; } /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType, fallbackData; if (canUseCompositionEvent ? eventType = getCompositionEventType(topLevelType) : currentComposition ? isFallbackCompositionEnd(topLevelType, nativeEvent) && (eventType = eventTypes.compositionEnd) : isFallbackCompositionStart(topLevelType, nativeEvent) && (eventType = eventTypes.compositionStart), !eventType) return null; useFallbackCompositionData && (// The current composition is stored statically and must not be // overwritten while composition continues. currentComposition || eventType !== eventTypes.compositionStart ? eventType === eventTypes.compositionEnd && currentComposition && (fallbackData = currentComposition.getData()) : currentComposition = FallbackCompositionState.getPooled(nativeEventTarget)); var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; else { var customData = getDataFromCustomEvent(nativeEvent); null !== customData && (event.data = customData); } return EventPropagators.accumulateTwoPhaseDispatches(event), event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; return which !== SPACEBAR_CODE ? null : (hasSpaceKeypress = !0, SPACEBAR_CHAR); case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. return chars === SPACEBAR_CHAR && hasSpaceKeypress ? null : chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); return FallbackCompositionState.release(currentComposition), currentComposition = null, chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ return nativeEvent.which && !isKeypressCommand(nativeEvent) ? String.fromCharCode(nativeEvent.which) : null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; // If no characters are being inserted, no BeforeInput event should // be fired. if (chars = canUseTextInputEvent ? getNativeBeforeInputChars(topLevelType, nativeEvent) : getFallbackBeforeInputChars(topLevelType, nativeEvent), !chars) return null; var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); return event.data = chars, EventPropagators.accumulateTwoPhaseDispatches(event), event; } var EventConstants = __webpack_require__(15), EventPropagators = __webpack_require__(19), ExecutionEnvironment = __webpack_require__(28), FallbackCompositionState = __webpack_require__(29), SyntheticCompositionEvent = __webpack_require__(33), SyntheticInputEvent = __webpack_require__(35), keyOf = __webpack_require__(36), END_KEYCODES = [ 9, 13, 27, 32 ], START_KEYCODE = 229, canUseCompositionEvent = ExecutionEnvironment.canUseDOM && "CompositionEvent" in window, documentMode = null; ExecutionEnvironment.canUseDOM && "documentMode" in document && (documentMode = document.documentMode); // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && "TextEvent" in window && !documentMode && !isPresto(), useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && 11 >= documentMode), SPACEBAR_CODE = 32, SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE), topLevelTypes = EventConstants.topLevelTypes, eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({ onBeforeInput: null }), captured: keyOf({ onBeforeInputCapture: null }) }, dependencies: [ topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste ] }, compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionEnd: null }), captured: keyOf({ onCompositionEndCapture: null }) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionStart: null }), captured: keyOf({ onCompositionStartCapture: null }) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionUpdate: null }), captured: keyOf({ onCompositionUpdateCapture: null }) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ] } }, hasSpaceKeypress = !1, currentComposition = null, BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [ extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) ]; } }; module.exports = BeforeInputEventPlugin; }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ "use strict"; var keyMirror = __webpack_require__(16), PropagationPhases = keyMirror({ bubbled: null, captured: null }), topLevelTypes = keyMirror({ topAbort: null, topAnimationEnd: null, topAnimationIteration: null, topAnimationStart: null, topBlur: null, topCanPlay: null, topCanPlayThrough: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topDurationChange: null, topEmptied: null, topEncrypted: null, topEnded: null, topError: null, topFocus: null, topInput: null, topInvalid: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topLoadedData: null, topLoadedMetadata: null, topLoadStart: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topPause: null, topPlay: null, topPlaying: null, topProgress: null, topRateChange: null, topReset: null, topScroll: null, topSeeked: null, topSeeking: null, topSelectionChange: null, topStalled: null, topSubmit: null, topSuspend: null, topTextInput: null, topTimeUpdate: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topTransitionEnd: null, topVolumeChange: null, topWaiting: null, topWheel: null }), EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only */ "use strict"; var invariant = __webpack_require__(18), keyMirror = function(obj) { var key, ret = {}; obj instanceof Object && !Array.isArray(obj) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "keyMirror(...): Argument must be an object.") : invariant(!1); for (key in obj) obj.hasOwnProperty(key) && (ret[key] = key); return ret; }; module.exports = keyMirror; }).call(exports, __webpack_require__(17)); }, /* 17 */ /***/ function(module, exports) { function cleanUpNextTick() { draining && currentQueue && (draining = !1, currentQueue.length ? queue = currentQueue.concat(queue) : queueIndex = -1, queue.length && drainQueue()); } function drainQueue() { if (!draining) { var timeout = setTimeout(cleanUpNextTick); draining = !0; for (var len = queue.length; len; ) { for (currentQueue = queue, queue = []; ++queueIndex < len; ) currentQueue && currentQueue[queueIndex].run(); queueIndex = -1, len = queue.length; } currentQueue = null, draining = !1, clearTimeout(timeout); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun, this.array = array; } function noop() {} // shim for using process in browser var currentQueue, process = module.exports = {}, queue = [], draining = !1, queueIndex = -1; 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)), 1 !== queue.length || draining || setTimeout(drainQueue, 0); }, Item.prototype.run = function() { this.fun.apply(null, this.array); }, process.title = "browser", process.browser = !0, process.env = {}, process.argv = [], process.version = "", // empty string to avoid regexp issues process.versions = {}, 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; }; }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if ("production" !== process.env.NODE_ENV && void 0 === format) throw new Error("invariant requires an error message argument"); if (!condition) { var error; if (void 0 === format) error = new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings."); else { var args = [ a, b, c, d, e, f ], argIndex = 0; error = new Error(format.replace(/%s/g, function() { return args[argIndex++]; })), error.name = "Invariant Violation"; } // we don't care about invariant's own frame throw error.framesToPop = 1, error; } } module.exports = invariant; }).call(exports, __webpack_require__(17)); }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ "use strict"; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, upwards, event) { "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(inst, "Dispatching inst must not be null") : void 0); var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured, listener = listenerAtPhase(inst, event, phase); listener && (event._dispatchListeners = accumulateInto(event._dispatchListeners, listener), event._dispatchInstances = accumulateInto(event._dispatchInstances, inst)); } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { event && event.dispatchConfig.phasedRegistrationNames && EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst, parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null; EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName, listener = getListener(inst, registrationName); listener && (event._dispatchListeners = accumulateInto(event._dispatchListeners, listener), event._dispatchInstances = accumulateInto(event._dispatchInstances, inst)); } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { event && event.dispatchConfig.registrationName && accumulateDispatches(event._targetInst, null, event); } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } var EventConstants = __webpack_require__(15), EventPluginHub = __webpack_require__(20), EventPluginUtils = __webpack_require__(22), accumulateInto = __webpack_require__(26), forEachAccumulated = __webpack_require__(27), warning = __webpack_require__(24), PropagationPhases = EventConstants.PropagationPhases, getListener = EventPluginHub.getListener, EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; }).call(exports, __webpack_require__(17)); }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ "use strict"; var EventPluginRegistry = __webpack_require__(21), EventPluginUtils = __webpack_require__(22), ReactErrorUtils = __webpack_require__(23), accumulateInto = __webpack_require__(26), forEachAccumulated = __webpack_require__(27), invariant = __webpack_require__(18), listenerBank = {}, eventQueue = null, executeDispatchesAndRelease = function(event, simulated) { event && (EventPluginUtils.executeDispatchesInOrder(event, simulated), event.isPersistent() || event.constructor.release(event)); }, executeDispatchesAndReleaseSimulated = function(e) { return executeDispatchesAndRelease(e, !0); }, executeDispatchesAndReleaseTopLevel = function(e) { return executeDispatchesAndRelease(e, !1); }, EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {function} listener The callback to store. */ putListener: function(inst, registrationName, listener) { "function" != typeof listener ? "production" !== process.env.NODE_ENV ? invariant(!1, "Expected %s listener to be a function, instead got type %s", registrationName, typeof listener) : invariant(!1) : void 0; var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[inst._rootNodeID] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; PluginModule && PluginModule.didPutListener && PluginModule.didPutListener(inst, registrationName, listener); }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function(inst, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[inst._rootNodeID]; }, /** * Deletes a listener from the registration bank. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function(inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; PluginModule && PluginModule.willDeleteListener && PluginModule.willDeleteListener(inst, registrationName); var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? bankForRegistrationName && delete bankForRegistrationName[inst._rootNodeID]; }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {object} inst The instance, which is the source of events. */ deleteAllListeners: function(inst) { for (var registrationName in listenerBank) if (listenerBank[registrationName][inst._rootNodeID]) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; PluginModule && PluginModule.willDeleteListener && PluginModule.willDeleteListener(inst, registrationName), delete listenerBank[registrationName][inst._rootNodeID]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { for (var events, plugins = EventPluginRegistry.plugins, i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); extractedEvents && (events = accumulateInto(events, extractedEvents)); } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function(events) { events && (eventQueue = accumulateInto(eventQueue, events)); }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function(simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null, simulated ? forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated) : forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel), eventQueue ? "production" !== process.env.NODE_ENV ? invariant(!1, "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.") : invariant(!1) : void 0, ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function() { listenerBank = {}; }, __getListenerBank: function() { return listenerBank; } }; module.exports = EventPluginHub; }).call(exports, __webpack_require__(17)); }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry */ "use strict"; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (EventPluginOrder) for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName], pluginIndex = EventPluginOrder.indexOf(pluginName); if (pluginIndex > -1 ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.", pluginName) : invariant(!1), !EventPluginRegistry.plugins[pluginIndex]) { PluginModule.extractEvents ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.", pluginName) : invariant(!1), EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", eventName, pluginName) : invariant(!1); } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.", eventName) : invariant(!1) : void 0, EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, PluginModule, eventName); } return !0; } return dispatchConfig.registrationName ? (publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName), !0) : !1; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { if (EventPluginRegistry.registrationNameModules[registrationName] ? "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.", registrationName) : invariant(!1) : void 0, EventPluginRegistry.registrationNameModules[registrationName] = PluginModule, EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies, "production" !== process.env.NODE_ENV) { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; } } var invariant = __webpack_require__(18), EventPluginOrder = null, namesToPlugins = {}, EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: "production" !== process.env.NODE_ENV ? {} : null, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function(InjectedEventPluginOrder) { EventPluginOrder ? "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.") : invariant(!1) : void 0, EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder), recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function(injectedNamesToPlugins) { var isOrderingDirty = !1; for (var pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) { var PluginModule = injectedNamesToPlugins[pluginName]; namesToPlugins.hasOwnProperty(pluginName) && namesToPlugins[pluginName] === PluginModule || (namesToPlugins[pluginName] ? "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.", pluginName) : invariant(!1) : void 0, namesToPlugins[pluginName] = PluginModule, isOrderingDirty = !0); } isOrderingDirty && recomputePluginOrdering(); }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function(event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; for (var phase in dispatchConfig.phasedRegistrationNames) if (dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; if (PluginModule) return PluginModule; } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function() { EventPluginOrder = null; for (var pluginName in namesToPlugins) namesToPlugins.hasOwnProperty(pluginName) && delete namesToPlugins[pluginName]; EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) eventNameDispatchConfigs.hasOwnProperty(eventName) && delete eventNameDispatchConfigs[eventName]; var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) registrationNameModules.hasOwnProperty(registrationName) && delete registrationNameModules[registrationName]; if ("production" !== process.env.NODE_ENV) { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) possibleRegistrationNames.hasOwnProperty(lowerCasedName) && delete possibleRegistrationNames[lowerCasedName]; } } }; module.exports = EventPluginRegistry; }).call(exports, __webpack_require__(17)); }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ "use strict"; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || "unknown-event"; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst), simulated ? ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event) : ReactErrorUtils.invokeGuardedCallback(type, listener, event), event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; if ("production" !== process.env.NODE_ENV && validateEventDispatches(event), Array.isArray(dispatchListeners)) for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); else dispatchListeners && executeDispatch(event, simulated, dispatchListeners, dispatchInstances); event._dispatchListeners = null, event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances; if ("production" !== process.env.NODE_ENV && validateEventDispatches(event), Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) return dispatchInstances[i]; } else if (dispatchListeners && dispatchListeners(event, dispatchInstances)) return dispatchInstances; return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); return event._dispatchInstances = null, event._dispatchListeners = null, ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { "production" !== process.env.NODE_ENV && validateEventDispatches(event); var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances; Array.isArray(dispatchListener) ? "production" !== process.env.NODE_ENV ? invariant(!1, "executeDirectDispatch(...): Invalid `event`.") : invariant(!1) : void 0, event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; return event.currentTarget = null, event._dispatchListeners = null, event._dispatchInstances = null, res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } var ComponentTree, TreeTraversal, validateEventDispatches, EventConstants = __webpack_require__(15), ReactErrorUtils = __webpack_require__(23), invariant = __webpack_require__(18), warning = __webpack_require__(24), injection = { injectComponentTree: function(Injected) { ComponentTree = Injected, "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, "EventPluginUtils.injection.injectComponentTree(...): Injected module is missing getNodeFromInstance or getInstanceFromNode.") : void 0); }, injectTreeTraversal: function(Injected) { TreeTraversal = Injected, "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, "EventPluginUtils.injection.injectTreeTraversal(...): Injected module is missing isAncestor or getLowestCommonAncestor.") : void 0); } }, topLevelTypes = EventConstants.topLevelTypes; "production" !== process.env.NODE_ENV && (validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances, listenersIsArr = Array.isArray(dispatchListeners), listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0, instancesIsArr = Array.isArray(dispatchInstances), instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; "production" !== process.env.NODE_ENV ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, "EventPluginUtils: Invalid `event`.") : void 0; }); /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getInstanceFromNode: function(node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function(node) { return ComponentTree.getNodeFromInstance(node); }, isAncestor: function(a, b) { return TreeTraversal.isAncestor(a, b); }, getLowestCommonAncestor: function(a, b) { return TreeTraversal.getLowestCommonAncestor(a, b); }, getParentInstance: function(inst) { return TreeTraversal.getParentInstance(inst); }, traverseTwoPhase: function(target, fn, arg) { return TreeTraversal.traverseTwoPhase(target, fn, arg); }, traverseEnterLeave: function(from, to, fn, argFrom, argTo) { return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo); }, injection: injection }; module.exports = EventPluginUtils; }).call(exports, __webpack_require__(17)); }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactErrorUtils */ "use strict"; /** * Call a function while guarding against errors that happens within it. * * @param {?String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a, b) { try { return func(a, b); } catch (x) { return void (null === caughtError && (caughtError = x)); } } var caughtError = null, ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function() { if (caughtError) { var error = caughtError; throw caughtError = null, error; } } }; if ("production" !== process.env.NODE_ENV && "undefined" != typeof window && "function" == typeof window.dispatchEvent && "undefined" != typeof document && "function" == typeof document.createEvent) { var fakeNode = document.createElement("react"); ReactErrorUtils.invokeGuardedCallback = function(name, func, a, b) { var boundFunc = func.bind(null, a, b), evtType = "react-" + name; fakeNode.addEventListener(evtType, boundFunc, !1); var evt = document.createEvent("Event"); evt.initEvent(evtType, !1, !1), fakeNode.dispatchEvent(evt), fakeNode.removeEventListener(evtType, boundFunc, !1); }; } module.exports = ReactErrorUtils; }).call(exports, __webpack_require__(17)); }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ "use strict"; var emptyFunction = __webpack_require__(25), warning = emptyFunction; "production" !== process.env.NODE_ENV && (warning = function(condition, format) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _len > _key; _key++) args[_key - 2] = arguments[_key]; if (void 0 === format) throw new Error("`warning(condition, format, ...args)` requires a warning message argument"); if (0 !== format.indexOf("Failed Composite propType: ") && !condition) { var argIndex = 0, message = "Warning: " + format.replace(/%s/g, function() { return args[argIndex++]; }); "undefined" != typeof console && console.error(message); try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} } }), module.exports = warning; }).call(exports, __webpack_require__(17)); }, /* 25 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function() {}; emptyFunction.thatReturns = makeEmptyFunction, emptyFunction.thatReturnsFalse = makeEmptyFunction(!1), emptyFunction.thatReturnsTrue = makeEmptyFunction(!0), emptyFunction.thatReturnsNull = makeEmptyFunction(null), emptyFunction.thatReturnsThis = function() { return this; }, emptyFunction.thatReturnsArgument = function(arg) { return arg; }, module.exports = emptyFunction; }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule accumulateInto */ "use strict"; /** * * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { if (null == next ? "production" !== process.env.NODE_ENV ? invariant(!1, "accumulateInto(...): Accumulated items must not be null or undefined.") : invariant(!1) : void 0, null == current) return next; // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current), nextIsArray = Array.isArray(next); return currentIsArray && nextIsArray ? (current.push.apply(current, next), current) : currentIsArray ? (current.push(next), current) : nextIsArray ? [ current ].concat(next) : [ current, next ]; } var invariant = __webpack_require__(18); module.exports = accumulateInto; }).call(exports, __webpack_require__(17)); }, /* 27 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated */ "use strict"; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function(arr, cb, scope) { Array.isArray(arr) ? arr.forEach(cb, scope) : arr && cb.call(scope, arr); }; module.exports = forEachAccumulated; }, /* 28 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ "use strict"; var canUseDOM = !("undefined" == typeof window || !window.document || !window.document.createElement), ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: "undefined" != typeof Worker, canUseEventListeners: canUseDOM && !(!window.addEventListener && !window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM }; module.exports = ExecutionEnvironment; }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FallbackCompositionState */ "use strict"; /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root, this._startText = this.getText(), this._fallbackText = null; } var _assign = __webpack_require__(30), PooledClass = __webpack_require__(31), getTextContentAccessor = __webpack_require__(32); _assign(FallbackCompositionState.prototype, { destructor: function() { this._root = null, this._startText = null, this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function() { return "value" in this._root ? this._root.value : this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function() { if (this._fallbackText) return this._fallbackText; var start, end, startValue = this._startText, startLength = startValue.length, endValue = this.getText(), endLength = endValue.length; for (start = 0; startLength > start && startValue[start] === endValue[start]; start++) ; var minEnd = startLength - start; for (end = 1; minEnd >= end && startValue[startLength - end] === endValue[endLength - end]; end++) ; var sliceTail = end > 1 ? 1 - end : void 0; return this._fallbackText = endValue.slice(start, sliceTail), this._fallbackText; } }), PooledClass.addPoolingTo(FallbackCompositionState), module.exports = FallbackCompositionState; }, /* 30 */ /***/ function(module, exports) { "use strict"; function toObject(val) { if (null === val || void 0 === val) throw new TypeError("Object.assign cannot be called with null or undefined"); return Object(val); } function shouldUseNative() { try { if (!Object.assign) return !1; // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String("abc"); if (// eslint-disable-line test1[5] = "de", "5" === Object.getOwnPropertyNames(test1)[0]) return !1; for (var test2 = {}, i = 0; 10 > i; i++) test2["_" + String.fromCharCode(i)] = i; var order2 = Object.getOwnPropertyNames(test2).map(function(n) { return test2[n]; }); if ("0123456789" !== order2.join("")) return !1; // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; return "abcdefghijklmnopqrst".split("").forEach(function(letter) { test3[letter] = letter; }), "abcdefghijklmnopqrst" === Object.keys(Object.assign({}, test3)).join(""); } catch (e) { // We don't expect any of the above to throw, but better to be safe. return !1; } } /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty, propIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = shouldUseNative() ? Object.assign : function(target, source) { for (var from, symbols, to = toObject(target), s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) hasOwnProperty.call(from, key) && (to[key] = from[key]); if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) propIsEnumerable.call(from, symbols[i]) && (to[symbols[i]] = from[symbols[i]]); } } return to; }; }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ "use strict"; var invariant = __webpack_require__(18), oneArgumentPooler = function(copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); return Klass.call(instance, copyFieldsFrom), instance; } return new Klass(copyFieldsFrom); }, twoArgumentPooler = function(a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); return Klass.call(instance, a1, a2), instance; } return new Klass(a1, a2); }, threeArgumentPooler = function(a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); return Klass.call(instance, a1, a2, a3), instance; } return new Klass(a1, a2, a3); }, fourArgumentPooler = function(a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); return Klass.call(instance, a1, a2, a3, a4), instance; } return new Klass(a1, a2, a3, a4); }, fiveArgumentPooler = function(a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); return Klass.call(instance, a1, a2, a3, a4, a5), instance; } return new Klass(a1, a2, a3, a4, a5); }, standardReleaser = function(instance) { var Klass = this; instance instanceof Klass ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Trying to release an instance into a pool of a different type.") : invariant(!1), instance.destructor(), Klass.instancePool.length < Klass.poolSize && Klass.instancePool.push(instance); }, DEFAULT_POOL_SIZE = 10, DEFAULT_POOLER = oneArgumentPooler, addPoolingTo = function(CopyConstructor, pooler) { var NewKlass = CopyConstructor; return NewKlass.instancePool = [], NewKlass.getPooled = pooler || DEFAULT_POOLER, NewKlass.poolSize || (NewKlass.poolSize = DEFAULT_POOL_SIZE), NewKlass.release = standardReleaser, NewKlass; }, PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; }).call(exports, __webpack_require__(17)); }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ "use strict"; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. return !contentKey && ExecutionEnvironment.canUseDOM && (contentKey = "textContent" in document.documentElement ? "textContent" : "innerText"), contentKey; } var ExecutionEnvironment = __webpack_require__(28), contentKey = null; module.exports = getTextContentAccessor; }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticEvent = __webpack_require__(34), CompositionEventInterface = { data: null }; SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface), module.exports = SyntheticCompositionEvent; }, /* 34 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent */ "use strict"; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { "production" !== process.env.NODE_ENV && (delete this.nativeEvent, delete this.preventDefault, delete this.stopPropagation), this.dispatchConfig = dispatchConfig, this._targetInst = targetInst, this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) if (Interface.hasOwnProperty(propName)) { "production" !== process.env.NODE_ENV && delete this[propName]; var normalize = Interface[propName]; normalize ? this[propName] = normalize(nativeEvent) : "target" === propName ? this.target = nativeEventTarget : this[propName] = nativeEvent[propName]; } var defaultPrevented = null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : nativeEvent.returnValue === !1; return defaultPrevented ? this.isDefaultPrevented = emptyFunction.thatReturnsTrue : this.isDefaultPrevented = emptyFunction.thatReturnsFalse, this.isPropagationStopped = emptyFunction.thatReturnsFalse, this; } /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { function set(val) { var action = isFunction ? "setting the method" : "setting the property"; return warn(action, "This is effectively a no-op"), val; } function get() { var action = isFunction ? "accessing the method" : "accessing the property", result = isFunction ? "This is a no-op function" : "This is set to null"; return warn(action, result), getVal; } function warn(action, result) { var warningCondition = !1; "production" !== process.env.NODE_ENV ? warning(warningCondition, "This synthetic event is reused for performance reasons. If you're seeing this, you're %s `%s` on a released/nullified synthetic event. %s. If you must keep the original synthetic event around, use event.persist(). See https://fb.me/react-event-pooling for more information.", action, propName, result) : void 0; } var isFunction = "function" == typeof getVal; return { configurable: !0, set: set, get: get }; } var _assign = __webpack_require__(30), PooledClass = __webpack_require__(31), emptyFunction = __webpack_require__(25), warning = __webpack_require__(24), didWarnForAddedNewProperty = !1, isProxySupported = "function" == typeof Proxy, shouldBeReleasedProperties = [ "dispatchConfig", "_targetInst", "nativeEvent", "isDefaultPrevented", "isPropagationStopped", "_dispatchListeners", "_dispatchInstances" ], EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function(event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; _assign(SyntheticEvent.prototype, { preventDefault: function() { this.defaultPrevented = !0; var event = this.nativeEvent; event && (event.preventDefault ? event.preventDefault() : event.returnValue = !1, this.isDefaultPrevented = emptyFunction.thatReturnsTrue); }, stopPropagation: function() { var event = this.nativeEvent; event && (event.stopPropagation ? event.stopPropagation() : event.cancelBubble = !0, this.isPropagationStopped = emptyFunction.thatReturnsTrue); }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function() { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function() { var Interface = this.constructor.Interface; for (var propName in Interface) "production" !== process.env.NODE_ENV ? Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])) : this[propName] = null; for (var i = 0; i < shouldBeReleasedProperties.length; i++) this[shouldBeReleasedProperties[i]] = null; if ("production" !== process.env.NODE_ENV) { var noop = __webpack_require__(25); Object.defineProperty(this, "nativeEvent", getPooledWarningPropertyDefinition("nativeEvent", null)), Object.defineProperty(this, "preventDefault", getPooledWarningPropertyDefinition("preventDefault", noop)), Object.defineProperty(this, "stopPropagation", getPooledWarningPropertyDefinition("stopPropagation", noop)); } } }), SyntheticEvent.Interface = EventInterface, "production" !== process.env.NODE_ENV && isProxySupported && (/*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function(target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function(constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function(target, prop, value) { return "isPersistent" === prop || target.constructor.Interface.hasOwnProperty(prop) || -1 !== shouldBeReleasedProperties.indexOf(prop) || ("production" !== process.env.NODE_ENV ? warning(didWarnForAddedNewProperty || target.isPersistent(), "This synthetic event is reused for performance reasons. If you're seeing this, you're adding a new property in the synthetic event object. The property is never released. See https://fb.me/react-event-pooling for more information.") : void 0, didWarnForAddedNewProperty = !0), target[prop] = value, !0; } }); } })), /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function(Class, Interface) { var Super = this, E = function() {}; E.prototype = Super.prototype; var prototype = new E(); _assign(prototype, Class.prototype), Class.prototype = prototype, Class.prototype.constructor = Class, Class.Interface = _assign({}, Super.Interface, Interface), Class.augmentClass = Super.augmentClass, PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }, PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler), module.exports = SyntheticEvent; }).call(exports, __webpack_require__(17)); }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticEvent = __webpack_require__(34), InputEventInterface = { data: null }; SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface), module.exports = SyntheticInputEvent; }, /* 36 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) if (oneKeyObj.hasOwnProperty(key)) return key; return null; }; module.exports = keyOf; }, /* 37 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ "use strict"; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return "select" === nodeName || "input" === nodeName && "file" === elem.type; } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event), // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event), EventPluginHub.processEventQueue(!1); } function startWatchingForChangeEventIE8(target, targetInst) { activeElement = target, activeElementInst = targetInst, activeElement.attachEvent("onchange", manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { activeElement && (activeElement.detachEvent("onchange", manualDispatchChangeEvent), activeElement = null, activeElementInst = null); } function getTargetInstForChangeEvent(topLevelType, targetInst) { return topLevelType === topLevelTypes.topChange ? targetInst : void 0; } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { topLevelType === topLevelTypes.topFocus ? (// stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(), startWatchingForChangeEventIE8(target, targetInst)) : topLevelType === topLevelTypes.topBlur && stopWatchingForChangeEventIE8(); } /** * (For IE <=11) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target, activeElementInst = targetInst, activeElementValue = target.value, activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, "value"), Object.defineProperty(activeElement, "value", newValueProp), activeElement.attachEvent ? activeElement.attachEvent("onpropertychange", handlePropertyChange) : activeElement.addEventListener("propertychange", handlePropertyChange, !1); } /** * (For IE <=11) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { activeElement && (// delete restores the original property definition delete activeElement.value, activeElement.detachEvent ? activeElement.detachEvent("onpropertychange", handlePropertyChange) : activeElement.removeEventListener("propertychange", handlePropertyChange, !1), activeElement = null, activeElementInst = null, activeElementValue = null, activeElementValueProp = null); } /** * (For IE <=11) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if ("value" === nativeEvent.propertyName) { var value = nativeEvent.srcElement.value; value !== activeElementValue && (activeElementValue = value, manualDispatchChangeEvent(nativeEvent)); } } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetInstForInputEvent(topLevelType, targetInst) { return topLevelType === topLevelTypes.topInput ? targetInst : void 0; } function handleEventsForInputEventIE(topLevelType, target, targetInst) { topLevelType === topLevelTypes.topFocus ? (// In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9-11, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(), startWatchingForValueChange(target, targetInst)) : topLevelType === topLevelTypes.topBlur && stopWatchingForValueChange(); } // For IE8 and IE9. function getTargetInstForInputEventIE(topLevelType, targetInst) { return topLevelType !== topLevelTypes.topSelectionChange && topLevelType !== topLevelTypes.topKeyUp && topLevelType !== topLevelTypes.topKeyDown || !activeElement || activeElement.value === activeElementValue ? void 0 : (activeElementValue = activeElement.value, activeElementInst); } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && "input" === elem.nodeName.toLowerCase() && ("checkbox" === elem.type || "radio" === elem.type); } function getTargetInstForClickEvent(topLevelType, targetInst) { return topLevelType === topLevelTypes.topClick ? targetInst : void 0; } var EventConstants = __webpack_require__(15), EventPluginHub = __webpack_require__(20), EventPropagators = __webpack_require__(19), ExecutionEnvironment = __webpack_require__(28), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), SyntheticEvent = __webpack_require__(34), getEventTarget = __webpack_require__(55), isEventSupported = __webpack_require__(56), isTextInputElement = __webpack_require__(57), keyOf = __webpack_require__(36), topLevelTypes = EventConstants.topLevelTypes, eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({ onChange: null }), captured: keyOf({ onChangeCapture: null }) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange ] } }, activeElement = null, activeElementInst = null, activeElementValue = null, activeElementValueProp = null, doesChangeEventBubble = !1; ExecutionEnvironment.canUseDOM && (// See `handleChange` comment below doesChangeEventBubble = isEventSupported("change") && (!("documentMode" in document) || document.documentMode > 8)); /** * SECTION: handle `input` event */ var isInputEventSupported = !1; ExecutionEnvironment.canUseDOM && (// IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. // IE10+ fire input events to often, such when a placeholder // changes or when an input with a placeholder is focused. isInputEventSupported = isEventSupported("input") && (!("documentMode" in document) || document.documentMode > 11)); /** * (For IE <=11) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function() { return activeElementValueProp.get.call(this); }, set: function(val) { activeElementValue = "" + val, activeElementValueProp.set.call(this, val); } }, ChangeEventPlugin = { eventTypes: eventTypes, extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var getTargetInstFunc, handleEventFunc, targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; if (shouldUseChangeEvent(targetNode) ? doesChangeEventBubble ? getTargetInstFunc = getTargetInstForChangeEvent : handleEventFunc = handleEventsForChangeEventIE8 : isTextInputElement(targetNode) ? isInputEventSupported ? getTargetInstFunc = getTargetInstForInputEvent : (getTargetInstFunc = getTargetInstForInputEventIE, handleEventFunc = handleEventsForInputEventIE) : shouldUseClickEvent(targetNode) && (getTargetInstFunc = getTargetInstForClickEvent), getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget); return event.type = "change", EventPropagators.accumulateTwoPhaseDispatches(event), event; } } handleEventFunc && handleEventFunc(topLevelType, targetNode, targetInst); } }; module.exports = ChangeEventPlugin; }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponentTree */ "use strict"; /** * Drill down (through composites and empty components) until we get a native or * native text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedNativeOrTextFromComponent(component) { for (var rendered; rendered = component._renderedComponent; ) component = rendered; return component; } /** * Populate `_nativeNode` on the rendered native/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var nativeInst = getRenderedNativeOrTextFromComponent(inst); nativeInst._nativeNode = node, node[internalInstanceKey] = nativeInst; } function uncacheNode(inst) { var node = inst._nativeNode; node && (delete node[internalInstanceKey], inst._nativeNode = null); } /** * Populate `_nativeNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (!(inst._flags & Flags.hasCachedChildNodes)) { var children = inst._renderedChildren, childNode = node.firstChild; outer: for (var name in children) if (children.hasOwnProperty(name)) { var childInst = children[name], childID = getRenderedNativeOrTextFromComponent(childInst)._domID; if (null != childID) { // We assume the child nodes are in the same order as the child instances. for (;null !== childNode; childNode = childNode.nextSibling) if (1 === childNode.nodeType && childNode.getAttribute(ATTR_NAME) === String(childID) || 8 === childNode.nodeType && childNode.nodeValue === " react-text: " + childID + " " || 8 === childNode.nodeType && childNode.nodeValue === " react-empty: " + childID + " ") { precacheNode(childInst, childNode); continue outer; } "production" !== process.env.NODE_ENV ? invariant(!1, "Unable to find element with ID %s.", childID) : invariant(!1); } } inst._flags |= Flags.hasCachedChildNodes; } } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) return node[internalInstanceKey]; for (// Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; !node[internalInstanceKey]; ) { if (parents.push(node), !node.parentNode) // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; node = node.parentNode; } for (var closest, inst; node && (inst = node[internalInstanceKey]); node = parents.pop()) closest = inst, parents.length && precacheChildNodes(inst, node); return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = getClosestInstanceFromNode(node); return null != inst && inst._nativeNode === node ? inst : null; } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { if (void 0 === inst._nativeNode ? "production" !== process.env.NODE_ENV ? invariant(!1, "getNodeFromInstance: Invalid argument.") : invariant(!1) : void 0, inst._nativeNode) return inst._nativeNode; for (// Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; !inst._nativeNode; ) parents.push(inst), inst._nativeParent ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "React DOM tree root should always have a node reference.") : invariant(!1), inst = inst._nativeParent; // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (;parents.length; inst = parents.pop()) precacheChildNodes(inst, inst._nativeNode); return inst._nativeNode; } var DOMProperty = __webpack_require__(39), ReactDOMComponentFlags = __webpack_require__(40), invariant = __webpack_require__(18), ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME, Flags = ReactDOMComponentFlags, internalInstanceKey = "__reactInternalInstance$" + Math.random().toString(36).slice(2), ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode }; module.exports = ReactDOMComponentTree; }).call(exports, __webpack_require__(17)); }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty */ "use strict"; function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var invariant = __webpack_require__(18), DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_PROPERTY: 1, HAS_SIDE_EFFECTS: 2, HAS_BOOLEAN_VALUE: 4, HAS_NUMERIC_VALUE: 8, HAS_POSITIVE_NUMERIC_VALUE: 24, HAS_OVERLOADED_BOOLEAN_VALUE: 32, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function(domPropertyConfig) { var Injection = DOMPropertyInjection, Properties = domPropertyConfig.Properties || {}, DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}, DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}, DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}, DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; domPropertyConfig.isCustomAttribute && DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); for (var propName in Properties) { DOMProperty.properties.hasOwnProperty(propName) ? "production" !== process.env.NODE_ENV ? invariant(!1, "injectDOMPropertyConfig(...): You're trying to inject DOM property '%s' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.", propName) : invariant(!1) : void 0; var lowerCased = propName.toLowerCase(), propConfig = Properties[propName], propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; if (!propertyInfo.mustUseProperty && propertyInfo.hasSideEffects ? "production" !== process.env.NODE_ENV ? invariant(!1, "DOMProperty: Properties that have side effects must use property: %s", propName) : invariant(!1) : void 0, propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1 ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s", propName) : invariant(!1), "production" !== process.env.NODE_ENV && (DOMProperty.getPossibleStandardName[lowerCased] = propName), DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName, "production" !== process.env.NODE_ENV && (DOMProperty.getPossibleStandardName[attributeName] = propName); } DOMAttributeNamespaces.hasOwnProperty(propName) && (propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]), DOMPropertyNames.hasOwnProperty(propName) && (propertyInfo.propertyName = DOMPropertyNames[propName]), DOMMutationMethods.hasOwnProperty(propName) && (propertyInfo.mutationMethod = DOMMutationMethods[propName]), DOMProperty.properties[propName] = propertyInfo; } } }, ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD", DOMProperty = { ID_ATTRIBUTE_NAME: "data-reactid", ROOT_ATTRIBUTE_NAME: "data-reactroot", ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\uB7\\u0300-\\u036F\\u203F-\\u2040", /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasSideEffects: * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. If true, we read from * the DOM before updating to ensure that the value is only set if it has * changed. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * @type {Object} */ getPossibleStandardName: "production" !== process.env.NODE_ENV ? {} : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function(attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) return !0; } return !1; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; }).call(exports, __webpack_require__(17)); }, /* 40 */ /***/ function(module, exports) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponentFlags */ "use strict"; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 }; module.exports = ReactDOMComponentFlags; }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ "use strict"; function ensureInjected() { ReactUpdates.ReactReconcileTransaction && batchingStrategy ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must inject a reconcile transaction class and batching strategy") : invariant(!1); } function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(), this.dirtyComponentsLength = null, this.callbackQueue = CallbackQueue.getPooled(), this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(/* useCreateElement */ !0); } function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(), batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; len !== dirtyComponents.length ? "production" !== process.env.NODE_ENV ? invariant(!1, "Expected flush transaction's stored dirty-components length (%s) to match dirty-components array length (%s).", len, dirtyComponents.length) : invariant(!1) : void 0, // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator), // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; for (var i = 0; len > i; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i], callbacks = component._pendingCallbacks; component._pendingCallbacks = null; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. component._currentElement.props === component._renderedComponent._currentElement && (namedComponent = component._renderedComponent), markerName = "React update: " + namedComponent.getName(), console.time(markerName); } if (ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber), markerName && console.timeEnd(markerName), callbacks) for (var j = 0; j < callbacks.length; j++) transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) return ensureInjected(), batchingStrategy.isBatchingUpdates ? (dirtyComponents.push(component), void (null == component._updateBatchNumber && (component._updateBatchNumber = updateBatchNumber + 1))) : void batchingStrategy.batchedUpdates(enqueueUpdate, component); } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { batchingStrategy.isBatchingUpdates ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates.asap: Can't enqueue an asap callback in a context whereupdates are not being batched.") : invariant(!1), asapCallbackQueue.enqueue(callback, context), asapEnqueued = !0; } var _assign = __webpack_require__(30), CallbackQueue = __webpack_require__(42), PooledClass = __webpack_require__(31), ReactFeatureFlags = __webpack_require__(43), ReactInstrumentation = __webpack_require__(44), ReactReconciler = __webpack_require__(51), Transaction = __webpack_require__(54), invariant = __webpack_require__(18), dirtyComponents = [], updateBatchNumber = 0, asapCallbackQueue = CallbackQueue.getPooled(), asapEnqueued = !1, batchingStrategy = null, NESTED_UPDATES = { initialize: function() { this.dirtyComponentsLength = dirtyComponents.length; }, close: function() { this.dirtyComponentsLength !== dirtyComponents.length ? (// Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength), flushBatchedUpdates()) : dirtyComponents.length = 0; } }, UPDATE_QUEUEING = { initialize: function() { this.callbackQueue.reset(); }, close: function() { this.callbackQueue.notifyAll(); } }, TRANSACTION_WRAPPERS = [ NESTED_UPDATES, UPDATE_QUEUEING ]; _assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, destructor: function() { this.dirtyComponentsLength = null, CallbackQueue.release(this.callbackQueue), this.callbackQueue = null, ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction), this.reconcileTransaction = null; }, perform: function(method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }), PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); var flushBatchedUpdates = function() { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. for ("production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onBeginFlush(); dirtyComponents.length || asapEnqueued; ) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction), ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = !1; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(), queue.notifyAll(), CallbackQueue.release(queue); } } "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onEndFlush(); }, ReactUpdatesInjection = { injectReconcileTransaction: function(ReconcileTransaction) { ReconcileTransaction ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must provide a reconcile transaction class") : invariant(!1), ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function(_batchingStrategy) { _batchingStrategy ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must provide a batching strategy") : invariant(!1), "function" != typeof _batchingStrategy.batchedUpdates ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must provide a batchedUpdates() function") : invariant(!1) : void 0, "boolean" != typeof _batchingStrategy.isBatchingUpdates ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must provide an isBatchingUpdates boolean attribute") : invariant(!1) : void 0, batchingStrategy = _batchingStrategy; } }, ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; }).call(exports, __webpack_require__(17)); }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ "use strict"; /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null, this._contexts = null; } var _assign = __webpack_require__(30), PooledClass = __webpack_require__(31), invariant = __webpack_require__(18); _assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function(callback, context) { this._callbacks = this._callbacks || [], this._contexts = this._contexts || [], this._callbacks.push(callback), this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function() { var callbacks = this._callbacks, contexts = this._contexts; if (callbacks) { callbacks.length !== contexts.length ? "production" !== process.env.NODE_ENV ? invariant(!1, "Mismatched list of contexts in callback queue") : invariant(!1) : void 0, this._callbacks = null, this._contexts = null; for (var i = 0; i < callbacks.length; i++) callbacks[i].call(contexts[i]); callbacks.length = 0, contexts.length = 0; } }, checkpoint: function() { return this._callbacks ? this._callbacks.length : 0; }, rollback: function(len) { this._callbacks && (this._callbacks.length = len, this._contexts.length = len); }, /** * Resets the internal queue. * * @internal */ reset: function() { this._callbacks = null, this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function() { this.reset(); } }), PooledClass.addPoolingTo(CallbackQueue), module.exports = CallbackQueue; }).call(exports, __webpack_require__(17)); }, /* 43 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactFeatureFlags */ "use strict"; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: !1 }; module.exports = ReactFeatureFlags; }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstrumentation */ "use strict"; var ReactDebugTool = __webpack_require__(45); module.exports = { debugTool: ReactDebugTool }; }, /* 45 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDebugTool */ "use strict"; function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) { "production" !== process.env.NODE_ENV && eventHandlers.forEach(function(handler) { try { handler[handlerFunctionName] && handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5); } catch (e) { "production" !== process.env.NODE_ENV ? warning(!handlerDoesThrowForEvent[handlerFunctionName], "exception thrown by devtool while handling %s: %s", handlerFunctionName, e.message) : void 0, handlerDoesThrowForEvent[handlerFunctionName] = !0; } }); } function clearHistory() { ReactComponentTreeDevtool.purgeUnmountedComponents(), ReactNativeOperationHistoryDevtool.clearHistory(); } function getTreeSnapshot(registeredIDs) { return registeredIDs.reduce(function(tree, id) { var ownerID = ReactComponentTreeDevtool.getOwnerID(id), parentID = ReactComponentTreeDevtool.getParentID(id); return tree[id] = { displayName: ReactComponentTreeDevtool.getDisplayName(id), text: ReactComponentTreeDevtool.getText(id), updateCount: ReactComponentTreeDevtool.getUpdateCount(id), childIDs: ReactComponentTreeDevtool.getChildIDs(id), // Text nodes don't have owners but this is close enough. ownerID: ownerID || ReactComponentTreeDevtool.getOwnerID(parentID), parentID: parentID }, tree; }, {}); } function resetMeasurements() { if ("production" !== process.env.NODE_ENV) { var previousStartTime = currentFlushStartTime, previousMeasurements = currentFlushMeasurements || [], previousOperations = ReactNativeOperationHistoryDevtool.getHistory(); if (!isProfiling || 0 === currentFlushNesting) return currentFlushStartTime = null, currentFlushMeasurements = null, void clearHistory(); if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeDevtool.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(), currentFlushStartTime = performanceNow(), currentFlushMeasurements = []; } } function checkDebugID(debugID) { "production" !== process.env.NODE_ENV ? warning(debugID, "ReactDebugTool: debugID may not be empty.") : void 0; } var ExecutionEnvironment = __webpack_require__(28), performanceNow = __webpack_require__(46), warning = __webpack_require__(24), eventHandlers = [], handlerDoesThrowForEvent = {}, isProfiling = !1, flushHistory = [], currentFlushNesting = 0, currentFlushMeasurements = null, currentFlushStartTime = null, currentTimerDebugID = null, currentTimerStartTime = null, currentTimerType = null, ReactDebugTool = { addDevtool: function(devtool) { eventHandlers.push(devtool); }, removeDevtool: function(devtool) { for (var i = 0; i < eventHandlers.length; i++) eventHandlers[i] === devtool && (eventHandlers.splice(i, 1), i--); }, beginProfiling: function() { if ("production" !== process.env.NODE_ENV) { if (isProfiling) return; isProfiling = !0, flushHistory.length = 0, resetMeasurements(); } }, endProfiling: function() { if ("production" !== process.env.NODE_ENV) { if (!isProfiling) return; isProfiling = !1, resetMeasurements(); } }, getFlushHistory: function() { return "production" !== process.env.NODE_ENV ? flushHistory : void 0; }, onBeginFlush: function() { "production" !== process.env.NODE_ENV && (currentFlushNesting++, resetMeasurements()), emitEvent("onBeginFlush"); }, onEndFlush: function() { "production" !== process.env.NODE_ENV && (resetMeasurements(), currentFlushNesting--), emitEvent("onEndFlush"); }, onBeginLifeCycleTimer: function(debugID, timerType) { checkDebugID(debugID), emitEvent("onBeginLifeCycleTimer", debugID, timerType), "production" !== process.env.NODE_ENV && isProfiling && currentFlushNesting > 0 && ("production" !== process.env.NODE_ENV ? warning(!currentTimerType, "There is an internal error in the React performance measurement code. Did not expect %s timer to start while %s timer is still in progress for %s instance.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another") : void 0, currentTimerStartTime = performanceNow(), currentTimerDebugID = debugID, currentTimerType = timerType); }, onEndLifeCycleTimer: function(debugID, timerType) { checkDebugID(debugID), "production" !== process.env.NODE_ENV && isProfiling && currentFlushNesting > 0 && ("production" !== process.env.NODE_ENV ? warning(currentTimerType === timerType, "There is an internal error in the React performance measurement code. We did not expect %s timer to stop while %s timer is still in progress for %s instance. Please report this as a bug in React.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another") : void 0, currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime }), currentTimerStartTime = null, currentTimerDebugID = null, currentTimerType = null), emitEvent("onEndLifeCycleTimer", debugID, timerType); }, onBeginReconcilerTimer: function(debugID, timerType) { checkDebugID(debugID), emitEvent("onBeginReconcilerTimer", debugID, timerType); }, onEndReconcilerTimer: function(debugID, timerType) { checkDebugID(debugID), emitEvent("onEndReconcilerTimer", debugID, timerType); }, onBeginProcessingChildContext: function() { emitEvent("onBeginProcessingChildContext"); }, onEndProcessingChildContext: function() { emitEvent("onEndProcessingChildContext"); }, onNativeOperation: function(debugID, type, payload) { checkDebugID(debugID), emitEvent("onNativeOperation", debugID, type, payload); }, onSetState: function() { emitEvent("onSetState"); }, onSetDisplayName: function(debugID, displayName) { checkDebugID(debugID), emitEvent("onSetDisplayName", debugID, displayName); }, onSetChildren: function(debugID, childDebugIDs) { checkDebugID(debugID), emitEvent("onSetChildren", debugID, childDebugIDs); }, onSetOwner: function(debugID, ownerDebugID) { checkDebugID(debugID), emitEvent("onSetOwner", debugID, ownerDebugID); }, onSetText: function(debugID, text) { checkDebugID(debugID), emitEvent("onSetText", debugID, text); }, onMountRootComponent: function(debugID) { checkDebugID(debugID), emitEvent("onMountRootComponent", debugID); }, onMountComponent: function(debugID) { checkDebugID(debugID), emitEvent("onMountComponent", debugID); }, onUpdateComponent: function(debugID) { checkDebugID(debugID), emitEvent("onUpdateComponent", debugID); }, onUnmountComponent: function(debugID) { checkDebugID(debugID), emitEvent("onUnmountComponent", debugID); } }; if ("production" !== process.env.NODE_ENV) { var ReactInvalidSetStateWarningDevTool = __webpack_require__(48), ReactNativeOperationHistoryDevtool = __webpack_require__(49), ReactComponentTreeDevtool = __webpack_require__(50); ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool), ReactDebugTool.addDevtool(ReactComponentTreeDevtool), ReactDebugTool.addDevtool(ReactNativeOperationHistoryDevtool); var url = ExecutionEnvironment.canUseDOM && window.location.href || ""; /[?&]react_perf\b/.test(url) && ReactDebugTool.beginProfiling(); } module.exports = ReactDebugTool; }).call(exports, __webpack_require__(17)); }, /* 46 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var performanceNow, performance = __webpack_require__(47); /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ performanceNow = performance.now ? function() { return performance.now(); } : function() { return Date.now(); }, module.exports = performanceNow; }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ "use strict"; var performance, ExecutionEnvironment = __webpack_require__(28); ExecutionEnvironment.canUseDOM && (performance = window.performance || window.msPerformance || window.webkitPerformance), module.exports = performance || {}; }, /* 48 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInvalidSetStateWarningDevTool */ "use strict"; var warning = __webpack_require__(24); if ("production" !== process.env.NODE_ENV) var processingChildContext = !1, warnInvalidSetState = function() { "production" !== process.env.NODE_ENV ? warning(!processingChildContext, "setState(...): Cannot call setState() inside getChildContext()") : void 0; }; var ReactInvalidSetStateWarningDevTool = { onBeginProcessingChildContext: function() { processingChildContext = !0; }, onEndProcessingChildContext: function() { processingChildContext = !1; }, onSetState: function() { warnInvalidSetState(); } }; module.exports = ReactInvalidSetStateWarningDevTool; }).call(exports, __webpack_require__(17)); }, /* 49 */ /***/ function(module, exports) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNativeOperationHistoryDevtool */ "use strict"; var history = [], ReactNativeOperationHistoryDevtool = { onNativeOperation: function(debugID, type, payload) { history.push({ instanceID: debugID, type: type, payload: payload }); }, clearHistory: function() { ReactNativeOperationHistoryDevtool._preventClearing || (history = []); }, getHistory: function() { return history; } }; module.exports = ReactNativeOperationHistoryDevtool; }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentTreeDevtool */ "use strict"; function updateTree(id, update) { tree[id] || (tree[id] = { parentID: null, ownerID: null, text: null, childIDs: [], displayName: "Unknown", isMounted: !1, updateCount: 0 }), update(tree[id]); } function purgeDeep(id) { var item = tree[id]; if (item) { var childIDs = item.childIDs; delete tree[id], childIDs.forEach(purgeDeep); } } var invariant = __webpack_require__(18), tree = {}, rootIDs = [], ReactComponentTreeDevtool = { onSetDisplayName: function(id, displayName) { updateTree(id, function(item) { return item.displayName = displayName; }); }, onSetChildren: function(id, nextChildIDs) { updateTree(id, function(item) { var prevChildIDs = item.childIDs; item.childIDs = nextChildIDs, nextChildIDs.forEach(function(nextChildID) { var nextChild = tree[nextChildID]; nextChild ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Expected devtool events to fire for the child before its parent includes it in onSetChildren().") : invariant(!1), null == nextChild.displayName ? "production" !== process.env.NODE_ENV ? invariant(!1, "Expected onSetDisplayName() to fire for the child before its parent includes it in onSetChildren().") : invariant(!1) : void 0, null == nextChild.childIDs && null == nextChild.text ? "production" !== process.env.NODE_ENV ? invariant(!1, "Expected onSetChildren() or onSetText() to fire for the child before its parent includes it in onSetChildren().") : invariant(!1) : void 0, nextChild.isMounted ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().") : invariant(!1), -1 === prevChildIDs.indexOf(nextChildID) && (nextChild.parentID = id); }); }); }, onSetOwner: function(id, ownerID) { updateTree(id, function(item) { return item.ownerID = ownerID; }); }, onSetText: function(id, text) { updateTree(id, function(item) { return item.text = text; }); }, onMountComponent: function(id) { updateTree(id, function(item) { return item.isMounted = !0; }); }, onMountRootComponent: function(id) { rootIDs.push(id); }, onUpdateComponent: function(id) { updateTree(id, function(item) { return item.updateCount++; }); }, onUnmountComponent: function(id) { updateTree(id, function(item) { return item.isMounted = !1; }), rootIDs = rootIDs.filter(function(rootID) { return rootID !== id; }); }, purgeUnmountedComponents: function() { ReactComponentTreeDevtool._preventPurging || Object.keys(tree).filter(function(id) { return !tree[id].isMounted; }).forEach(purgeDeep); }, isMounted: function(id) { var item = tree[id]; return item ? item.isMounted : !1; }, getChildIDs: function(id) { var item = tree[id]; return item ? item.childIDs : []; }, getDisplayName: function(id) { var item = tree[id]; return item ? item.displayName : "Unknown"; }, getOwnerID: function(id) { var item = tree[id]; return item ? item.ownerID : null; }, getParentID: function(id) { var item = tree[id]; return item ? item.parentID : null; }, getText: function(id) { var item = tree[id]; return item ? item.text : null; }, getUpdateCount: function(id) { var item = tree[id]; return item ? item.updateCount : 0; }, getRootIDs: function() { return rootIDs; }, getRegisteredIDs: function() { return Object.keys(tree); } }; module.exports = ReactComponentTreeDevtool; }).call(exports, __webpack_require__(17)); }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ "use strict"; /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactRef = __webpack_require__(52), ReactInstrumentation = __webpack_require__(44), invariant = __webpack_require__(18), ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing native component instance * @param {?object} info about the native container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function(internalInstance, transaction, nativeParent, nativeContainerInfo, context) { "production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, "mountComponent"); var markup = internalInstance.mountComponent(transaction, nativeParent, nativeContainerInfo, context); return internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance), "production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && (ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, "mountComponent"), ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID)), markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getNativeNode: function(internalInstance) { return internalInstance.getNativeNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function(internalInstance, safely) { "production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, "unmountComponent"), ReactRef.detachRefs(internalInstance, internalInstance._currentElement), internalInstance.unmountComponent(safely), "production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && (ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, "unmountComponent"), ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID)); }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function(internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement !== prevElement || context !== internalInstance._context) { "production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, "receiveComponent"); var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); refsChanged && ReactRef.detachRefs(internalInstance, prevElement), internalInstance.receiveComponent(nextElement, transaction, context), refsChanged && internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance), "production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && (ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, "receiveComponent"), ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID)); } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function(internalInstance, transaction, updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. return internalInstance._updateBatchNumber !== updateBatchNumber ? void (null != internalInstance._updateBatchNumber && internalInstance._updateBatchNumber !== updateBatchNumber + 1 ? "production" !== process.env.NODE_ENV ? invariant(!1, "performUpdateIfNecessary: Unexpected batch number (current %s, pending %s)", updateBatchNumber, internalInstance._updateBatchNumber) : invariant(!1) : void 0) : ("production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, "performUpdateIfNecessary"), internalInstance.performUpdateIfNecessary(transaction), void ("production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && (ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, "performUpdateIfNecessary"), ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID)))); } }; module.exports = ReactReconciler; }).call(exports, __webpack_require__(17)); }, /* 52 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRef */ "use strict"; function attachRef(ref, component, owner) { "function" == typeof ref ? ref(component.getPublicInstance()) : // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } function detachRef(ref, component, owner) { "function" == typeof ref ? ref(null) : // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } var ReactOwner = __webpack_require__(53), ReactRef = {}; ReactRef.attachRefs = function(instance, element) { if (null !== element && element !== !1) { var ref = element.ref; null != ref && attachRef(ref, instance, element._owner); } }, ReactRef.shouldUpdateRefs = function(prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevEmpty = null === prevElement || prevElement === !1, nextEmpty = null === nextElement || nextElement === !1; // This has a few false positives w/r/t empty components. return prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref; }, ReactRef.detachRefs = function(instance, element) { if (null !== element && element !== !1) { var ref = element.ref; null != ref && detachRef(ref, instance, element._owner); } }, module.exports = ReactRef; }, /* 53 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ "use strict"; var invariant = __webpack_require__(18), ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function(object) { return !(!object || "function" != typeof object.attachRef || "function" != typeof object.detachRef); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function(component, ref, owner) { ReactOwner.isValidOwner(owner) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).") : invariant(!1), owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function(component, ref, owner) { ReactOwner.isValidOwner(owner) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).") : invariant(!1); var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance() && owner.detachRef(ref); } }; module.exports = ReactOwner; }).call(exports, __webpack_require__(17)); }, /* 54 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ "use strict"; var invariant = __webpack_require__(18), Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function() { this.transactionWrappers = this.getTransactionWrappers(), this.wrapperInitData ? this.wrapperInitData.length = 0 : this.wrapperInitData = [], this._isInTransaction = !1; }, _isInTransaction: !1, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function() { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function(method, scope, a, b, c, d, e, f) { this.isInTransaction() ? "production" !== process.env.NODE_ENV ? invariant(!1, "Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.") : invariant(!1) : void 0; var errorThrown, ret; try { this._isInTransaction = !0, // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = !0, this.initializeAll(0), ret = method.call(scope, a, b, c, d, e, f), errorThrown = !1; } finally { try { if (errorThrown) // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} else // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } finally { this._isInTransaction = !1; } } return ret; }, initializeAll: function(startIndex) { for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR, this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function(startIndex) { this.isInTransaction() ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Transaction.closeAll(): Cannot close transaction when none are open.") : invariant(!1); for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) { var errorThrown, wrapper = transactionWrappers[i], initData = this.wrapperInitData[i]; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = !0, initData !== Transaction.OBSERVED_ERROR && wrapper.close && wrapper.close.call(this, initData), errorThrown = !1; } finally { if (errorThrown) // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } this.wrapperInitData.length = 0; } }, Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occurred. */ OBSERVED_ERROR: {} }; module.exports = Transaction; }).call(exports, __webpack_require__(17)); }, /* 55 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventTarget */ "use strict"; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html // Normalize SVG <use> element events #4963 return target.correspondingUseElement && (target = target.correspondingUseElement), 3 === target.nodeType ? target.parentNode : target; } module.exports = getEventTarget; }, /* 56 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ "use strict"; /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !("addEventListener" in document)) return !1; var eventName = "on" + eventNameSuffix, isSupported = eventName in document; if (!isSupported) { var element = document.createElement("div"); element.setAttribute(eventName, "return;"), isSupported = "function" == typeof element[eventName]; } // This is the only way to test support for the `wheel` event in IE9+. return !isSupported && useHasFeature && "wheel" === eventNameSuffix && (isSupported = document.implementation.hasFeature("Events.wheel", "3.0")), isSupported; } var useHasFeature, ExecutionEnvironment = __webpack_require__(28); ExecutionEnvironment.canUseDOM && (useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature("", "") !== !0), module.exports = isEventSupported; }, /* 57 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement */ "use strict"; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && ("input" === nodeName && supportedInputTypes[elem.type] || "textarea" === nodeName); } /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { color: !0, date: !0, datetime: !0, "datetime-local": !0, email: !0, month: !0, number: !0, password: !0, range: !0, search: !0, tel: !0, text: !0, time: !0, url: !0, week: !0 }; module.exports = isTextInputElement; }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ "use strict"; var keyOf = __webpack_require__(36), DefaultEventPluginOrder = [ keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null }) ]; module.exports = DefaultEventPluginOrder; }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin */ "use strict"; var EventConstants = __webpack_require__(15), EventPropagators = __webpack_require__(19), ReactDOMComponentTree = __webpack_require__(38), SyntheticMouseEvent = __webpack_require__(60), keyOf = __webpack_require__(36), topLevelTypes = EventConstants.topLevelTypes, eventTypes = { mouseEnter: { registrationName: keyOf({ onMouseEnter: null }), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] }, mouseLeave: { registrationName: keyOf({ onMouseLeave: null }), dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ] } }, EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) return null; if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) // Must not be a mouse in or mouse out - ignoring. return null; var win; if (nativeEventTarget.window === nativeEventTarget) // `nativeEventTarget` is probably a window object. win = nativeEventTarget; else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; win = doc ? doc.defaultView || doc.parentWindow : window; } var from, to; if (topLevelType === topLevelTypes.topMouseOut) { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else from = null, to = targetInst; if (from === to) // Nothing pertains to our managed components. return null; var fromNode = null == from ? win : ReactDOMComponentTree.getNodeFromInstance(from), toNode = null == to ? win : ReactDOMComponentTree.getNodeFromInstance(to), leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = "mouseleave", leave.target = fromNode, leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); return enter.type = "mouseenter", enter.target = toNode, enter.relatedTarget = fromNode, EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to), [ leave, enter ]; } }; module.exports = EnterLeaveEventPlugin; }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticUIEvent = __webpack_require__(61), ViewportMetrics = __webpack_require__(62), getEventModifierState = __webpack_require__(63), MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function(event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; return "which" in event ? button : 2 === button ? 2 : 4 === button ? 1 : 0; }, buttons: null, relatedTarget: function(event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function(event) { return "pageX" in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function(event) { return "pageY" in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface), module.exports = SyntheticMouseEvent; }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticEvent = __webpack_require__(34), getEventTarget = __webpack_require__(55), UIEventInterface = { view: function(event) { if (event.view) return event.view; var target = getEventTarget(event); if (null != target && target.window === target) // target is a window object return target; var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. return doc ? doc.defaultView || doc.parentWindow : window; }, detail: function(event) { return event.detail || 0; } }; SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface), module.exports = SyntheticUIEvent; }, /* 62 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ "use strict"; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function(scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x, ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; }, /* 63 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState */ "use strict"; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this, nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) return nativeEvent.getModifierState(keyArg); var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : !1; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { Alt: "altKey", Control: "ctrlKey", Meta: "metaKey", Shift: "shiftKey" }; module.exports = getEventModifierState; }, /* 64 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ "use strict"; var DOMProperty = __webpack_require__(39), MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY, HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE, HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS, HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE, HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE, HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE, HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp("^(data|aria)-[" + DOMProperty.ATTRIBUTE_NAME_CHAR + "]*$")), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, "default": HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, icon: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, "typeof": 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: "accept-charset", className: "class", htmlFor: "for", httpEquiv: "http-equiv" }, DOMPropertyNames: {} }; module.exports = HTMLDOMPropertyConfig; }, /* 65 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ "use strict"; var DOMChildrenOperations = __webpack_require__(66), ReactDOMIDOperations = __webpack_require__(78), ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function(rootNodeID) {} }; module.exports = ReactComponentBrowserEnvironment; }, /* 66 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations */ "use strict"; function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getNativeNode. return Array.isArray(node) && (node = node[1]), node ? node.nextSibling : parentNode.firstChild; } function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { Array.isArray(childNode) ? moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode) : insertChildAt(parentNode, childNode, referenceNode); } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0], removeDelimitedText(parentNode, childNode, closingComment), parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { for (var node = openingComment; ;) { var nextNode = node.nextSibling; if (insertChildAt(parentNode, node, referenceNode), node === closingComment) break; node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { for (;;) { var node = startNode.nextSibling; if (node === closingComment) // The closing comment is removed by ReactMultiChild. break; parentNode.removeChild(node); } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode, nodeAfterComment = openingComment.nextSibling; nodeAfterComment === closingComment ? // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. stringText && insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment) : stringText ? (// Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText), removeDelimitedText(parentNode, nodeAfterComment, closingComment)) : removeDelimitedText(parentNode, openingComment, closingComment), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, "replace text", stringText); } var DOMLazyTree = __webpack_require__(67), Danger = __webpack_require__(73), ReactMultiChildUpdateTypes = __webpack_require__(77), ReactDOMComponentTree = __webpack_require__(38), ReactInstrumentation = __webpack_require__(44), createMicrosoftUnsafeLocalFunction = __webpack_require__(69), setInnerHTML = __webpack_require__(72), setTextContent = __webpack_require__(70), insertChildAt = createMicrosoftUnsafeLocalFunction(function(parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }), dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup; "production" !== process.env.NODE_ENV && (dangerouslyReplaceNodeWithMarkup = function(oldChild, markup, prevInstance) { if (Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup), 0 !== prevInstance._debugID) ReactInstrumentation.debugTool.onNativeOperation(prevInstance._debugID, "replace with", markup.toString()); else { var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node); 0 !== nextInstance._debugID && ReactInstrumentation.debugTool.onNativeOperation(nextInstance._debugID, "mount", markup.toString()); } }); /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @internal */ processUpdates: function(parentNode, updates) { if ("production" !== process.env.NODE_ENV) var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID; for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "insert child", { toIndex: update.toIndex, content: update.content.toString() }); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "move child", { fromIndex: update.fromIndex, toIndex: update.toIndex }); break; case ReactMultiChildUpdateTypes.SET_MARKUP: setInnerHTML(parentNode, update.content), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "replace children", update.content.toString()); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent(parentNode, update.content), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "replace text", update.content.toString()); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: removeChild(parentNode, update.fromNode), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "remove child", { fromIndex: update.fromIndex }); } } } }; module.exports = DOMChildrenOperations; }).call(exports, __webpack_require__(17)); }, /* 67 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMLazyTree */ "use strict"; function insertTreeChildren(tree) { if (enableLazy) { var node = tree.node, children = tree.children; if (children.length) for (var i = 0; i < children.length; i++) insertTreeBefore(node, children[i], null); else null != tree.html ? node.innerHTML = tree.html : null != tree.text && setTextContent(node, tree.text); } } function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode), insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { enableLazy ? parentTree.children.push(childTree) : parentTree.node.appendChild(childTree.node); } function queueHTML(tree, html) { enableLazy ? tree.html = html : tree.node.innerHTML = html; } function queueText(tree, text) { enableLazy ? tree.text = text : setTextContent(tree.node, text); } function toString() { return this.node.nodeName; } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null, toString: toString }; } var DOMNamespaces = __webpack_require__(68), createMicrosoftUnsafeLocalFunction = __webpack_require__(69), setTextContent = __webpack_require__(70), ELEMENT_NODE_TYPE = 1, DOCUMENT_FRAGMENT_NODE_TYPE = 11, enableLazy = "undefined" != typeof document && "number" == typeof document.documentMode || "undefined" != typeof navigator && "string" == typeof navigator.userAgent && /\bEdge\/\d/.test(navigator.userAgent), insertTreeBefore = createMicrosoftUnsafeLocalFunction(function(parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. Also, some <object> plugins (like Flash Player) will read // <param> nodes immediately upon insertion into the DOM, so <object> // must also be populated prior to insertion into the DOM. tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && "object" === tree.node.nodeName.toLowerCase() && (null == tree.node.namespaceURI || tree.node.namespaceURI === DOMNamespaces.html) ? (insertTreeChildren(tree), parentNode.insertBefore(tree.node, referenceNode)) : (parentNode.insertBefore(tree.node, referenceNode), insertTreeChildren(tree)); }); DOMLazyTree.insertTreeBefore = insertTreeBefore, DOMLazyTree.replaceChildWithTree = replaceChildWithTree, DOMLazyTree.queueChild = queueChild, DOMLazyTree.queueHTML = queueHTML, DOMLazyTree.queueText = queueText, module.exports = DOMLazyTree; }, /* 68 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMNamespaces */ "use strict"; var DOMNamespaces = { html: "http://www.w3.org/1999/xhtml", mathml: "http://www.w3.org/1998/Math/MathML", svg: "http://www.w3.org/2000/svg" }; module.exports = DOMNamespaces; }, /* 69 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createMicrosoftUnsafeLocalFunction */ /* globals MSApp */ "use strict"; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function(func) { return "undefined" != typeof MSApp && MSApp.execUnsafeLocalFunction ? function(arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function() { return func(arg0, arg1, arg2, arg3); }); } : func; }; module.exports = createMicrosoftUnsafeLocalFunction; }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setTextContent */ "use strict"; var ExecutionEnvironment = __webpack_require__(28), escapeTextContentForBrowser = __webpack_require__(71), setInnerHTML = __webpack_require__(72), setTextContent = function(node, text) { node.textContent = text; }; ExecutionEnvironment.canUseDOM && ("textContent" in document.documentElement || (setTextContent = function(node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); })), module.exports = setTextContent; }, /* 71 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule escapeTextContentForBrowser */ "use strict"; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { return ("" + text).replace(ESCAPE_REGEX, escaper); } var ESCAPE_LOOKUP = { "&": "&amp;", ">": "&gt;", "<": "&lt;", '"': "&quot;", "'": "&#x27;" }, ESCAPE_REGEX = /[&><"']/g; module.exports = escapeTextContentForBrowser; }, /* 72 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ "use strict"; var ExecutionEnvironment = __webpack_require__(28), WHITESPACE_TEST = /^[ \r\n\t\f]/, NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/, createMicrosoftUnsafeLocalFunction = __webpack_require__(69), setInnerHTML = createMicrosoftUnsafeLocalFunction(function(node, html) { node.innerHTML = html; }); if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement("div"); testElement.innerHTML = " ", "" === testElement.innerHTML && (setInnerHTML = function(node, html) { // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (// Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? node.parentNode && node.parentNode.replaceChild(node, node), WHITESPACE_TEST.test(html) || "<" === html[0] && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(65279) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; 1 === textNode.data.length ? node.removeChild(textNode) : textNode.deleteData(0, 1); } else node.innerHTML = html; }), testElement = null; } module.exports = setInnerHTML; }, /* 73 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger */ "use strict"; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(" ")); } var DOMLazyTree = __webpack_require__(67), ExecutionEnvironment = __webpack_require__(28), createNodesFromMarkup = __webpack_require__(74), emptyFunction = __webpack_require__(25), getMarkupWrap = __webpack_require__(76), invariant = __webpack_require__(18), OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/, RESULT_INDEX_ATTR = "data-danger-index", Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function(markupList) { ExecutionEnvironment.canUseDOM ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString for server rendering.") : invariant(!1); // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var nodeName, markupByNodeName = {}, i = 0; i < markupList.length; i++) markupList[i] ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyRenderMarkup(...): Missing markup.") : invariant(!1), nodeName = getNodeName(markupList[i]), nodeName = getMarkupWrap(nodeName) ? nodeName : "*", markupByNodeName[nodeName] = markupByNodeName[nodeName] || [], markupByNodeName[nodeName][i] = markupList[i]; var resultList = [], resultListAssignmentCount = 0; for (nodeName in markupByNodeName) if (markupByNodeName.hasOwnProperty(nodeName)) { var resultIndex, markupListByNodeName = markupByNodeName[nodeName]; for (resultIndex in markupListByNodeName) if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP, // This index will be parsed back out below. "$1 " + RESULT_INDEX_ATTR + '="' + resultIndex + '" '); } for (var renderNodes = createNodesFromMarkup(markupListByNodeName.join(""), emptyFunction), j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR) ? (resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR), renderNode.removeAttribute(RESULT_INDEX_ATTR), resultList.hasOwnProperty(resultIndex) ? "production" !== process.env.NODE_ENV ? invariant(!1, "Danger: Assigning to an already-occupied result index.") : invariant(!1) : void 0, resultList[resultIndex] = renderNode, resultListAssignmentCount += 1) : "production" !== process.env.NODE_ENV && console.error("Danger: Discarding unexpected node:", renderNode); } } // Although resultList was populated out of order, it should now be a dense // array. return resultListAssignmentCount !== resultList.length ? "production" !== process.env.NODE_ENV ? invariant(!1, "Danger: Did not assign to every index of resultList.") : invariant(!1) : void 0, resultList.length !== markupList.length ? "production" !== process.env.NODE_ENV ? invariant(!1, "Danger: Expected markup to render %s nodes, but rendered %s.", markupList.length, resultList.length) : invariant(!1) : void 0, resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function(oldChild, markup) { if (ExecutionEnvironment.canUseDOM ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.") : invariant(!1), markup ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyReplaceNodeWithMarkup(...): Missing markup.") : invariant(!1), "HTML" === oldChild.nodeName ? "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().") : invariant(!1) : void 0, "string" == typeof markup) { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else DOMLazyTree.replaceChildWithTree(oldChild, markup); } }; module.exports = Danger; }).call(exports, __webpack_require__(17)); }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { "use strict"; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; dummyNode ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "createNodesFromMarkup dummy not initialized") : invariant(!1); var nodeName = getNodeName(markup), wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; for (var wrapDepth = wrap[0]; wrapDepth--; ) node = node.lastChild; } else node.innerHTML = markup; var scripts = node.getElementsByTagName("script"); scripts.length && (handleScript ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "createNodesFromMarkup(...): Unexpected <script> element rendered.") : invariant(!1), createArrayFromMixed(scripts).forEach(handleScript)); for (var nodes = Array.from(node.childNodes); node.lastChild; ) node.removeChild(node.lastChild); return nodes; } /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = __webpack_require__(28), createArrayFromMixed = __webpack_require__(75), getMarkupWrap = __webpack_require__(76), invariant = __webpack_require__(18), dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement("div") : null, nodeNamePattern = /^\s*<(\w+)/; module.exports = createNodesFromMarkup; }).call(exports, __webpack_require__(17)); }, /* 75 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { "use strict"; /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (Array.isArray(obj) || "object" != typeof obj && "function" != typeof obj ? "production" !== process.env.NODE_ENV ? invariant(!1, "toArray: Array-like object expected") : invariant(!1) : void 0, "number" != typeof length ? "production" !== process.env.NODE_ENV ? invariant(!1, "toArray: Object needs a length property") : invariant(!1) : void 0, 0 === length || length - 1 in obj ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "toArray: Object should have keys for indices") : invariant(!1), "function" == typeof obj.callee ? "production" !== process.env.NODE_ENV ? invariant(!1, "toArray: Object can't be `arguments`. Use rest params (function(...args) {}) or Array.from() instead.") : invariant(!1) : void 0, obj.hasOwnProperty) try { return Array.prototype.slice.call(obj); } catch (e) {} for (var ret = Array(length), ii = 0; length > ii; ii++) ret[ii] = obj[ii]; return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { // not null/false // arrays are objects, NodeLists are functions in Safari // quacks like an array // not window // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 // a real array // arguments // HTMLCollection/NodeList return !!obj && ("object" == typeof obj || "function" == typeof obj) && "length" in obj && !("setInterval" in obj) && "number" != typeof obj.nodeType && (Array.isArray(obj) || "callee" in obj || "item" in obj); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { return hasArrayNature(obj) ? Array.isArray(obj) ? obj.slice() : toArray(obj) : [ obj ]; } /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var invariant = __webpack_require__(18); module.exports = createArrayFromMixed; }).call(exports, __webpack_require__(17)); }, /* 76 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { "use strict"; /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { return dummyNode ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Markup wrapping node not initialized") : invariant(!1), markupWrap.hasOwnProperty(nodeName) || (nodeName = "*"), shouldWrap.hasOwnProperty(nodeName) || ("*" === nodeName ? dummyNode.innerHTML = "<link />" : dummyNode.innerHTML = "<" + nodeName + "></" + nodeName + ">", shouldWrap[nodeName] = !dummyNode.firstChild), shouldWrap[nodeName] ? markupWrap[nodeName] : null; } /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /*eslint-disable fb-www/unsafe-html */ var ExecutionEnvironment = __webpack_require__(28), invariant = __webpack_require__(18), dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement("div") : null, shouldWrap = {}, selectWrap = [ 1, '<select multiple="true">', "</select>" ], tableWrap = [ 1, "<table>", "</table>" ], trWrap = [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], svgWrap = [ 1, '<svg xmlns="http://www.w3.org/2000/svg">', "</svg>" ], markupWrap = { "*": [ 1, "?<div>", "</div>" ], area: [ 1, "<map>", "</map>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], param: [ 1, "<object>", "</object>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], optgroup: selectWrap, option: selectWrap, caption: tableWrap, colgroup: tableWrap, tbody: tableWrap, tfoot: tableWrap, thead: tableWrap, td: trWrap, th: trWrap }, svgElements = [ "circle", "clipPath", "defs", "ellipse", "g", "image", "line", "linearGradient", "mask", "path", "pattern", "polygon", "polyline", "radialGradient", "rect", "stop", "text", "tspan" ]; svgElements.forEach(function(nodeName) { markupWrap[nodeName] = svgWrap, shouldWrap[nodeName] = !0; }), module.exports = getMarkupWrap; }).call(exports, __webpack_require__(17)); }, /* 77 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ "use strict"; var keyMirror = __webpack_require__(16), ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, SET_MARKUP: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; }, /* 78 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations */ "use strict"; var DOMChildrenOperations = __webpack_require__(66), ReactDOMComponentTree = __webpack_require__(38), ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function(parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); } }; module.exports = ReactDOMIDOperations; }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent */ /* global hasOwnProperty:true */ "use strict"; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) return " This DOM node was rendered by `" + name + "`."; } } return ""; } function friendlyStringify(obj) { if ("object" == typeof obj) { if (Array.isArray(obj)) return "[" + obj.map(friendlyStringify).join(", ") + "]"; var pairs = []; for (var key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ": " + friendlyStringify(obj[key])); } return "{" + pairs.join(", ") + "}"; } return "string" == typeof obj ? JSON.stringify(obj) : "function" == typeof obj ? "[function object]" : String(obj); } function checkAndWarnForMutatedStyle(style1, style2, component) { if (null != style1 && null != style2 && !shallowEqual(style1, style2)) { var ownerName, componentName = component._tag, owner = component._currentElement._owner; owner && (ownerName = owner.getName()); var hash = ownerName + "|" + componentName; styleMutationWarning.hasOwnProperty(hash) || (styleMutationWarning[hash] = !0, "production" !== process.env.NODE_ENV ? warning(!1, "`%s` was passed a style object that has previously been mutated. Mutating `style` is deprecated. Consider cloning it beforehand. Check the `render` %s. Previous style: %s. Mutated style: %s.", componentName, owner ? "of `" + ownerName + "`" : "using <" + componentName + ">", friendlyStringify(style1), friendlyStringify(style2)) : void 0); } } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { props && (// Note the use of `==` which checks for null or undefined. voidElementTags[component._tag] && (null != props.children || null != props.dangerouslySetInnerHTML ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s is a void element tag and must not have `children` or use `props.dangerouslySetInnerHTML`.%s", component._tag, component._currentElement._owner ? " Check the render method of " + component._currentElement._owner.getName() + "." : "") : invariant(!1) : void 0), null != props.dangerouslySetInnerHTML && (null != props.children ? "production" !== process.env.NODE_ENV ? invariant(!1, "Can only set one of `children` or `props.dangerouslySetInnerHTML`.") : invariant(!1) : void 0, "object" == typeof props.dangerouslySetInnerHTML && HTML in props.dangerouslySetInnerHTML ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.") : invariant(!1)), "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null == props.innerHTML, "Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`.") : void 0, "production" !== process.env.NODE_ENV ? warning(props.suppressContentEditableWarning || !props.contentEditable || null == props.children, "A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.") : void 0, "production" !== process.env.NODE_ENV ? warning(null == props.onFocusIn && null == props.onFocusOut, "React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React.") : void 0), null != props.style && "object" != typeof props.style ? "production" !== process.env.NODE_ENV ? invariant(!1, "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.%s", getDeclarationErrorAddendum(component)) : invariant(!1) : void 0); } function enqueuePutListener(inst, registrationName, listener, transaction) { if (!(transaction instanceof ReactServerRenderingTransaction)) { "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning("onScroll" !== registrationName || isEventSupported("scroll", !0), "This browser doesn't support the `onScroll` event") : void 0); var containerInfo = inst._nativeContainerInfo, isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE, doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; listenTo(registrationName, doc), transaction.getReactMountReady().enqueue(putListener, { inst: inst, registrationName: registrationName, listener: listener }); } } function putListener() { var listenerToPut = this; EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } function trapBubbledEventsLocal() { var inst = this; inst._rootNodeID ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Must be mounted to trap events") : invariant(!1); var node = getNode(inst); switch (node ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "trapBubbledEvent(...): Requires node to be rendered.") : invariant(!1), inst._tag) { case "iframe": case "object": inst._wrapperState.listeners = [ ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, "load", node) ]; break; case "video": case "audio": inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) mediaEvents.hasOwnProperty(event) && inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); break; case "img": inst._wrapperState.listeners = [ ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, "error", node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, "load", node) ]; break; case "form": inst._wrapperState.listeners = [ ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, "reset", node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, "submit", node) ]; break; case "input": case "select": case "textarea": inst._wrapperState.listeners = [ ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topInvalid, "invalid", node) ]; } } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } function validateDangerousTag(tag) { hasOwnProperty.call(validatedTagCache, tag) || (VALID_TAG_REGEX.test(tag) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Invalid tag: %s", tag) : invariant(!1), validatedTagCache[tag] = !0); } function isCustomComponent(tagName, props) { return tagName.indexOf("-") >= 0 || null != props.is; } /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(element) { var tag = element.type; validateDangerousTag(tag), this._currentElement = element, this._tag = tag.toLowerCase(), this._namespaceURI = null, this._renderedChildren = null, this._previousStyle = null, this._previousStyleCopy = null, this._nativeNode = null, this._nativeParent = null, this._rootNodeID = null, this._domID = null, this._nativeContainerInfo = null, this._wrapperState = null, this._topLevelWrapper = null, this._flags = 0, "production" !== process.env.NODE_ENV && (this._ancestorInfo = null, this._contentDebugID = null); } var _assign = __webpack_require__(30), AutoFocusUtils = __webpack_require__(80), CSSPropertyOperations = __webpack_require__(82), DOMLazyTree = __webpack_require__(67), DOMNamespaces = __webpack_require__(68), DOMProperty = __webpack_require__(39), DOMPropertyOperations = __webpack_require__(90), EventConstants = __webpack_require__(15), EventPluginHub = __webpack_require__(20), EventPluginRegistry = __webpack_require__(21), ReactBrowserEventEmitter = __webpack_require__(95), ReactComponentBrowserEnvironment = __webpack_require__(65), ReactDOMButton = __webpack_require__(98), ReactDOMComponentFlags = __webpack_require__(40), ReactDOMComponentTree = __webpack_require__(38), ReactDOMInput = __webpack_require__(100), ReactDOMOption = __webpack_require__(109), ReactDOMSelect = __webpack_require__(113), ReactDOMTextarea = __webpack_require__(114), ReactInstrumentation = __webpack_require__(44), ReactMultiChild = __webpack_require__(115), ReactServerRenderingTransaction = __webpack_require__(128), emptyFunction = __webpack_require__(25), escapeTextContentForBrowser = __webpack_require__(71), invariant = __webpack_require__(18), isEventSupported = __webpack_require__(56), keyOf = __webpack_require__(36), shallowEqual = __webpack_require__(129), validateDOMNesting = __webpack_require__(130), warning = __webpack_require__(24), Flags = ReactDOMComponentFlags, deleteListener = EventPluginHub.deleteListener, getNode = ReactDOMComponentTree.getNodeFromInstance, listenTo = ReactBrowserEventEmitter.listenTo, registrationNameModules = EventPluginRegistry.registrationNameModules, CONTENT_TYPES = { string: !0, number: !0 }, STYLE = keyOf({ style: null }), HTML = keyOf({ __html: null }), RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }, DOC_FRAGMENT_TYPE = 11, styleMutationWarning = {}, setContentChildForInstrumentation = emptyFunction; "production" !== process.env.NODE_ENV && (setContentChildForInstrumentation = function(contentToUse) { var debugID = this._debugID, contentDebugID = debugID + "#text"; this._contentDebugID = contentDebugID, ReactInstrumentation.debugTool.onSetDisplayName(contentDebugID, "#text"), ReactInstrumentation.debugTool.onSetText(contentDebugID, "" + contentToUse), ReactInstrumentation.debugTool.onMountComponent(contentDebugID), ReactInstrumentation.debugTool.onSetChildren(debugID, [ contentDebugID ]); }); // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: "abort", topCanPlay: "canplay", topCanPlayThrough: "canplaythrough", topDurationChange: "durationchange", topEmptied: "emptied", topEncrypted: "encrypted", topEnded: "ended", topError: "error", topLoadedData: "loadeddata", topLoadedMetadata: "loadedmetadata", topLoadStart: "loadstart", topPause: "pause", topPlay: "play", topPlaying: "playing", topProgress: "progress", topRateChange: "ratechange", topSeeked: "seeked", topSeeking: "seeking", topStalled: "stalled", topSuspend: "suspend", topTimeUpdate: "timeupdate", topVolumeChange: "volumechange", topWaiting: "waiting" }, omittedCloseTags = { area: !0, base: !0, br: !0, col: !0, embed: !0, hr: !0, img: !0, input: !0, keygen: !0, link: !0, meta: !0, param: !0, source: !0, track: !0, wbr: !0 }, newlineEatingTags = { listing: !0, pre: !0, textarea: !0 }, voidElementTags = _assign({ menuitem: !0 }, omittedCloseTags), VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, validatedTagCache = {}, hasOwnProperty = {}.hasOwnProperty, globalIdCounter = 1; ReactDOMComponent.displayName = "ReactDOMComponent", ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?ReactDOMComponent} the containing DOM component instance * @param {?object} info about the native container * @param {object} context * @return {string} The computed markup. */ mountComponent: function(transaction, nativeParent, nativeContainerInfo, context) { this._rootNodeID = globalIdCounter++, this._domID = nativeContainerInfo._idCounter++, this._nativeParent = nativeParent, this._nativeContainerInfo = nativeContainerInfo; var props = this._currentElement.props; switch (this._tag) { case "iframe": case "object": case "img": case "form": case "video": case "audio": this._wrapperState = { listeners: null }, transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case "button": props = ReactDOMButton.getNativeProps(this, props, nativeParent); break; case "input": ReactDOMInput.mountWrapper(this, props, nativeParent), props = ReactDOMInput.getNativeProps(this, props), transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case "option": ReactDOMOption.mountWrapper(this, props, nativeParent), props = ReactDOMOption.getNativeProps(this, props); break; case "select": ReactDOMSelect.mountWrapper(this, props, nativeParent), props = ReactDOMSelect.getNativeProps(this, props), transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case "textarea": ReactDOMTextarea.mountWrapper(this, props, nativeParent), props = ReactDOMTextarea.getNativeProps(this, props), transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); } assertValidProps(this, props); // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI, parentTag; if (null != nativeParent ? (namespaceURI = nativeParent._namespaceURI, parentTag = nativeParent._tag) : nativeContainerInfo._tag && (namespaceURI = nativeContainerInfo._namespaceURI, parentTag = nativeContainerInfo._tag), (null == namespaceURI || namespaceURI === DOMNamespaces.svg && "foreignobject" === parentTag) && (namespaceURI = DOMNamespaces.html), namespaceURI === DOMNamespaces.html && ("svg" === this._tag ? namespaceURI = DOMNamespaces.svg : "math" === this._tag && (namespaceURI = DOMNamespaces.mathml)), this._namespaceURI = namespaceURI, "production" !== process.env.NODE_ENV) { var parentInfo; null != nativeParent ? parentInfo = nativeParent._ancestorInfo : nativeContainerInfo._tag && (parentInfo = nativeContainerInfo._ancestorInfo), parentInfo && // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(this._tag, this, parentInfo), this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; if (transaction.useCreateElement) { var el, ownerDocument = nativeContainerInfo._ownerDocument; if (namespaceURI === DOMNamespaces.html) if ("script" === this._tag) { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement("div"), type = this._currentElement.type; div.innerHTML = "<" + type + "></" + type + ">", el = div.removeChild(div.firstChild); } else el = ownerDocument.createElement(this._currentElement.type, props.is || null); else el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type); ReactDOMComponentTree.precacheNode(this, el), this._flags |= Flags.hasCachedChildNodes, this._nativeParent || DOMPropertyOperations.setAttributeForRoot(el), this._updateDOMProperties(null, props, transaction); var lazyTree = DOMLazyTree(el); this._createInitialChildren(transaction, props, context, lazyTree), mountImage = lazyTree; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props), tagContent = this._createContentMarkup(transaction, props, context); mountImage = !tagContent && omittedCloseTags[this._tag] ? tagOpen + "/>" : tagOpen + ">" + tagContent + "</" + this._currentElement.type + ">"; } switch (this._tag) { case "button": case "input": case "select": case "textarea": props.autoFocus && transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); break; case "option": transaction.getReactMountReady().enqueue(optionPostMount, this); } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function(transaction, props) { var ret = "<" + this._currentElement.type; for (var propKey in props) if (props.hasOwnProperty(propKey)) { var propValue = props[propKey]; if (null != propValue) if (registrationNameModules.hasOwnProperty(propKey)) propValue && enqueuePutListener(this, propKey, propValue, transaction); else { propKey === STYLE && (propValue && ("production" !== process.env.NODE_ENV && (// See `_updateDOMProperties`. style block this._previousStyle = propValue), propValue = this._previousStyleCopy = _assign({}, props.style)), propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this)); var markup = null; null != this._tag && isCustomComponent(this._tag, props) ? RESERVED_PROPS.hasOwnProperty(propKey) || (markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue)) : markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue), markup && (ret += " " + markup); } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. // For static pages, no need to put React ID and checksum. Saves lots of // bytes. return transaction.renderToStaticMarkup ? ret : (this._nativeParent || (ret += " " + DOMPropertyOperations.createMarkupForRoot()), ret += " " + DOMPropertyOperations.createMarkupForID(this._domID)); }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function(transaction, props, context) { var ret = "", innerHTML = props.dangerouslySetInnerHTML; if (null != innerHTML) null != innerHTML.__html && (ret = innerHTML.__html); else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null, childrenToUse = null != contentToUse ? null : props.children; if (null != contentToUse) ret = escapeTextContentForBrowser(contentToUse), "production" !== process.env.NODE_ENV && setContentChildForInstrumentation.call(this, contentToUse); else if (null != childrenToUse) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(""); } } return newlineEatingTags[this._tag] && "\n" === ret.charAt(0) ? "\n" + ret : ret; }, _createInitialChildren: function(transaction, props, context, lazyTree) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (null != innerHTML) null != innerHTML.__html && DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null, childrenToUse = null != contentToUse ? null : props.children; if (null != contentToUse) // TODO: Validate that text is allowed as a child of this node "production" !== process.env.NODE_ENV && setContentChildForInstrumentation.call(this, contentToUse), DOMLazyTree.queueText(lazyTree, contentToUse); else if (null != childrenToUse) for (var mountImages = this.mountChildren(childrenToUse, transaction, context), i = 0; i < mountImages.length; i++) DOMLazyTree.queueChild(lazyTree, mountImages[i]); } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function(nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement, this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function(transaction, prevElement, nextElement, context) { var lastProps = prevElement.props, nextProps = this._currentElement.props; switch (this._tag) { case "button": lastProps = ReactDOMButton.getNativeProps(this, lastProps), nextProps = ReactDOMButton.getNativeProps(this, nextProps); break; case "input": ReactDOMInput.updateWrapper(this), lastProps = ReactDOMInput.getNativeProps(this, lastProps), nextProps = ReactDOMInput.getNativeProps(this, nextProps); break; case "option": lastProps = ReactDOMOption.getNativeProps(this, lastProps), nextProps = ReactDOMOption.getNativeProps(this, nextProps); break; case "select": lastProps = ReactDOMSelect.getNativeProps(this, lastProps), nextProps = ReactDOMSelect.getNativeProps(this, nextProps); break; case "textarea": ReactDOMTextarea.updateWrapper(this), lastProps = ReactDOMTextarea.getNativeProps(this, lastProps), nextProps = ReactDOMTextarea.getNativeProps(this, nextProps); } assertValidProps(this, nextProps), this._updateDOMProperties(lastProps, nextProps, transaction), this._updateDOMChildren(lastProps, nextProps, transaction, context), "select" === this._tag && // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {?DOMElement} node */ _updateDOMProperties: function(lastProps, nextProps, transaction) { var propKey, styleName, styleUpdates; for (propKey in lastProps) if (!nextProps.hasOwnProperty(propKey) && lastProps.hasOwnProperty(propKey) && null != lastProps[propKey]) if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) lastStyle.hasOwnProperty(styleName) && (styleUpdates = styleUpdates || {}, styleUpdates[styleName] = ""); this._previousStyleCopy = null; } else registrationNameModules.hasOwnProperty(propKey) ? lastProps[propKey] && // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this, propKey) : (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) && DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey); for (propKey in nextProps) { var nextProp = nextProps[propKey], lastProp = propKey === STYLE ? this._previousStyleCopy : null != lastProps ? lastProps[propKey] : void 0; if (nextProps.hasOwnProperty(propKey) && nextProp !== lastProp && (null != nextProp || null != lastProp)) if (propKey === STYLE) if (nextProp ? ("production" !== process.env.NODE_ENV && (checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this), this._previousStyle = nextProp), nextProp = this._previousStyleCopy = _assign({}, nextProp)) : this._previousStyleCopy = null, lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) !lastProp.hasOwnProperty(styleName) || nextProp && nextProp.hasOwnProperty(styleName) || (styleUpdates = styleUpdates || {}, styleUpdates[styleName] = ""); // Update styles that changed since `lastProp`. for (styleName in nextProp) nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName] && (styleUpdates = styleUpdates || {}, styleUpdates[styleName] = nextProp[styleName]); } else // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; else if (registrationNameModules.hasOwnProperty(propKey)) nextProp ? enqueuePutListener(this, propKey, nextProp, transaction) : lastProp && deleteListener(this, propKey); else if (isCustomComponent(this._tag, nextProps)) RESERVED_PROPS.hasOwnProperty(propKey) || DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. null != nextProp ? DOMPropertyOperations.setValueForProperty(node, propKey, nextProp) : DOMPropertyOperations.deleteValueForProperty(node, propKey); } } styleUpdates && CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this); }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function(lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null, nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null, lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html, nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html, lastChildren = null != lastContent ? null : lastProps.children, nextChildren = null != nextContent ? null : nextProps.children, lastHasContentOrHtml = null != lastContent || null != lastHtml, nextHasContentOrHtml = null != nextContent || null != nextHtml; null != lastChildren && null == nextChildren ? this.updateChildren(null, transaction, context) : lastHasContentOrHtml && !nextHasContentOrHtml && (this.updateTextContent(""), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onSetChildren(this._debugID, [])), null != nextContent ? lastContent !== nextContent && (this.updateTextContent("" + nextContent), "production" !== process.env.NODE_ENV && (this._contentDebugID = this._debugID + "#text", setContentChildForInstrumentation.call(this, nextContent))) : null != nextHtml ? (lastHtml !== nextHtml && this.updateMarkup("" + nextHtml), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onSetChildren(this._debugID, [])) : null != nextChildren && ("production" !== process.env.NODE_ENV && this._contentDebugID && (ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID), this._contentDebugID = null), this.updateChildren(nextChildren, transaction, context)); }, getNativeNode: function() { return getNode(this); }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function(safely) { switch (this._tag) { case "iframe": case "object": case "img": case "form": case "video": case "audio": var listeners = this._wrapperState.listeners; if (listeners) for (var i = 0; i < listeners.length; i++) listeners[i].remove(); break; case "html": case "head": case "body": "production" !== process.env.NODE_ENV ? invariant(!1, "<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.", this._tag) : invariant(!1); } this.unmountChildren(safely), ReactDOMComponentTree.uncacheNode(this), EventPluginHub.deleteAllListeners(this), ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID), this._rootNodeID = null, this._domID = null, this._wrapperState = null, "production" !== process.env.NODE_ENV && this._contentDebugID && (ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID), this._contentDebugID = null); }, getPublicInstance: function() { return getNode(this); } }, _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin), module.exports = ReactDOMComponent; }).call(exports, __webpack_require__(17)); }, /* 80 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutoFocusUtils */ "use strict"; var ReactDOMComponentTree = __webpack_require__(38), focusNode = __webpack_require__(81), AutoFocusUtils = { focusDOMComponent: function() { focusNode(ReactDOMComponentTree.getNodeFromInstance(this)); } }; module.exports = AutoFocusUtils; }, /* 81 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ "use strict"; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; }, /* 82 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations */ "use strict"; var CSSProperty = __webpack_require__(83), ExecutionEnvironment = __webpack_require__(28), ReactInstrumentation = __webpack_require__(44), camelizeStyleName = __webpack_require__(84), dangerousStyleValue = __webpack_require__(86), hyphenateStyleName = __webpack_require__(87), memoizeStringOnly = __webpack_require__(89), warning = __webpack_require__(24), processStyleName = memoizeStringOnly(function(styleName) { return hyphenateStyleName(styleName); }), hasShorthandPropertyBug = !1, styleFloatAccessor = "cssFloat"; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement("div").style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ""; } catch (e) { hasShorthandPropertyBug = !0; } // IE8 only supports accessing cssFloat (standard) as styleFloat void 0 === document.documentElement.style.cssFloat && (styleFloatAccessor = "styleFloat"); } if ("production" !== process.env.NODE_ENV) // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/, badStyleValueWithSemicolonPattern = /;\s*$/, warnedStyleNames = {}, warnedStyleValues = {}, warnedForNaNValue = !1, warnHyphenatedStyleName = function(name, owner) { warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name] || (warnedStyleNames[name] = !0, "production" !== process.env.NODE_ENV ? warning(!1, "Unsupported style property %s. Did you mean %s?%s", name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0); }, warnBadVendoredStyleName = function(name, owner) { warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name] || (warnedStyleNames[name] = !0, "production" !== process.env.NODE_ENV ? warning(!1, "Unsupported vendor-prefixed style property %s. Did you mean %s?%s", name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0); }, warnStyleValueWithSemicolon = function(name, value, owner) { warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value] || (warnedStyleValues[value] = !0, "production" !== process.env.NODE_ENV ? warning(!1, 'Style property values shouldn\'t contain a semicolon.%s Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, "")) : void 0); }, warnStyleValueIsNaN = function(name, value, owner) { warnedForNaNValue || (warnedForNaNValue = !0, "production" !== process.env.NODE_ENV ? warning(!1, "`NaN` is an invalid value for the `%s` css style property.%s", name, checkRenderMessage(owner)) : void 0); }, checkRenderMessage = function(owner) { if (owner) { var name = owner.getName(); if (name) return " Check the render method of `" + name + "`."; } return ""; }, warnValidStyle = function(name, value, component) { var owner; component && (owner = component._currentElement._owner), name.indexOf("-") > -1 ? warnHyphenatedStyleName(name, owner) : badVendoredStyleNamePattern.test(name) ? warnBadVendoredStyleName(name, owner) : badStyleValueWithSemicolonPattern.test(value) && warnStyleValueWithSemicolon(name, value, owner), "number" == typeof value && isNaN(value) && warnStyleValueIsNaN(name, value, owner); }; /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function(styles, component) { var serialized = ""; for (var styleName in styles) if (styles.hasOwnProperty(styleName)) { var styleValue = styles[styleName]; "production" !== process.env.NODE_ENV && warnValidStyle(styleName, styleValue, component), null != styleValue && (serialized += processStyleName(styleName) + ":", serialized += dangerousStyleValue(styleName, styleValue, component) + ";"); } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function(node, styles, component) { "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(component._debugID, "update styles", styles); var style = node.style; for (var styleName in styles) if (styles.hasOwnProperty(styleName)) { "production" !== process.env.NODE_ENV && warnValidStyle(styleName, styles[styleName], component); var styleValue = dangerousStyleValue(styleName, styles[styleName], component); if ("float" !== styleName && "cssFloat" !== styleName || (styleName = styleFloatAccessor), styleValue) style[styleName] = styleValue; else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) style[individualStyleName] = ""; else style[styleName] = ""; } } } }; module.exports = CSSPropertyOperations; }).call(exports, __webpack_require__(17)); }, /* 83 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ "use strict"; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: !0, borderImageOutset: !0, borderImageSlice: !0, borderImageWidth: !0, boxFlex: !0, boxFlexGroup: !0, boxOrdinalGroup: !0, columnCount: !0, flex: !0, flexGrow: !0, flexPositive: !0, flexShrink: !0, flexNegative: !0, flexOrder: !0, gridRow: !0, gridColumn: !0, fontWeight: !0, lineClamp: !0, lineHeight: !0, opacity: !0, order: !0, orphans: !0, tabSize: !0, widows: !0, zIndex: !0, zoom: !0, // SVG-related properties fillOpacity: !0, floodOpacity: !0, stopOpacity: !0, strokeDasharray: !0, strokeDashoffset: !0, strokeMiterlimit: !0, strokeOpacity: !0, strokeWidth: !0 }, prefixes = [ "Webkit", "ms", "Moz", "O" ]; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function(prop) { prefixes.forEach(function(prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: !0, backgroundColor: !0, backgroundImage: !0, backgroundPositionX: !0, backgroundPositionY: !0, backgroundRepeat: !0 }, backgroundPosition: { backgroundPositionX: !0, backgroundPositionY: !0 }, border: { borderWidth: !0, borderStyle: !0, borderColor: !0 }, borderBottom: { borderBottomWidth: !0, borderBottomStyle: !0, borderBottomColor: !0 }, borderLeft: { borderLeftWidth: !0, borderLeftStyle: !0, borderLeftColor: !0 }, borderRight: { borderRightWidth: !0, borderRightStyle: !0, borderRightColor: !0 }, borderTop: { borderTopWidth: !0, borderTopStyle: !0, borderTopColor: !0 }, font: { fontStyle: !0, fontVariant: !0, fontWeight: !0, fontSize: !0, lineHeight: !0, fontFamily: !0 }, outline: { outlineWidth: !0, outlineStyle: !0, outlineColor: !0 } }, CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; }, /* 84 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ "use strict"; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, "ms-")); } var camelize = __webpack_require__(85), msPattern = /^-ms-/; module.exports = camelizeStyleName; }, /* 85 */ /***/ function(module, exports) { "use strict"; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function(_, character) { return character.toUpperCase(); }); } /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _hyphenPattern = /-(.)/g; module.exports = camelize; }, /* 86 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue */ "use strict"; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = null == value || "boolean" == typeof value || "" === value; if (isEmpty) return ""; var isNonNumeric = isNaN(value); if (isNonNumeric || 0 === value || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) return "" + value; if ("string" == typeof value) { if ("production" !== process.env.NODE_ENV && component) { var owner = component._currentElement._owner, ownerName = owner ? owner.getName() : null; ownerName && !styleWarnings[ownerName] && (styleWarnings[ownerName] = {}); var warned = !1; if (ownerName) { var warnings = styleWarnings[ownerName]; warned = warnings[name], warned || (warnings[name] = !0); } warned || ("production" !== process.env.NODE_ENV ? warning(!1, "a `%s` tag (owner: `%s`) was passed a numeric string value for CSS property `%s` (value: `%s`) which will be treated as a unitless number in a future version of React.", component._currentElement.type, ownerName || "unknown", name, value) : void 0); } value = value.trim(); } return value + "px"; } var CSSProperty = __webpack_require__(83), warning = __webpack_require__(24), isUnitlessNumber = CSSProperty.isUnitlessNumber, styleWarnings = {}; module.exports = dangerousStyleValue; }).call(exports, __webpack_require__(17)); }, /* 87 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ "use strict"; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, "-ms-"); } var hyphenate = __webpack_require__(88), msPattern = /^ms-/; module.exports = hyphenateStyleName; }, /* 88 */ /***/ function(module, exports) { "use strict"; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, "-$1").toLowerCase(); } /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; module.exports = hyphenate; }, /* 89 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @typechecks static-only */ "use strict"; /** * Memoizes the return value of a function that accepts one string argument. */ function memoizeStringOnly(callback) { var cache = {}; return function(string) { return cache.hasOwnProperty(string) || (cache[string] = callback.call(this, string)), cache[string]; }; } module.exports = memoizeStringOnly; }, /* 90 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations */ "use strict"; function isAttributeNameSafe(attributeName) { return validatedAttributeNameCache.hasOwnProperty(attributeName) ? !0 : illegalAttributeNameCache.hasOwnProperty(attributeName) ? !1 : VALID_ATTRIBUTE_NAME_REGEX.test(attributeName) ? (validatedAttributeNameCache[attributeName] = !0, !0) : (illegalAttributeNameCache[attributeName] = !0, "production" !== process.env.NODE_ENV ? warning(!1, "Invalid attribute name: `%s`", attributeName) : void 0, !1); } function shouldIgnoreValue(propertyInfo, value) { return null == value || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && 1 > value || propertyInfo.hasOverloadedBooleanValue && value === !1; } var DOMProperty = __webpack_require__(39), ReactDOMComponentTree = __webpack_require__(38), ReactDOMInstrumentation = __webpack_require__(91), ReactInstrumentation = __webpack_require__(44), quoteAttributeValueForBrowser = __webpack_require__(94), warning = __webpack_require__(24), VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + DOMProperty.ATTRIBUTE_NAME_START_CHAR + "][" + DOMProperty.ATTRIBUTE_NAME_CHAR + "]*$"), illegalAttributeNameCache = {}, validatedAttributeNameCache = {}, DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function(id) { return DOMProperty.ID_ATTRIBUTE_NAME + "=" + quoteAttributeValueForBrowser(id); }, setAttributeForID: function(node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function() { return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function(node) { node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, ""); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function(name, value) { "production" !== process.env.NODE_ENV && ReactDOMInstrumentation.debugTool.onCreateMarkupForProperty(name, value); var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) return ""; var attributeName = propertyInfo.attributeName; return propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === !0 ? attributeName + '=""' : attributeName + "=" + quoteAttributeValueForBrowser(value); } return DOMProperty.isCustomAttribute(name) ? null == value ? "" : name + "=" + quoteAttributeValueForBrowser(value) : null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function(name, value) { return isAttributeNameSafe(name) && null != value ? name + "=" + quoteAttributeValueForBrowser(value) : ""; }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function(node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) mutationMethod(node, value); else { if (shouldIgnoreValue(propertyInfo, value)) return void this.deleteValueForProperty(node, name); if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. propertyInfo.hasSideEffects && "" + node[propName] == "" + value || (// Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value); } else { var attributeName = propertyInfo.attributeName, namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. namespace ? node.setAttributeNS(namespace, attributeName, "" + value) : propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === !0 ? node.setAttribute(attributeName, "") : node.setAttribute(attributeName, "" + value); } } } else if (DOMProperty.isCustomAttribute(name)) return void DOMPropertyOperations.setValueForAttribute(node, name, value); if ("production" !== process.env.NODE_ENV) { ReactDOMInstrumentation.debugTool.onSetValueForProperty(node, name, value); var payload = {}; payload[name] = value, ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, "update attribute", payload); } }, setValueForAttribute: function(node, name, value) { if (isAttributeNameSafe(name) && (null == value ? node.removeAttribute(name) : node.setAttribute(name, "" + value), "production" !== process.env.NODE_ENV)) { var payload = {}; payload[name] = value, ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, "update attribute", payload); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function(node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) mutationMethod(node, void 0); else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; propertyInfo.hasBooleanValue ? // No HAS_SIDE_EFFECTS logic here, only `value` has it and is string. node[propName] = !1 : propertyInfo.hasSideEffects && "" + node[propName] == "" || (node[propName] = ""); } else node.removeAttribute(propertyInfo.attributeName); } else DOMProperty.isCustomAttribute(name) && node.removeAttribute(name); "production" !== process.env.NODE_ENV && (ReactDOMInstrumentation.debugTool.onDeleteValueForProperty(node, name), ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, "remove attribute", name)); } }; module.exports = DOMPropertyOperations; }).call(exports, __webpack_require__(17)); }, /* 91 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInstrumentation */ "use strict"; var ReactDOMDebugTool = __webpack_require__(92); module.exports = { debugTool: ReactDOMDebugTool }; }, /* 92 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMDebugTool */ "use strict"; function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) { "production" !== process.env.NODE_ENV && eventHandlers.forEach(function(handler) { try { handler[handlerFunctionName] && handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5); } catch (e) { "production" !== process.env.NODE_ENV ? warning(!handlerDoesThrowForEvent[handlerFunctionName], "exception thrown by devtool while handling %s: %s", handlerFunctionName, e.message) : void 0, handlerDoesThrowForEvent[handlerFunctionName] = !0; } }); } var ReactDOMUnknownPropertyDevtool = __webpack_require__(93), warning = __webpack_require__(24), eventHandlers = [], handlerDoesThrowForEvent = {}, ReactDOMDebugTool = { addDevtool: function(devtool) { eventHandlers.push(devtool); }, removeDevtool: function(devtool) { for (var i = 0; i < eventHandlers.length; i++) eventHandlers[i] === devtool && (eventHandlers.splice(i, 1), i--); }, onCreateMarkupForProperty: function(name, value) { emitEvent("onCreateMarkupForProperty", name, value); }, onSetValueForProperty: function(node, name, value) { emitEvent("onSetValueForProperty", node, name, value); }, onDeleteValueForProperty: function(node, name) { emitEvent("onDeleteValueForProperty", node, name); } }; ReactDOMDebugTool.addDevtool(ReactDOMUnknownPropertyDevtool), module.exports = ReactDOMDebugTool; }).call(exports, __webpack_require__(17)); }, /* 93 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMUnknownPropertyDevtool */ "use strict"; var DOMProperty = __webpack_require__(39), EventPluginRegistry = __webpack_require__(21), warning = __webpack_require__(24); if ("production" !== process.env.NODE_ENV) var reactProps = { children: !0, dangerouslySetInnerHTML: !0, key: !0, ref: !0 }, warnedProperties = {}, warnUnknownProperty = function(name) { if (!DOMProperty.properties.hasOwnProperty(name) && !DOMProperty.isCustomAttribute(name) && !(reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name])) { warnedProperties[name] = !0; var lowerCasedName = name.toLowerCase(), standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; "production" !== process.env.NODE_ENV ? warning(null == standardName, "Unknown DOM property %s. Did you mean %s?", name, standardName) : void 0; var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null; "production" !== process.env.NODE_ENV ? warning(null == registrationName, "Unknown event handler property %s. Did you mean `%s`?", name, registrationName) : void 0; } }; var ReactDOMUnknownPropertyDevtool = { onCreateMarkupForProperty: function(name, value) { warnUnknownProperty(name); }, onSetValueForProperty: function(node, name, value) { warnUnknownProperty(name); }, onDeleteValueForProperty: function(node, name) { warnUnknownProperty(name); } }; module.exports = ReactDOMUnknownPropertyDevtool; }).call(exports, __webpack_require__(17)); }, /* 94 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule quoteAttributeValueForBrowser */ "use strict"; /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } var escapeTextContentForBrowser = __webpack_require__(71); module.exports = quoteAttributeValueForBrowser; }, /* 95 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter */ "use strict"; function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. return Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey) || (mountAt[topListenersIDKey] = reactTopListenersCounter++, alreadyListeningTo[mountAt[topListenersIDKey]] = {}), alreadyListeningTo[mountAt[topListenersIDKey]]; } var hasEventPageXY, _assign = __webpack_require__(30), EventConstants = __webpack_require__(15), EventPluginRegistry = __webpack_require__(21), ReactEventEmitterMixin = __webpack_require__(96), ViewportMetrics = __webpack_require__(62), getVendorPrefixedEventName = __webpack_require__(97), isEventSupported = __webpack_require__(56), alreadyListeningTo = {}, isMonitoringScrollValue = !1, reactTopListenersCounter = 0, topEventMapping = { topAbort: "abort", topAnimationEnd: getVendorPrefixedEventName("animationend") || "animationend", topAnimationIteration: getVendorPrefixedEventName("animationiteration") || "animationiteration", topAnimationStart: getVendorPrefixedEventName("animationstart") || "animationstart", topBlur: "blur", topCanPlay: "canplay", topCanPlayThrough: "canplaythrough", topChange: "change", topClick: "click", topCompositionEnd: "compositionend", topCompositionStart: "compositionstart", topCompositionUpdate: "compositionupdate", topContextMenu: "contextmenu", topCopy: "copy", topCut: "cut", topDoubleClick: "dblclick", topDrag: "drag", topDragEnd: "dragend", topDragEnter: "dragenter", topDragExit: "dragexit", topDragLeave: "dragleave", topDragOver: "dragover", topDragStart: "dragstart", topDrop: "drop", topDurationChange: "durationchange", topEmptied: "emptied", topEncrypted: "encrypted", topEnded: "ended", topError: "error", topFocus: "focus", topInput: "input", topKeyDown: "keydown", topKeyPress: "keypress", topKeyUp: "keyup", topLoadedData: "loadeddata", topLoadedMetadata: "loadedmetadata", topLoadStart: "loadstart", topMouseDown: "mousedown", topMouseMove: "mousemove", topMouseOut: "mouseout", topMouseOver: "mouseover", topMouseUp: "mouseup", topPaste: "paste", topPause: "pause", topPlay: "play", topPlaying: "playing", topProgress: "progress", topRateChange: "ratechange", topScroll: "scroll", topSeeked: "seeked", topSeeking: "seeking", topSelectionChange: "selectionchange", topStalled: "stalled", topSuspend: "suspend", topTextInput: "textInput", topTimeUpdate: "timeupdate", topTouchCancel: "touchcancel", topTouchEnd: "touchend", topTouchMove: "touchmove", topTouchStart: "touchstart", topTransitionEnd: getVendorPrefixedEventName("transitionend") || "transitionend", topVolumeChange: "volumechange", topWaiting: "waiting", topWheel: "wheel" }, topListenersIDKey = "_reactListenersID" + String(Math.random()).slice(2), ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function(ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel), ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !(!ReactBrowserEventEmitter.ReactEventListener || !ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function(registrationName, contentDocumentHandle) { for (var mountAt = contentDocumentHandle, isListening = getListeningForDocument(mountAt), dependencies = EventPluginRegistry.registrationNameDependencies[registrationName], topLevelTypes = EventConstants.topLevelTypes, i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; isListening.hasOwnProperty(dependency) && isListening[dependency] || (dependency === topLevelTypes.topWheel ? isEventSupported("wheel") ? ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, "wheel", mountAt) : isEventSupported("mousewheel") ? ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, "mousewheel", mountAt) : ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, "DOMMouseScroll", mountAt) : dependency === topLevelTypes.topScroll ? isEventSupported("scroll", !0) ? ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, "scroll", mountAt) : ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, "scroll", ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE) : dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur ? (isEventSupported("focus", !0) ? (ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, "focus", mountAt), ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, "blur", mountAt)) : isEventSupported("focusin") && (ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, "focusin", mountAt), ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, "focusout", mountAt)), isListening[topLevelTypes.topBlur] = !0, isListening[topLevelTypes.topFocus] = !0) : topEventMapping.hasOwnProperty(dependency) && ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt), isListening[dependency] = !0); } }, trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when * pageX/pageY isn't supported (legacy browsers). * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function() { if (void 0 === hasEventPageXY && (hasEventPageXY = document.createEvent && "pageX" in document.createEvent("MouseEvent")), !hasEventPageXY && !isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh), isMonitoringScrollValue = !0; } } }); module.exports = ReactBrowserEventEmitter; }, /* 96 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ "use strict"; function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events), EventPluginHub.processEventQueue(!1); } var EventPluginHub = __webpack_require__(20), ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; }, /* 97 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getVendorPrefixedEventName */ "use strict"; /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; return prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(), prefixes["Webkit" + styleProp] = "webkit" + eventName, prefixes["Moz" + styleProp] = "moz" + eventName, prefixes["ms" + styleProp] = "MS" + eventName, prefixes["O" + styleProp] = "o" + eventName.toLowerCase(), prefixes; } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) return prefixedEventNames[eventName]; if (!vendorPrefixes[eventName]) return eventName; var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) return prefixedEventNames[eventName] = prefixMap[styleProp]; return ""; } var ExecutionEnvironment = __webpack_require__(28), vendorPrefixes = { animationend: makePrefixMap("Animation", "AnimationEnd"), animationiteration: makePrefixMap("Animation", "AnimationIteration"), animationstart: makePrefixMap("Animation", "AnimationStart"), transitionend: makePrefixMap("Transition", "TransitionEnd") }, prefixedEventNames = {}, style = {}; /** * Bootstrap if a DOM exists. */ ExecutionEnvironment.canUseDOM && (style = document.createElement("div").style, "AnimationEvent" in window || (delete vendorPrefixes.animationend.animation, delete vendorPrefixes.animationiteration.animation, delete vendorPrefixes.animationstart.animation), "TransitionEvent" in window || delete vendorPrefixes.transitionend.transition), module.exports = getVendorPrefixedEventName; }, /* 98 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ "use strict"; var DisabledInputUtils = __webpack_require__(99), ReactDOMButton = { getNativeProps: DisabledInputUtils.getNativeProps }; module.exports = ReactDOMButton; }, /* 99 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DisabledInputUtils */ "use strict"; var disableableMouseListenerNames = { onClick: !0, onDoubleClick: !0, onMouseDown: !0, onMouseMove: !0, onMouseUp: !0, onClickCapture: !0, onDoubleClickCapture: !0, onMouseDownCapture: !0, onMouseMoveCapture: !0, onMouseUpCapture: !0 }, DisabledInputUtils = { getNativeProps: function(inst, props) { if (!props.disabled) return props; // Copy the props, except the mouse listeners var nativeProps = {}; for (var key in props) !disableableMouseListenerNames[key] && props.hasOwnProperty(key) && (nativeProps[key] = props[key]); return nativeProps; } }; module.exports = DisabledInputUtils; }, /* 100 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ "use strict"; function forceUpdateIfMounted() { this._rootNodeID && // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } function warnIfValueIsNull(props) { null == props || null !== props.value || didWarnValueNull || ("production" !== process.env.NODE_ENV ? warning(!1, "`value` prop on `input` should not be null. Consider using the empty string to clear the component or `undefined` for uncontrolled components.") : void 0, didWarnValueNull = !0); } function _handleChange(event) { var props = this._currentElement.props, returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if ("radio" === props.type && null != name) { for (var rootNode = ReactDOMComponentTree.getNodeFromInstance(this), queryRoot = rootNode; queryRoot.parentNode; ) queryRoot = queryRoot.parentNode; for (var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]'), i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode !== rootNode && otherNode.form === rootNode.form) { // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode); otherInstance ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.") : invariant(!1), // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } } return returnValue; } var _assign = __webpack_require__(30), DisabledInputUtils = __webpack_require__(99), DOMPropertyOperations = __webpack_require__(90), LinkedValueUtils = __webpack_require__(101), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), invariant = __webpack_require__(18), warning = __webpack_require__(24), didWarnValueLink = !1, didWarnCheckedLink = !1, didWarnValueNull = !1, didWarnValueDefaultValue = !1, didWarnCheckedDefaultChecked = !1, didWarnControlledToUncontrolled = !1, didWarnUncontrolledToControlled = !1, ReactDOMInput = { getNativeProps: function(inst, props) { var value = LinkedValueUtils.getValue(props), checked = LinkedValueUtils.getChecked(props), nativeProps = _assign({ // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type: void 0 }, DisabledInputUtils.getNativeProps(inst, props), { defaultChecked: void 0, defaultValue: void 0, value: null != value ? value : inst._wrapperState.initialValue, checked: null != checked ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function(inst, props) { if ("production" !== process.env.NODE_ENV) { LinkedValueUtils.checkPropTypes("input", props, inst._currentElement._owner); var owner = inst._currentElement._owner; void 0 === props.valueLink || didWarnValueLink || ("production" !== process.env.NODE_ENV ? warning(!1, "`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.") : void 0, didWarnValueLink = !0), void 0 === props.checkedLink || didWarnCheckedLink || ("production" !== process.env.NODE_ENV ? warning(!1, "`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.") : void 0, didWarnCheckedLink = !0), void 0 === props.checked || void 0 === props.defaultChecked || didWarnCheckedDefaultChecked || ("production" !== process.env.NODE_ENV ? warning(!1, "%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://fb.me/react-controlled-components", owner && owner.getName() || "A component", props.type) : void 0, didWarnCheckedDefaultChecked = !0), void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue || ("production" !== process.env.NODE_ENV ? warning(!1, "%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://fb.me/react-controlled-components", owner && owner.getName() || "A component", props.type) : void 0, didWarnValueDefaultValue = !0), warnIfValueIsNull(props); } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.defaultChecked || !1, initialValue: null != defaultValue ? defaultValue : null, listeners: null, onChange: _handleChange.bind(inst) }, "production" !== process.env.NODE_ENV && (inst._wrapperState.controlled = void 0 !== props.checked || void 0 !== props.value); }, updateWrapper: function(inst) { var props = inst._currentElement.props; if ("production" !== process.env.NODE_ENV) { warnIfValueIsNull(props); var initialValue = inst._wrapperState.initialChecked || inst._wrapperState.initialValue, defaultValue = props.defaultChecked || props.defaultValue, controlled = void 0 !== props.checked || void 0 !== props.value, owner = inst._currentElement._owner; !initialValue && inst._wrapperState.controlled || !controlled || didWarnUncontrolledToControlled || ("production" !== process.env.NODE_ENV ? warning(!1, "%s is changing an uncontrolled input of type %s to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components", owner && owner.getName() || "A component", props.type) : void 0, didWarnUncontrolledToControlled = !0), !inst._wrapperState.controlled || !defaultValue && controlled || didWarnControlledToUncontrolled || ("production" !== process.env.NODE_ENV ? warning(!1, "%s is changing a controlled input of type %s to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components", owner && owner.getName() || "A component", props.type) : void 0, didWarnControlledToUncontrolled = !0); } // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; null != checked && DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), "checked", checked || !1); var value = LinkedValueUtils.getValue(props); null != value && // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), "value", "" + value); } }; module.exports = ReactDOMInput; }).call(exports, __webpack_require__(17)); }, /* 101 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils */ "use strict"; function _assertSingleLink(inputProps) { null != inputProps.checkedLink && null != inputProps.valueLink ? "production" !== process.env.NODE_ENV ? invariant(!1, "Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don't want to use valueLink and vice versa.") : invariant(!1) : void 0; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps), null != inputProps.value || null != inputProps.onChange ? "production" !== process.env.NODE_ENV ? invariant(!1, "Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don't want to use valueLink.") : invariant(!1) : void 0; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps), null != inputProps.checked || null != inputProps.onChange ? "production" !== process.env.NODE_ENV ? invariant(!1, "Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don't want to use checkedLink") : invariant(!1) : void 0; } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) return " Check the render method of `" + name + "`."; } return ""; } var ReactPropTypes = __webpack_require__(102), ReactPropTypeLocations = __webpack_require__(108), invariant = __webpack_require__(18), warning = __webpack_require__(24), hasReadOnlyValue = { button: !0, checkbox: !0, image: !0, hidden: !0, radio: !0, reset: !0, submit: !0 }, propTypes = { value: function(props, propName, componentName) { return !props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled ? null : new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."); }, checked: function(props, propName, componentName) { return !props[propName] || props.onChange || props.readOnly || props.disabled ? null : new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."); }, onChange: ReactPropTypes.func }, loggedTypeFailures = {}, LinkedValueUtils = { checkPropTypes: function(tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = !0; var addendum = getDeclarationErrorAddendum(owner); "production" !== process.env.NODE_ENV ? warning(!1, "Failed form propType: %s%s", error.message, addendum) : void 0; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function(inputProps) { return inputProps.valueLink ? (_assertValueLink(inputProps), inputProps.valueLink.value) : inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function(inputProps) { return inputProps.checkedLink ? (_assertCheckedLink(inputProps), inputProps.checkedLink.value) : inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function(inputProps, event) { return inputProps.valueLink ? (_assertValueLink(inputProps), inputProps.valueLink.requestChange(event.target.value)) : inputProps.checkedLink ? (_assertCheckedLink(inputProps), inputProps.checkedLink.requestChange(event.target.checked)) : inputProps.onChange ? inputProps.onChange.call(void 0, event) : void 0; } }; module.exports = LinkedValueUtils; }).call(exports, __webpack_require__(17)); }, /* 102 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ "use strict"; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm // SameValue algorithm return x === y ? 0 !== x || 1 / x === 1 / y : x !== x && y !== y; } /*eslint-enable no-self-compare*/ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { if (componentName = componentName || ANONYMOUS, propFullName = propFullName || propName, null == props[propName]) { var locationName = ReactPropTypeLocationNames[location]; return isRequired ? new Error("Required " + locationName + " `" + propFullName + "` was not specified in " + ("`" + componentName + "`.")) : null; } return validate(props, propName, componentName, location, propFullName); } var chainedCheckType = checkType.bind(null, !1); return chainedCheckType.isRequired = checkType.bind(null, !0), chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName], propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location], preciseType = getPreciseType(propValue); return new Error("Invalid " + locationName + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`.")); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if ("function" != typeof typeChecker) return new Error("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf."); var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location], propType = getPropType(propValue); return new Error("Invalid " + locationName + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array.")); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + "[" + i + "]"); if (error instanceof Error) return error; } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error("Invalid " + locationName + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a single ReactElement.")); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location], expectedClassName = expectedClass.name || ANONYMOUS, actualClassName = getClassName(props[propName]); return new Error("Invalid " + locationName + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`.")); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { function validate(props, propName, componentName, location, propFullName) { for (var propValue = props[propName], i = 0; i < expectedValues.length; i++) if (is(propValue, expectedValues[i])) return null; var locationName = ReactPropTypeLocationNames[location], valuesString = JSON.stringify(expectedValues); return new Error("Invalid " + locationName + " `" + propFullName + "` of value `" + propValue + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + ".")); } return createChainableTypeChecker(Array.isArray(expectedValues) ? validate : function() { return new Error("Invalid argument supplied to oneOf, expected an instance of array."); }); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if ("function" != typeof typeChecker) return new Error("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf."); var propValue = props[propName], propType = getPropType(propValue); if ("object" !== propType) { var locationName = ReactPropTypeLocationNames[location]; return new Error("Invalid " + locationName + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object.")); } for (var key in propValue) if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + "." + key); if (error instanceof Error) return error; } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (null == checker(props, propName, componentName, location, propFullName)) return null; } var locationName = ReactPropTypeLocationNames[location]; return new Error("Invalid " + locationName + " `" + propFullName + "` supplied to " + ("`" + componentName + "`.")); } return createChainableTypeChecker(Array.isArray(arrayOfTypeCheckers) ? validate : function() { return new Error("Invalid argument supplied to oneOfType, expected an instance of array."); }); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error("Invalid " + locationName + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode.")); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName], propType = getPropType(propValue); if ("object" !== propType) { var locationName = ReactPropTypeLocationNames[location]; return new Error("Invalid " + locationName + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`.")); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (checker) { var error = checker(propValue, key, componentName, location, propFullName + "." + key); if (error) return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case "number": case "string": case "undefined": return !0; case "boolean": return !propValue; case "object": if (Array.isArray(propValue)) return propValue.every(isNode); if (null === propValue || ReactElement.isValidElement(propValue)) return !0; var iteratorFn = getIteratorFn(propValue); if (!iteratorFn) return !1; var step, iterator = iteratorFn.call(propValue); if (iteratorFn !== propValue.entries) { for (;!(step = iterator.next()).done; ) if (!isNode(step.value)) return !1; } else // Iterator will provide entry [k,v] tuples rather than values. for (;!(step = iterator.next()).done; ) { var entry = step.value; if (entry && !isNode(entry[1])) return !1; } return !0; default: return !1; } } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; return Array.isArray(propValue) ? "array" : propValue instanceof RegExp ? "object" : propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if ("object" === propType) { if (propValue instanceof Date) return "date"; if (propValue instanceof RegExp) return "regexp"; } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { return propValue.constructor && propValue.constructor.name ? propValue.constructor.name : ANONYMOUS; } var ReactElement = __webpack_require__(103), ReactPropTypeLocationNames = __webpack_require__(106), emptyFunction = __webpack_require__(25), getIteratorFn = __webpack_require__(107), ANONYMOUS = "<<anonymous>>", ReactPropTypes = { array: createPrimitiveTypeChecker("array"), bool: createPrimitiveTypeChecker("boolean"), func: createPrimitiveTypeChecker("function"), number: createPrimitiveTypeChecker("number"), object: createPrimitiveTypeChecker("object"), string: createPrimitiveTypeChecker("string"), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; module.exports = ReactPropTypes; }, /* 103 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ "use strict"; var specialPropKeyWarningShown, specialPropRefWarningShown, _assign = __webpack_require__(30), ReactCurrentOwner = __webpack_require__(104), warning = __webpack_require__(24), canDefineProperty = __webpack_require__(105), REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103, RESERVED_PROPS = { key: !0, ref: !0, __self: !0, __source: !0 }, ReactElement = function(type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. // self and source are DEV only properties. // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. return "production" !== process.env.NODE_ENV && (element._store = {}, canDefineProperty ? (Object.defineProperty(element._store, "validated", { configurable: !1, enumerable: !1, writable: !0, value: !1 }), Object.defineProperty(element, "_self", { configurable: !1, enumerable: !1, writable: !1, value: self }), Object.defineProperty(element, "_source", { configurable: !1, enumerable: !1, writable: !1, value: source })) : (element._store.validated = !1, element._self = self, element._source = source), Object.freeze && (Object.freeze(element.props), Object.freeze(element))), element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ ReactElement.createElement = function(type, config, children) { var propName, props = {}, key = null, ref = null, self = null, source = null; if (null != config) { "production" !== process.env.NODE_ENV ? ("production" !== process.env.NODE_ENV ? warning(null == config.__proto__ || config.__proto__ === Object.prototype, "React.createElement(...): Expected props argument to be a plain object. Properties defined in its prototype chain will be ignored.") : void 0, ref = !config.hasOwnProperty("ref") || Object.getOwnPropertyDescriptor(config, "ref").get ? null : config.ref, key = !config.hasOwnProperty("key") || Object.getOwnPropertyDescriptor(config, "key").get ? null : "" + config.key) : (ref = void 0 === config.ref ? null : config.ref, key = void 0 === config.key ? null : "" + config.key), self = void 0 === config.__self ? null : config.__self, source = void 0 === config.__source ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName) && (props[propName] = config[propName]); } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (1 === childrenLength) props.children = children; else if (childrenLength > 1) { for (var childArray = Array(childrenLength), i = 0; childrenLength > i; i++) childArray[i] = arguments[i + 2]; props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) void 0 === props[propName] && (props[propName] = defaultProps[propName]); } // Create dummy `key` and `ref` property to `props` to warn users // against its use return "production" !== process.env.NODE_ENV && ("undefined" != typeof props.$$typeof && props.$$typeof === REACT_ELEMENT_TYPE || (props.hasOwnProperty("key") || Object.defineProperty(props, "key", { get: function() { specialPropKeyWarningShown || (specialPropKeyWarningShown = !0, "production" !== process.env.NODE_ENV ? warning(!1, "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)", "function" == typeof type && "displayName" in type ? type.displayName : "Element") : void 0); }, configurable: !0 }), props.hasOwnProperty("ref") || Object.defineProperty(props, "ref", { get: function() { specialPropRefWarningShown || (specialPropRefWarningShown = !0, "production" !== process.env.NODE_ENV ? warning(!1, "%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)", "function" == typeof type && "displayName" in type ? type.displayName : "Element") : void 0); }, configurable: !0 }))), ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }, /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed return factory.type = type, factory; }, ReactElement.cloneAndReplaceKey = function(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }, /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ ReactElement.cloneElement = function(element, config, children) { var propName, props = _assign({}, element.props), key = element.key, ref = element.ref, self = element._self, source = element._source, owner = element._owner; if (null != config) { "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null == config.__proto__ || config.__proto__ === Object.prototype, "React.cloneElement(...): Expected props argument to be a plain object. Properties defined in its prototype chain will be ignored.") : void 0), void 0 !== config.ref && (ref = config.ref, owner = ReactCurrentOwner.current), void 0 !== config.key && (key = "" + config.key); // Remaining properties override existing props var defaultProps; element.type && element.type.defaultProps && (defaultProps = element.type.defaultProps); for (propName in config) config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName) && (void 0 === config[propName] && void 0 !== defaultProps ? props[propName] = defaultProps[propName] : props[propName] = config[propName]); } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (1 === childrenLength) props.children = children; else if (childrenLength > 1) { for (var childArray = Array(childrenLength), i = 0; childrenLength > i; i++) childArray[i] = arguments[i + 2]; props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }, /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { return "object" == typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE; }, module.exports = ReactElement; }).call(exports, __webpack_require__(17)); }, /* 104 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ "use strict"; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; }, /* 105 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule canDefineProperty */ "use strict"; var canDefineProperty = !1; if ("production" !== process.env.NODE_ENV) try { Object.defineProperty({}, "x", { get: function() {} }), canDefineProperty = !0; } catch (x) {} module.exports = canDefineProperty; }).call(exports, __webpack_require__(17)); }, /* 106 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ "use strict"; var ReactPropTypeLocationNames = {}; "production" !== process.env.NODE_ENV && (ReactPropTypeLocationNames = { prop: "prop", context: "context", childContext: "child context" }), module.exports = ReactPropTypeLocationNames; }).call(exports, __webpack_require__(17)); }, /* 107 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getIteratorFn */ "use strict"; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); return "function" == typeof iteratorFn ? iteratorFn : void 0; } /* global Symbol */ var ITERATOR_SYMBOL = "function" == typeof Symbol && Symbol.iterator, FAUX_ITERATOR_SYMBOL = "@@iterator"; module.exports = getIteratorFn; }, /* 108 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ "use strict"; var keyMirror = __webpack_require__(16), ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; }, /* 109 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ "use strict"; var _assign = __webpack_require__(30), ReactChildren = __webpack_require__(110), ReactDOMComponentTree = __webpack_require__(38), ReactDOMSelect = __webpack_require__(113), warning = __webpack_require__(24), ReactDOMOption = { mountWrapper: function(inst, props, nativeParent) { // TODO (yungsters): Remove support for `selected` in <option>. "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null == props.selected, "Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.") : void 0); // Look up whether this option is 'selected' var selectValue = null; if (null != nativeParent) { var selectParent = nativeParent; "optgroup" === selectParent._tag && (selectParent = selectParent._nativeParent), null != selectParent && "select" === selectParent._tag && (selectValue = ReactDOMSelect.getSelectValueContext(selectParent)); } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (null != selectValue) if (selected = !1, Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) if ("" + selectValue[i] == "" + props.value) { selected = !0; break; } } else selected = "" + selectValue == "" + props.value; inst._wrapperState = { selected: selected }; }, postMountWrapper: function(inst) { // value="" should make a value attribute (#6219) var props = inst._currentElement.props; if (null != props.value) { var node = ReactDOMComponentTree.getNodeFromInstance(inst); node.setAttribute("value", props.value); } }, getNativeProps: function(inst, props) { var nativeProps = _assign({ selected: void 0, children: void 0 }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering null != inst._wrapperState.selected && (nativeProps.selected = inst._wrapperState.selected); var content = ""; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. return ReactChildren.forEach(props.children, function(child) { null != child && ("string" == typeof child || "number" == typeof child ? content += child : "production" !== process.env.NODE_ENV ? warning(!1, "Only strings and numbers are supported as <option> children.") : void 0); }), content && (nativeProps.children = content), nativeProps; } }; module.exports = ReactDOMOption; }).call(exports, __webpack_require__(17)); }, /* 110 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ "use strict"; function escapeUserProvidedKey(text) { return ("" + text).replace(userProvidedKeyEscapeRegex, "$&/"); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction, this.context = forEachContext, this.count = 0; } function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (null == children) return children; var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext), ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult, this.keyPrefix = keyPrefix, this.func = mapFunction, this.context = mapContext, this.count = 0; } function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context, mappedChild = func.call(context, child, bookKeeping.count++); Array.isArray(mappedChild) ? mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument) : null != mappedChild && (ReactElement.isValidElement(mappedChild) && (mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (!mappedChild.key || child && child.key === mappedChild.key ? "" : escapeUserProvidedKey(mappedChild.key) + "/") + childKey)), result.push(mappedChild)); } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ""; null != prefix && (escapedPrefix = escapeUserProvidedKey(prefix) + "/"); var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext), MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (null == children) return children; var result = []; return mapIntoWithKeyPrefixInternal(children, result, null, func, context), result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ function toArray(children) { var result = []; return mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument), result; } var PooledClass = __webpack_require__(31), ReactElement = __webpack_require__(103), emptyFunction = __webpack_require__(25), traverseAllChildren = __webpack_require__(111), twoArgumentPooler = PooledClass.twoArgumentPooler, fourArgumentPooler = PooledClass.fourArgumentPooler, userProvidedKeyEscapeRegex = /\/+/g; ForEachBookKeeping.prototype.destructor = function() { this.func = null, this.context = null, this.count = 0; }, PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler), MapBookKeeping.prototype.destructor = function() { this.result = null, this.keyPrefix = null, this.func = null, this.context = null, this.count = 0; }, PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; }, /* 111 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ "use strict"; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. return component && "object" == typeof component && null != component.key ? KeyEscapeUtils.escape(component.key) : index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if ("undefined" !== type && "boolean" !== type || (// All of the above are perceived as null. children = null), null === children || "string" === type || "number" === type || ReactElement.isValidElement(children)) // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. return callback(traverseContext, children, "" === nameSoFar ? SEPARATOR + getComponentKey(children, 0) : nameSoFar), 1; var child, nextName, subtreeCount = 0, nextNamePrefix = "" === nameSoFar ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) for (var i = 0; i < children.length; i++) child = children[i], nextName = nextNamePrefix + getComponentKey(child, i), subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var step, iterator = iteratorFn.call(children); if (iteratorFn !== children.entries) for (var ii = 0; !(step = iterator.next()).done; ) child = step.value, nextName = nextNamePrefix + getComponentKey(child, ii++), subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); else // Iterator will provide entry [k,v] tuples rather than values. for ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(didWarnAboutMaps, "Using Maps as children is not yet fully supported. It is an experimental feature that might be removed. Convert it to a sequence / iterable of keyed ReactElements instead.") : void 0, didWarnAboutMaps = !0); !(step = iterator.next()).done; ) { var entry = step.value; entry && (child = entry[1], nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0), subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext)); } } else if ("object" === type) { var addendum = ""; if ("production" !== process.env.NODE_ENV && (addendum = " If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.", children._isReactElement && (addendum = " It looks like you're using an element created by a different version of React. Make sure to use only one copy of React."), ReactCurrentOwner.current)) { var name = ReactCurrentOwner.current.getName(); name && (addendum += " Check the render method of `" + name + "`."); } var childrenString = String(children); "production" !== process.env.NODE_ENV ? invariant(!1, "Objects are not valid as a React child (found: %s).%s", "[object Object]" === childrenString ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString, addendum) : invariant(!1); } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { return null == children ? 0 : traverseAllChildrenImpl(children, "", callback, traverseContext); } var ReactCurrentOwner = __webpack_require__(104), ReactElement = __webpack_require__(103), getIteratorFn = __webpack_require__(107), invariant = __webpack_require__(18), KeyEscapeUtils = __webpack_require__(112), warning = __webpack_require__(24), SEPARATOR = ".", SUBSEPARATOR = ":", didWarnAboutMaps = !1; module.exports = traverseAllChildren; }).call(exports, __webpack_require__(17)); }, /* 112 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule KeyEscapeUtils */ "use strict"; /** * Escape and wrap key so it is safe to use as a reactid * * @param {*} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g, escaperLookup = { "=": "=0", ":": "=2" }, escapedString = ("" + key).replace(escapeRegex, function(match) { return escaperLookup[match]; }); return "$" + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g, unescaperLookup = { "=0": "=", "=2": ":" }, keySubstring = "." === key[0] && "$" === key[1] ? key.substring(2) : key.substring(1); return ("" + keySubstring).replace(unescapeRegex, function(match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; }, /* 113 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ "use strict"; function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = !1; var props = this._currentElement.props, value = LinkedValueUtils.getValue(props); null != value && updateOptions(this, Boolean(props.multiple), value); } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) return " Check the render method of `" + name + "`."; } return ""; } function warnIfValueIsNull(props) { null == props || null !== props.value || didWarnValueNull || ("production" !== process.env.NODE_ENV ? warning(!1, "`value` prop on `select` should not be null. Consider using the empty string to clear the component or `undefined` for uncontrolled components.") : void 0, didWarnValueNull = !0); } /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes("select", props, owner), void 0 === props.valueLink || didWarnValueLink || ("production" !== process.env.NODE_ENV ? warning(!1, "`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.") : void 0, didWarnValueLink = !0); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; null != props[propName] && (props.multiple ? "production" !== process.env.NODE_ENV ? warning(Array.isArray(props[propName]), "The `%s` prop supplied to <select> must be an array if `multiple` is true.%s", propName, getDeclarationErrorAddendum(owner)) : void 0 : "production" !== process.env.NODE_ENV ? warning(!Array.isArray(props[propName]), "The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s", propName, getDeclarationErrorAddendum(owner)) : void 0); } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i, options = ReactDOMComponentTree.getNodeFromInstance(inst).options; if (multiple) { for (selectedValue = {}, i = 0; i < propValue.length; i++) selectedValue["" + propValue[i]] = !0; for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); options[i].selected !== selected && (options[i].selected = selected); } } else { for (selectedValue = "" + propValue, i = 0; i < options.length; i++) if (options[i].value === selectedValue) return void (options[i].selected = !0); options.length && (options[0].selected = !0); } } function _handleChange(event) { var props = this._currentElement.props, returnValue = LinkedValueUtils.executeOnChange(props, event); return this._rootNodeID && (this._wrapperState.pendingUpdate = !0), ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this), returnValue; } var _assign = __webpack_require__(30), DisabledInputUtils = __webpack_require__(99), LinkedValueUtils = __webpack_require__(101), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), warning = __webpack_require__(24), didWarnValueLink = !1, didWarnValueNull = !1, didWarnValueDefaultValue = !1, valuePropNames = [ "value", "defaultValue" ], ReactDOMSelect = { getNativeProps: function(inst, props) { return _assign({}, DisabledInputUtils.getNativeProps(inst, props), { onChange: inst._wrapperState.onChange, value: void 0 }); }, mountWrapper: function(inst, props) { "production" !== process.env.NODE_ENV && (checkSelectPropTypes(inst, props), warnIfValueIsNull(props)); var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: !1, initialValue: null != value ? value : props.defaultValue, listeners: null, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }, void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue || ("production" !== process.env.NODE_ENV ? warning(!1, "Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://fb.me/react-controlled-components") : void 0, didWarnValueDefaultValue = !0); }, getSelectValueContext: function(inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function(inst) { var props = inst._currentElement.props; "production" !== process.env.NODE_ENV && warnIfValueIsNull(props), // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = void 0; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); null != value ? (inst._wrapperState.pendingUpdate = !1, updateOptions(inst, Boolean(props.multiple), value)) : wasMultiple !== Boolean(props.multiple) && (// For simplicity, reapply `defaultValue` if `multiple` is toggled. null != props.defaultValue ? updateOptions(inst, Boolean(props.multiple), props.defaultValue) : updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : "")); } }; module.exports = ReactDOMSelect; }).call(exports, __webpack_require__(17)); }, /* 114 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ "use strict"; function forceUpdateIfMounted() { this._rootNodeID && // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } function warnIfValueIsNull(props) { null == props || null !== props.value || didWarnValueNull || ("production" !== process.env.NODE_ENV ? warning(!1, "`value` prop on `textarea` should not be null. Consider using the empty string to clear the component or `undefined` for uncontrolled components.") : void 0, didWarnValueNull = !0); } function _handleChange(event) { var props = this._currentElement.props, returnValue = LinkedValueUtils.executeOnChange(props, event); return ReactUpdates.asap(forceUpdateIfMounted, this), returnValue; } var _assign = __webpack_require__(30), DisabledInputUtils = __webpack_require__(99), DOMPropertyOperations = __webpack_require__(90), LinkedValueUtils = __webpack_require__(101), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), invariant = __webpack_require__(18), warning = __webpack_require__(24), didWarnValueLink = !1, didWarnValueNull = !1, didWarnValDefaultVal = !1, ReactDOMTextarea = { getNativeProps: function(inst, props) { null != props.dangerouslySetInnerHTML ? "production" !== process.env.NODE_ENV ? invariant(!1, "`dangerouslySetInnerHTML` does not make sense on <textarea>.") : invariant(!1) : void 0; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. var nativeProps = _assign({}, DisabledInputUtils.getNativeProps(inst, props), { defaultValue: void 0, value: void 0, children: inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function(inst, props) { "production" !== process.env.NODE_ENV && (LinkedValueUtils.checkPropTypes("textarea", props, inst._currentElement._owner), void 0 === props.valueLink || didWarnValueLink || ("production" !== process.env.NODE_ENV ? warning(!1, "`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.") : void 0, didWarnValueLink = !0), void 0 === props.value || void 0 === props.defaultValue || didWarnValDefaultVal || ("production" !== process.env.NODE_ENV ? warning(!1, "Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://fb.me/react-controlled-components") : void 0, didWarnValDefaultVal = !0), warnIfValueIsNull(props)); var defaultValue = props.defaultValue, children = props.children; null != children && ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!1, "Use the `defaultValue` or `value` props instead of setting children on <textarea>.") : void 0), null != defaultValue ? "production" !== process.env.NODE_ENV ? invariant(!1, "If you supply `defaultValue` on a <textarea>, do not pass children.") : invariant(!1) : void 0, Array.isArray(children) && (children.length <= 1 ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "<textarea> can only have at most one child.") : invariant(!1), children = children[0]), defaultValue = "" + children), null == defaultValue && (defaultValue = ""); var value = LinkedValueUtils.getValue(props); inst._wrapperState = { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: "" + (null != value ? value : defaultValue), listeners: null, onChange: _handleChange.bind(inst) }; }, updateWrapper: function(inst) { var props = inst._currentElement.props; "production" !== process.env.NODE_ENV && warnIfValueIsNull(props); var value = LinkedValueUtils.getValue(props); null != value && // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), "value", "" + value); } }; module.exports = ReactDOMTextarea; }).call(exports, __webpack_require__(17)); }, /* 115 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild */ "use strict"; /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.INSERT_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.MOVE_EXISTING, content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getNativeNode(child), toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for removing an element at an index. * * @param {number} fromIndex Index of the element to remove. * @private */ function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.REMOVE_NODE, content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.SET_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.TEXT_CONTENT, content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { return update && (queue = queue || [], queue.push(update)), queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue); } var ReactComponentEnvironment = __webpack_require__(116), ReactInstrumentation = __webpack_require__(44), ReactMultiChildUpdateTypes = __webpack_require__(77), ReactCurrentOwner = __webpack_require__(104), ReactReconciler = __webpack_require__(51), ReactChildReconciler = __webpack_require__(117), emptyFunction = __webpack_require__(25), flattenChildren = __webpack_require__(127), invariant = __webpack_require__(18), setChildrenForInstrumentation = emptyFunction; "production" !== process.env.NODE_ENV && (setChildrenForInstrumentation = function(children) { ReactInstrumentation.debugTool.onSetChildren(this._debugID, children ? Object.keys(children).map(function(key) { return children[key]._debugID; }) : []); }); /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function(nestedChildren, transaction, context) { if ("production" !== process.env.NODE_ENV && this._currentElement) try { return ReactCurrentOwner.current = this._currentElement._owner, ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); } finally { ReactCurrentOwner.current = null; } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function(prevChildren, nextNestedChildrenElements, removedNodes, transaction, context) { var nextChildren; if ("production" !== process.env.NODE_ENV && this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner, nextChildren = flattenChildren(nextNestedChildrenElements); } finally { ReactCurrentOwner.current = null; } return ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context), nextChildren; } return nextChildren = flattenChildren(nextNestedChildrenElements), ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context), nextChildren; }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function(nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = [], index = 0; for (var name in children) if (children.hasOwnProperty(name)) { var child = children[name], mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context); child._mountIndex = index++, mountImages.push(mountImage); } return "production" !== process.env.NODE_ENV && setChildrenForInstrumentation.call(this, children), mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function(nextContent) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, !1); for (var name in prevChildren) prevChildren.hasOwnProperty(name) && ("production" !== process.env.NODE_ENV ? invariant(!1, "updateTextContent called on non-empty component.") : invariant(!1)); // Set new text content. var updates = [ makeTextContent(nextContent) ]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function(nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, !1); for (var name in prevChildren) prevChildren.hasOwnProperty(name) && ("production" !== process.env.NODE_ENV ? invariant(!1, "updateTextContent called on non-empty component.") : invariant(!1)); var updates = [ makeSetMarkup(nextMarkup) ]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function(nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function(nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren, removedNodes = {}, nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, removedNodes, transaction, context); if (nextChildren || prevChildren) { var name, updates = null, lastIndex = 0, nextIndex = 0, lastPlacedNode = null; for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) { var prevChild = prevChildren && prevChildren[name], nextChild = nextChildren[name]; prevChild === nextChild ? (updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)), lastIndex = Math.max(prevChild._mountIndex, lastIndex), prevChild._mountIndex = nextIndex) : (prevChild && (// Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex)), // The child must be instantiated before it's mounted. updates = enqueue(updates, this._mountChildAtIndex(nextChild, lastPlacedNode, nextIndex, transaction, context))), nextIndex++, lastPlacedNode = ReactReconciler.getNativeNode(nextChild); } // Remove children that are no longer present. for (name in removedNodes) removedNodes.hasOwnProperty(name) && (updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name]))); updates && processQueue(this, updates), this._renderedChildren = nextChildren, "production" !== process.env.NODE_ENV && setChildrenForInstrumentation.call(this, nextChildren); } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. It does not actually perform any * backend operations. * * @internal */ unmountChildren: function(safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely), this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function(child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. return child._mountIndex < lastIndex ? makeMove(child, afterNode, toIndex) : void 0; }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function(child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function(child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function(child, afterNode, index, transaction, context) { var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context); return child._mountIndex = index, this.createChild(child, afterNode, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function(child, node) { var update = this.removeChild(child, node); return child._mountIndex = null, update; } } }; module.exports = ReactMultiChild; }).call(exports, __webpack_require__(17)); }, /* 116 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentEnvironment */ "use strict"; var invariant = __webpack_require__(18), injected = !1, ReactComponentEnvironment = { /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. */ unmountIDFromEnvironment: null, /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkup: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function(environment) { injected ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactCompositeComponent: injectEnvironment() can only be called once.") : invariant(!1) : void 0, ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment, ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup, ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates, injected = !0; } } }; module.exports = ReactComponentEnvironment; }).call(exports, __webpack_require__(17)); }, /* 117 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildReconciler */ "use strict"; function instantiateChild(childInstances, child, name) { // We found a component instance. var keyUnique = void 0 === childInstances[name]; "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(keyUnique, "flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.", KeyEscapeUtils.unescape(name)) : void 0), null != child && keyUnique && (childInstances[name] = instantiateReactComponent(child)); } var ReactReconciler = __webpack_require__(51), instantiateReactComponent = __webpack_require__(118), KeyEscapeUtils = __webpack_require__(112), shouldUpdateReactComponent = __webpack_require__(124), traverseAllChildren = __webpack_require__(111), warning = __webpack_require__(24), ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function(nestedChildNodes, transaction, context) { if (null == nestedChildNodes) return null; var childInstances = {}; return traverseAllChildren(nestedChildNodes, instantiateChild, childInstances), childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function(prevChildren, nextChildren, removedNodes, transaction, context) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (nextChildren || prevChildren) { var name, prevChild; for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) { prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement, nextElement = nextChildren[name]; if (null != prevChild && shouldUpdateReactComponent(prevElement, nextElement)) ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context), nextChildren[name] = prevChild; else { prevChild && (removedNodes[name] = ReactReconciler.getNativeNode(prevChild), ReactReconciler.unmountComponent(prevChild, !1)); // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement); nextChildren[name] = nextChildInstance; } } // Unmount children that are no longer present. for (name in prevChildren) !prevChildren.hasOwnProperty(name) || nextChildren && nextChildren.hasOwnProperty(name) || (prevChild = prevChildren[name], removedNodes[name] = ReactReconciler.getNativeNode(prevChild), ReactReconciler.unmountComponent(prevChild, !1)); } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function(renderedChildren, safely) { for (var name in renderedChildren) if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild, safely); } } }; module.exports = ReactChildReconciler; }).call(exports, __webpack_require__(17)); }, /* 118 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent */ "use strict"; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) return " Check the render method of `" + name + "`."; } return ""; } function getDisplayName(instance) { var element = instance._currentElement; return null == element ? "#empty" : "string" == typeof element || "number" == typeof element ? "#text" : "string" == typeof element.type ? element.type : instance.getName ? instance.getName() || "Unknown" : element.type.displayName || element.type.name || "Unknown"; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return "function" == typeof type && "undefined" != typeof type.prototype && "function" == typeof type.prototype.mountComponent && "function" == typeof type.prototype.receiveComponent; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node) { var instance, isEmpty = null === node || node === !1; if (isEmpty) instance = ReactEmptyComponent.create(instantiateReactComponent); else if ("object" == typeof node) { var element = node; !element || "function" != typeof element.type && "string" != typeof element.type ? "production" !== process.env.NODE_ENV ? invariant(!1, "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", null == element.type ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(!1) : void 0, // Special case string values instance = "string" == typeof element.type ? ReactNativeComponent.createInternalComponent(element) : isInternalComponentType(element.type) ? new element.type(element) : new ReactCompositeComponentWrapper(element); } else "string" == typeof node || "number" == typeof node ? instance = ReactNativeComponent.createInstanceForText(node) : "production" !== process.env.NODE_ENV ? invariant(!1, "Encountered invalid React node of type %s", typeof node) : invariant(!1); if ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning("function" == typeof instance.mountComponent && "function" == typeof instance.receiveComponent && "function" == typeof instance.getNativeNode && "function" == typeof instance.unmountComponent, "Only React Components can be mounted.") : void 0), // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0, instance._mountImage = null, "production" !== process.env.NODE_ENV && (instance._isOwnerNecessary = !1, instance._warnedAboutRefsInRender = !1), "production" !== process.env.NODE_ENV) { var debugID = isEmpty ? 0 : nextDebugID++; if (instance._debugID = debugID, 0 !== debugID) { var displayName = getDisplayName(instance); ReactInstrumentation.debugTool.onSetDisplayName(debugID, displayName); var owner = node && node._owner; owner && ReactInstrumentation.debugTool.onSetOwner(debugID, owner._debugID); } } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. return "production" !== process.env.NODE_ENV && Object.preventExtensions && Object.preventExtensions(instance), instance; } var _assign = __webpack_require__(30), ReactCompositeComponent = __webpack_require__(119), ReactEmptyComponent = __webpack_require__(125), ReactNativeComponent = __webpack_require__(126), ReactInstrumentation = __webpack_require__(44), invariant = __webpack_require__(18), warning = __webpack_require__(24), ReactCompositeComponentWrapper = function(element) { this.construct(element); }; _assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent }); var nextDebugID = 1; module.exports = instantiateReactComponent; }).call(exports, __webpack_require__(17)); }, /* 119 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ "use strict"; function getDeclarationErrorAddendum(component) { var owner = component._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) return " Check the render method of `" + name + "`."; } return ""; } function StatelessComponent(Component) {} function warnIfInvalidElement(Component, element) { "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null === element || element === !1 || ReactElement.isValidElement(element), "%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.", Component.displayName || Component.name || "Component") : void 0); } function invokeComponentDidMountWithTimer() { var publicInstance = this._instance; 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentDidMount"), publicInstance.componentDidMount(), 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentDidMount"); } function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) { var publicInstance = this._instance; 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentDidUpdate"), publicInstance.componentDidUpdate(prevProps, prevState, prevContext), 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentDidUpdate"); } function shouldConstruct(Component) { return Component.prototype && Component.prototype.isReactComponent; } var _assign = __webpack_require__(30), ReactComponentEnvironment = __webpack_require__(116), ReactCurrentOwner = __webpack_require__(104), ReactElement = __webpack_require__(103), ReactErrorUtils = __webpack_require__(23), ReactInstanceMap = __webpack_require__(120), ReactInstrumentation = __webpack_require__(44), ReactNodeTypes = __webpack_require__(121), ReactPropTypeLocations = __webpack_require__(108), ReactPropTypeLocationNames = __webpack_require__(106), ReactReconciler = __webpack_require__(51), ReactUpdateQueue = __webpack_require__(122), emptyObject = __webpack_require__(123), invariant = __webpack_require__(18), shouldUpdateReactComponent = __webpack_require__(124), warning = __webpack_require__(24); StatelessComponent.prototype.render = function() { var Component = ReactInstanceMap.get(this)._currentElement.type, element = Component(this.props, this.context, this.updater); return warnIfInvalidElement(Component, element), element; }; /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1, ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function(element) { this._currentElement = element, this._rootNodeID = null, this._instance = null, this._nativeParent = null, this._nativeContainerInfo = null, // See ReactUpdateQueue this._updateBatchNumber = null, this._pendingElement = null, this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1, this._renderedNodeType = null, this._renderedComponent = null, this._context = null, this._mountOrder = 0, this._topLevelWrapper = null, // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null, // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = !1; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} nativeParent * @param {?object} nativeContainerInfo * @param {?object} context * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function(transaction, nativeParent, nativeContainerInfo, context) { this._context = context, this._mountOrder = nextMountID++, this._nativeParent = nativeParent, this._nativeContainerInfo = nativeContainerInfo; var renderedElement, publicProps = this._processProps(this._currentElement.props), publicContext = this._processContext(context), Component = this._currentElement.type, inst = this._constructComponent(publicProps, publicContext); if (// Support functional components shouldConstruct(Component) || null != inst && null != inst.render || (renderedElement = inst, warnIfInvalidElement(Component, renderedElement), null === inst || inst === !1 || ReactElement.isValidElement(inst) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.", Component.displayName || Component.name || "Component") : invariant(!1), inst = new StatelessComponent(Component)), "production" !== process.env.NODE_ENV) { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging null == inst.render && ("production" !== process.env.NODE_ENV ? warning(!1, "%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.", Component.displayName || Component.name || "Component") : void 0); var propsMutated = inst.props !== publicProps, componentName = Component.displayName || Component.name || "Component"; "production" !== process.env.NODE_ENV ? warning(void 0 === inst.props || !propsMutated, "%s(...): When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.", componentName, componentName) : void 0; } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps, inst.context = publicContext, inst.refs = emptyObject, inst.updater = ReactUpdateQueue, this._instance = inst, // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this), "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, "getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?", this.getName() || "a component") : void 0, "production" !== process.env.NODE_ENV ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, "getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.", this.getName() || "a component") : void 0, "production" !== process.env.NODE_ENV ? warning(!inst.propTypes, "propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.", this.getName() || "a component") : void 0, "production" !== process.env.NODE_ENV ? warning(!inst.contextTypes, "contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.", this.getName() || "a component") : void 0, "production" !== process.env.NODE_ENV ? warning("function" != typeof inst.componentShouldUpdate, "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", this.getName() || "A component") : void 0, "production" !== process.env.NODE_ENV ? warning("function" != typeof inst.componentDidUnmount, "%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?", this.getName() || "A component") : void 0, "production" !== process.env.NODE_ENV ? warning("function" != typeof inst.componentWillRecieveProps, "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", this.getName() || "A component") : void 0); var initialState = inst.state; void 0 === initialState && (inst.state = initialState = null), "object" != typeof initialState || Array.isArray(initialState) ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s.state: must be set to an object or null", this.getName() || "ReactCompositeComponent") : invariant(!1) : void 0, this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1; var markup; return markup = inst.unstable_handleError ? this.performInitialMountWithErrorHandling(renderedElement, nativeParent, nativeContainerInfo, transaction, context) : this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context), inst.componentDidMount && ("production" !== process.env.NODE_ENV ? transaction.getReactMountReady().enqueue(invokeComponentDidMountWithTimer, this) : transaction.getReactMountReady().enqueue(inst.componentDidMount, inst)), markup; }, _constructComponent: function(publicProps, publicContext) { if ("production" === process.env.NODE_ENV) return this._constructComponentWithoutOwner(publicProps, publicContext); ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(publicProps, publicContext); } finally { ReactCurrentOwner.current = null; } }, _constructComponentWithoutOwner: function(publicProps, publicContext) { var instanceOrElement, Component = this._currentElement.type; // This can still be an instance in case of factory components // but we'll count this as time spent rendering as the more common case. return shouldConstruct(Component) ? ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "ctor"), instanceOrElement = new Component(publicProps, publicContext, ReactUpdateQueue), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "ctor")) : ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "render"), instanceOrElement = Component(publicProps, publicContext, ReactUpdateQueue), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "render")), instanceOrElement; }, performInitialMountWithErrorHandling: function(renderedElement, nativeParent, nativeContainerInfo, transaction, context) { var markup, checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint), this._instance.unstable_handleError(e), this._pendingStateQueue && (this._instance.state = this._processPendingState(this._instance.props, this._instance.context)), checkpoint = transaction.checkpoint(), this._renderedComponent.unmountComponent(!0), transaction.rollback(checkpoint), // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } return markup; }, performInitialMount: function(renderedElement, nativeParent, nativeContainerInfo, transaction, context) { var inst = this._instance; inst.componentWillMount && ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentWillMount"), inst.componentWillMount(), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentWillMount"), // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. this._pendingStateQueue && (inst.state = this._processPendingState(inst.props, inst.context))), // If not a stateless component, we now render void 0 === renderedElement && (renderedElement = this._renderValidatedComponent()), this._renderedNodeType = ReactNodeTypes.getType(renderedElement), this._renderedComponent = this._instantiateReactComponent(renderedElement); var markup = ReactReconciler.mountComponent(this._renderedComponent, transaction, nativeParent, nativeContainerInfo, this._processChildContext(context)); return "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onSetChildren(this._debugID, 0 !== this._renderedComponent._debugID ? [ this._renderedComponent._debugID ] : []), markup; }, getNativeNode: function() { return ReactReconciler.getNativeNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function(safely) { if (this._renderedComponent) { var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { if (inst._calledComponentWillUnmount = !0, "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentWillUnmount"), safely) { var name = this.getName() + ".componentWillUnmount()"; ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst)); } else inst.componentWillUnmount(); "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentWillUnmount"); } this._renderedComponent && (ReactReconciler.unmountComponent(this._renderedComponent, safely), this._renderedNodeType = null, this._renderedComponent = null, this._instance = null), // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1, this._pendingCallbacks = null, this._pendingElement = null, // These fields do not really need to be reset since this object is no // longer accessible. this._context = null, this._rootNodeID = null, this._topLevelWrapper = null, // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); } }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function(context) { var Component = this._currentElement.type, contextTypes = Component.contextTypes; if (!contextTypes) return emptyObject; var maskedContext = {}; for (var contextName in contextTypes) maskedContext[contextName] = context[contextName]; return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function(context) { var maskedContext = this._maskContext(context); if ("production" !== process.env.NODE_ENV) { var Component = this._currentElement.type; Component.contextTypes && this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function(currentContext) { var Component = this._currentElement.type, inst = this._instance; "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onBeginProcessingChildContext(); var childContext = inst.getChildContext && inst.getChildContext(); if ("production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onEndProcessingChildContext(), childContext) { "object" != typeof Component.childContextTypes ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().", this.getName() || "ReactCompositeComponent") : invariant(!1) : void 0, "production" !== process.env.NODE_ENV && this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); for (var name in childContext) name in Component.childContextTypes ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || "ReactCompositeComponent", name) : invariant(!1); return _assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function(newProps) { if ("production" !== process.env.NODE_ENV) { var Component = this._currentElement.type; Component.propTypes && this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop); } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function(propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) if (propTypes.hasOwnProperty(propName)) { var error; try { "function" != typeof propTypes[propName] ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.", componentName || "React class", ReactPropTypeLocationNames[location], propName) : invariant(!1) : void 0, error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // top-level render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); location === ReactPropTypeLocations.prop ? "production" !== process.env.NODE_ENV ? warning(!1, "Failed Composite propType: %s%s", error.message, addendum) : void 0 : "production" !== process.env.NODE_ENV ? warning(!1, "Failed Context Types: %s%s", error.message, addendum) : void 0; } } }, receiveComponent: function(nextElement, transaction, nextContext) { var prevElement = this._currentElement, prevContext = this._context; this._pendingElement = null, this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function(transaction) { null != this._pendingElement ? ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context) : null !== this._pendingStateQueue || this._pendingForceUpdate ? this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context) : this._updateBatchNumber = null; }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function(transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var nextContext, nextProps, inst = this._instance, willReceive = !1; // Determine if the context has changed or not this._context === nextUnmaskedContext ? nextContext = inst.context : (nextContext = this._processContext(nextUnmaskedContext), willReceive = !0), // Distinguish between a props update versus a simple state update prevParentElement === nextParentElement ? // Skip checking prop types again -- we don't read inst.props to avoid // warning for DOM component props in this upgrade nextProps = nextParentElement.props : (nextProps = this._processProps(nextParentElement.props), willReceive = !0), // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. willReceive && inst.componentWillReceiveProps && ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentWillReceiveProps"), inst.componentWillReceiveProps(nextProps, nextContext), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentWillReceiveProps")); var nextState = this._processPendingState(nextProps, nextContext), shouldUpdate = !0; !this._pendingForceUpdate && inst.shouldComponentUpdate && ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "shouldComponentUpdate"), shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "shouldComponentUpdate")), "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(void 0 !== shouldUpdate, "%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.", this.getName() || "ReactCompositeComponent") : void 0), this._updateBatchNumber = null, shouldUpdate ? (this._pendingForceUpdate = !1, // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext)) : (// If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement, this._context = nextUnmaskedContext, inst.props = nextProps, inst.state = nextState, inst.context = nextContext); }, _processPendingState: function(props, context) { var inst = this._instance, queue = this._pendingStateQueue, replace = this._pendingReplaceState; if (this._pendingReplaceState = !1, this._pendingStateQueue = null, !queue) return inst.state; if (replace && 1 === queue.length) return queue[0]; for (var nextState = _assign({}, replace ? queue[0] : inst.state), i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; _assign(nextState, "function" == typeof partial ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function(nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var prevProps, prevState, prevContext, inst = this._instance, hasComponentDidUpdate = Boolean(inst.componentDidUpdate); hasComponentDidUpdate && (prevProps = inst.props, prevState = inst.state, prevContext = inst.context), inst.componentWillUpdate && ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentWillUpdate"), inst.componentWillUpdate(nextProps, nextState, nextContext), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentWillUpdate")), this._currentElement = nextElement, this._context = unmaskedContext, inst.props = nextProps, inst.state = nextState, inst.context = nextContext, this._updateRenderedComponent(transaction, unmaskedContext), hasComponentDidUpdate && ("production" !== process.env.NODE_ENV ? transaction.getReactMountReady().enqueue(invokeComponentDidUpdateWithTimer.bind(this, prevProps, prevState, prevContext), this) : transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst)); }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function(transaction, context) { var prevComponentInstance = this._renderedComponent, prevRenderedElement = prevComponentInstance._currentElement, nextRenderedElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); else { var oldNativeNode = ReactReconciler.getNativeNode(prevComponentInstance); ReactReconciler.unmountComponent(prevComponentInstance, !1), this._renderedNodeType = ReactNodeTypes.getType(nextRenderedElement), this._renderedComponent = this._instantiateReactComponent(nextRenderedElement); var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, transaction, this._nativeParent, this._nativeContainerInfo, this._processChildContext(context)); "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onSetChildren(this._debugID, 0 !== this._renderedComponent._debugID ? [ this._renderedComponent._debugID ] : []), this._replaceNodeWithMarkup(oldNativeNode, nextMarkup, prevComponentInstance); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function(oldNativeNode, nextMarkup, prevInstance) { ReactComponentEnvironment.replaceNodeWithMarkup(oldNativeNode, nextMarkup, prevInstance); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function() { var inst = this._instance; "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "render"); var renderedComponent = inst.render(); // This is probably bad practice. Consider warning here and // deprecating this convenience. return "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "render"), "production" !== process.env.NODE_ENV && void 0 === renderedComponent && inst.render._isMockFunction && (renderedComponent = null), renderedComponent; }, /** * @private */ _renderValidatedComponent: function() { var renderedComponent; ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } // TODO: An `isValidNode` function would probably be more appropriate return null === renderedComponent || renderedComponent === !1 || ReactElement.isValidElement(renderedComponent) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.", this.getName() || "ReactCompositeComponent") : invariant(!1), renderedComponent; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function(ref, component) { var inst = this.getPublicInstance(); null == inst ? "production" !== process.env.NODE_ENV ? invariant(!1, "Stateless function components cannot have refs.") : invariant(!1) : void 0; var publicComponentInstance = component.getPublicInstance(); if ("production" !== process.env.NODE_ENV) { var componentName = component && component.getName ? component.getName() : "a component"; "production" !== process.env.NODE_ENV ? warning(null != publicComponentInstance, 'Stateless function components cannot be given refs (See ref "%s" in %s created by %s). Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function(ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function() { var type = this._currentElement.type, constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function() { var inst = this._instance; return inst instanceof StatelessComponent ? null : inst; }, // Stub _instantiateReactComponent: null }, ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; }).call(exports, __webpack_require__(17)); }, /* 120 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceMap */ "use strict"; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function(key) { key._reactInternalInstance = void 0; }, get: function(key) { return key._reactInternalInstance; }, has: function(key) { return void 0 !== key._reactInternalInstance; }, set: function(key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; }, /* 121 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNodeTypes */ "use strict"; var ReactElement = __webpack_require__(103), invariant = __webpack_require__(18), ReactNodeTypes = { NATIVE: 0, COMPOSITE: 1, EMPTY: 2, getType: function(node) { return null === node || node === !1 ? ReactNodeTypes.EMPTY : ReactElement.isValidElement(node) ? "function" == typeof node.type ? ReactNodeTypes.COMPOSITE : ReactNodeTypes.NATIVE : void ("production" !== process.env.NODE_ENV ? invariant(!1, "Unexpected node: %s", node) : invariant(!1)); } }; module.exports = ReactNodeTypes; }).call(exports, __webpack_require__(17)); }, /* 122 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdateQueue */ "use strict"; function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function formatUnexpectedArgument(arg) { var type = typeof arg; if ("object" !== type) return type; var displayName = arg.constructor && arg.constructor.name || type, keys = Object.keys(arg); return keys.length > 0 && keys.length < 20 ? displayName + " (keys: " + keys.join(", ") + ")" : displayName; } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. return internalInstance ? ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null == ReactCurrentOwner.current, "%s(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.", callerName) : void 0), internalInstance) : ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!callerName, "%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op. Please check the code for the %s component.", callerName, callerName, publicInstance.constructor.displayName) : void 0), null); } var ReactCurrentOwner = __webpack_require__(104), ReactInstanceMap = __webpack_require__(120), ReactUpdates = __webpack_require__(41), invariant = __webpack_require__(18), warning = __webpack_require__(24), ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function(publicInstance) { if ("production" !== process.env.NODE_ENV) { var owner = ReactCurrentOwner.current; null !== owner && ("production" !== process.env.NODE_ENV ? warning(owner._warnedAboutRefsInRender, "%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", owner.getName() || "A component") : void 0, owner._warnedAboutRefsInRender = !0); } var internalInstance = ReactInstanceMap.get(publicInstance); return internalInstance ? !!internalInstance._renderedComponent : !1; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @param {string} callerName Name of the calling function in the public API. * @internal */ enqueueCallback: function(publicInstance, callback, callerName) { ReactUpdateQueue.validateCallback(callback, callerName); var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. return internalInstance ? (internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ], void enqueueUpdate(internalInstance)) : null; }, enqueueCallbackInternal: function(internalInstance, callback) { internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ], enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function(publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, "forceUpdate"); internalInstance && (internalInstance._pendingForceUpdate = !0, enqueueUpdate(internalInstance)); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function(publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, "replaceState"); internalInstance && (internalInstance._pendingStateQueue = [ completeState ], internalInstance._pendingReplaceState = !0, enqueueUpdate(internalInstance)); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function(publicInstance, partialState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, "setState"); if (internalInstance) { var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState), enqueueUpdate(internalInstance); } }, enqueueElementInternal: function(internalInstance, newElement) { internalInstance._pendingElement = newElement, enqueueUpdate(internalInstance); }, validateCallback: function(callback, callerName) { callback && "function" != typeof callback ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, formatUnexpectedArgument(callback)) : invariant(!1) : void 0; } }; module.exports = ReactUpdateQueue; }).call(exports, __webpack_require__(17)); }, /* 123 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ "use strict"; var emptyObject = {}; "production" !== process.env.NODE_ENV && Object.freeze(emptyObject), module.exports = emptyObject; }).call(exports, __webpack_require__(17)); }, /* 124 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent */ "use strict"; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = null === prevElement || prevElement === !1, nextEmpty = null === nextElement || nextElement === !1; if (prevEmpty || nextEmpty) return prevEmpty === nextEmpty; var prevType = typeof prevElement, nextType = typeof nextElement; return "string" === prevType || "number" === prevType ? "string" === nextType || "number" === nextType : "object" === nextType && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } module.exports = shouldUpdateReactComponent; }, /* 125 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponent */ "use strict"; var emptyComponentFactory, ReactEmptyComponentInjection = { injectEmptyComponentFactory: function(factory) { emptyComponentFactory = factory; } }, ReactEmptyComponent = { create: function(instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection, module.exports = ReactEmptyComponent; }, /* 126 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNativeComponent */ "use strict"; /** * Get a composite component wrapper class for a specific tag. * * @param {ReactElement} element The tag for which to get the class. * @return {function} The React class constructor function. */ function getComponentClassForElement(element) { if ("function" == typeof element.type) return element.type; var tag = element.type, componentClass = tagToComponentClass[tag]; return null == componentClass && (tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag)), componentClass; } /** * Get a native internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { return genericComponentClass ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "There is no registered component for the tag %s", element.type) : invariant(!1), new genericComponentClass(element); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var _assign = __webpack_require__(30), invariant = __webpack_require__(18), autoGenerateWrapperClass = null, genericComponentClass = null, tagToComponentClass = {}, textComponentClass = null, ReactNativeComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function(componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function(componentClass) { textComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function(componentClasses) { _assign(tagToComponentClass, componentClasses); } }, ReactNativeComponent = { getComponentClassForElement: getComponentClassForElement, createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactNativeComponentInjection }; module.exports = ReactNativeComponent; }).call(exports, __webpack_require__(17)); }, /* 127 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren */ "use strict"; /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext, keyUnique = void 0 === result[name]; "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(keyUnique, "flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.", KeyEscapeUtils.unescape(name)) : void 0), keyUnique && null != child && (result[name] = child); } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (null == children) return children; var result = {}; return traverseAllChildren(children, flattenSingleChildIntoContext, result), result; } var KeyEscapeUtils = __webpack_require__(112), traverseAllChildren = __webpack_require__(111), warning = __webpack_require__(24); module.exports = flattenChildren; }).call(exports, __webpack_require__(17)); }, /* 128 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRenderingTransaction */ "use strict"; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(), this.renderToStaticMarkup = renderToStaticMarkup, this.useCreateElement = !1; } var _assign = __webpack_require__(30), PooledClass = __webpack_require__(31), Transaction = __webpack_require__(54), TRANSACTION_WRAPPERS = [], noopCallbackQueue = { enqueue: function() {} }, Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return noopCallbackQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function() {}, checkpoint: function() {}, rollback: function() {} }; _assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin), PooledClass.addPoolingTo(ReactServerRenderingTransaction), module.exports = ReactServerRenderingTransaction; }, /* 129 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * */ /*eslint-disable no-self-compare */ "use strict"; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm // SameValue algorithm return x === y ? 0 !== x || 1 / x === 1 / y : x !== x && y !== y; } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(objA, objB)) return !0; if ("object" != typeof objA || null === objA || "object" != typeof objB || null === objB) return !1; var keysA = Object.keys(objA), keysB = Object.keys(objB); if (keysA.length !== keysB.length) return !1; // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) return !1; return !0; } var hasOwnProperty = Object.prototype.hasOwnProperty; module.exports = shallowEqual; }, /* 130 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule validateDOMNesting */ "use strict"; var _assign = __webpack_require__(30), emptyFunction = __webpack_require__(25), warning = __webpack_require__(24), validateDOMNesting = emptyFunction; if ("production" !== process.env.NODE_ENV) { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = [ "address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "main", "marquee", "menu", "menuitem", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "source", "style", "summary", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp" ], inScopeTags = [ "applet", "caption", "html", "table", "td", "th", "marquee", "object", "template", // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings "foreignObject", "desc", "title" ], buttonScopeTags = inScopeTags.concat([ "button" ]), impliedEndTags = [ "dd", "dt", "li", "option", "optgroup", "p", "rp", "rt" ], emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }, updatedAncestorInfo = function(oldInfo, tag, instance) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo), info = { tag: tag, instance: instance }; // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody return -1 !== inScopeTags.indexOf(tag) && (ancestorInfo.aTagInScope = null, ancestorInfo.buttonTagInScope = null, ancestorInfo.nobrTagInScope = null), -1 !== buttonScopeTags.indexOf(tag) && (ancestorInfo.pTagInButtonScope = null), -1 !== specialTags.indexOf(tag) && "address" !== tag && "div" !== tag && "p" !== tag && (ancestorInfo.listItemTagAutoclosing = null, ancestorInfo.dlItemTagAutoclosing = null), ancestorInfo.current = info, "form" === tag && (ancestorInfo.formTag = info), "a" === tag && (ancestorInfo.aTagInScope = info), "button" === tag && (ancestorInfo.buttonTagInScope = info), "nobr" === tag && (ancestorInfo.nobrTagInScope = info), "p" === tag && (ancestorInfo.pTagInButtonScope = info), "li" === tag && (ancestorInfo.listItemTagAutoclosing = info), "dd" !== tag && "dt" !== tag || (ancestorInfo.dlItemTagAutoclosing = info), ancestorInfo; }, isTagValidWithParent = function(tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case "select": return "option" === tag || "optgroup" === tag || "#text" === tag; case "optgroup": return "option" === tag || "#text" === tag; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case "option": return "#text" === tag; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case "tr": return "th" === tag || "td" === tag || "style" === tag || "script" === tag || "template" === tag; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case "tbody": case "thead": case "tfoot": return "tr" === tag || "style" === tag || "script" === tag || "template" === tag; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case "colgroup": return "col" === tag || "template" === tag; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case "table": return "caption" === tag || "colgroup" === tag || "tbody" === tag || "tfoot" === tag || "thead" === tag || "style" === tag || "script" === tag || "template" === tag; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case "head": return "base" === tag || "basefont" === tag || "bgsound" === tag || "link" === tag || "meta" === tag || "title" === tag || "noscript" === tag || "noframes" === tag || "style" === tag || "script" === tag || "template" === tag; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case "html": return "head" === tag || "body" === tag; case "#document": return "html" === tag; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": return "h1" !== parentTag && "h2" !== parentTag && "h3" !== parentTag && "h4" !== parentTag && "h5" !== parentTag && "h6" !== parentTag; case "rp": case "rt": return -1 === impliedEndTags.indexOf(parentTag); case "body": case "caption": case "col": case "colgroup": case "frame": case "head": case "html": case "tbody": case "td": case "tfoot": case "th": case "thead": case "tr": // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return null == parentTag; } return !0; }, findInvalidAncestorForTag = function(tag, ancestorInfo) { switch (tag) { case "address": case "article": case "aside": case "blockquote": case "center": case "details": case "dialog": case "dir": case "div": case "dl": case "fieldset": case "figcaption": case "figure": case "footer": case "header": case "hgroup": case "main": case "menu": case "nav": case "ol": case "p": case "section": case "summary": case "ul": case "pre": case "listing": case "table": case "hr": case "xmp": case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": return ancestorInfo.pTagInButtonScope; case "form": return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case "li": return ancestorInfo.listItemTagAutoclosing; case "dd": case "dt": return ancestorInfo.dlItemTagAutoclosing; case "button": return ancestorInfo.buttonTagInScope; case "a": // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case "nobr": return ancestorInfo.nobrTagInScope; } return null; }, findOwnerStack = function(instance) { if (!instance) return []; var stack = []; do stack.push(instance); while (instance = instance._currentElement._owner); return stack.reverse(), stack; }, didWarn = {}; validateDOMNesting = function(childTag, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current, parentTag = parentInfo && parentInfo.tag, invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo, invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo), problematic = invalidParent || invalidAncestor; if (problematic) { var i, ancestorTag = problematic.tag, ancestorInstance = problematic.instance, childOwner = childInstance && childInstance._currentElement._owner, ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner, childOwners = findOwnerStack(childOwner), ancestorOwners = findOwnerStack(ancestorOwner), minStackLen = Math.min(childOwners.length, ancestorOwners.length), deepestCommon = -1; for (i = 0; minStackLen > i && childOwners[i] === ancestorOwners[i]; i++) deepestCommon = i; var UNKNOWN = "(unknown)", childOwnerNames = childOwners.slice(deepestCommon + 1).map(function(inst) { return inst.getName() || UNKNOWN; }), ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function(inst) { return inst.getName() || UNKNOWN; }), ownerInfo = [].concat(-1 !== deepestCommon ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, invalidAncestor ? [ "..." ] : [], childOwnerNames, childTag).join(" > "), warnKey = !!invalidParent + "|" + childTag + "|" + ancestorTag + "|" + ownerInfo; if (didWarn[warnKey]) return; didWarn[warnKey] = !0; var tagDisplayName = childTag; if ("#text" !== childTag && (tagDisplayName = "<" + childTag + ">"), invalidParent) { var info = ""; "table" === ancestorTag && "tr" === childTag && (info += " Add a <tbody> to your code to match the DOM tree generated by the browser."), "production" !== process.env.NODE_ENV ? warning(!1, "validateDOMNesting(...): %s cannot appear as a child of <%s>. See %s.%s", tagDisplayName, ancestorTag, ownerInfo, info) : void 0; } else "production" !== process.env.NODE_ENV ? warning(!1, "validateDOMNesting(...): %s cannot appear as a descendant of <%s>. See %s.", tagDisplayName, ancestorTag, ownerInfo) : void 0; } }, validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo, // For testing validateDOMNesting.isTagValidInContext = function(tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current, parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; }).call(exports, __webpack_require__(17)); }, /* 131 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMEmptyComponent */ "use strict"; var _assign = __webpack_require__(30), DOMLazyTree = __webpack_require__(67), ReactDOMComponentTree = __webpack_require__(38), ReactDOMEmptyComponent = function(instantiate) { // ReactCompositeComponent uses this: this._currentElement = null, // ReactDOMComponentTree uses these: this._nativeNode = null, this._nativeParent = null, this._nativeContainerInfo = null, this._domID = null; }; _assign(ReactDOMEmptyComponent.prototype, { mountComponent: function(transaction, nativeParent, nativeContainerInfo, context) { var domID = nativeContainerInfo._idCounter++; this._domID = domID, this._nativeParent = nativeParent, this._nativeContainerInfo = nativeContainerInfo; var nodeValue = " react-empty: " + this._domID + " "; if (transaction.useCreateElement) { var ownerDocument = nativeContainerInfo._ownerDocument, node = ownerDocument.createComment(nodeValue); return ReactDOMComponentTree.precacheNode(this, node), DOMLazyTree(node); } return transaction.renderToStaticMarkup ? "" : "<!--" + nodeValue + "-->"; }, receiveComponent: function() {}, getNativeNode: function() { return ReactDOMComponentTree.getNodeFromInstance(this); }, unmountComponent: function() { ReactDOMComponentTree.uncacheNode(this); } }), module.exports = ReactDOMEmptyComponent; }, /* 132 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTreeTraversal */ "use strict"; /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { "_nativeNode" in instA ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "getNodeFromInstance: Invalid argument.") : invariant(!1), "_nativeNode" in instB ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "getNodeFromInstance: Invalid argument.") : invariant(!1); for (var depthA = 0, tempA = instA; tempA; tempA = tempA._nativeParent) depthA++; for (var depthB = 0, tempB = instB; tempB; tempB = tempB._nativeParent) depthB++; // If A is deeper, crawl up. for (;depthA - depthB > 0; ) instA = instA._nativeParent, depthA--; // If B is deeper, crawl up. for (;depthB - depthA > 0; ) instB = instB._nativeParent, depthB--; for (// Walk in lockstep until we find a match. var depth = depthA; depth--; ) { if (instA === instB) return instA; instA = instA._nativeParent, instB = instB._nativeParent; } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { "_nativeNode" in instA ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "isAncestor: Invalid argument.") : invariant(!1), "_nativeNode" in instB ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "isAncestor: Invalid argument.") : invariant(!1); for (;instB; ) { if (instB === instA) return !0; instB = instB._nativeParent; } return !1; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { return "_nativeNode" in inst ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "getParentInstance: Invalid argument.") : invariant(!1), inst._nativeParent; } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { for (var path = []; inst; ) path.push(inst), inst = inst._nativeParent; var i; for (i = path.length; i-- > 0; ) fn(path[i], !1, arg); for (i = 0; i < path.length; i++) fn(path[i], !0, arg); } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { for (var common = from && to ? getLowestCommonAncestor(from, to) : null, pathFrom = []; from && from !== common; ) pathFrom.push(from), from = from._nativeParent; for (var pathTo = []; to && to !== common; ) pathTo.push(to), to = to._nativeParent; var i; for (i = 0; i < pathFrom.length; i++) fn(pathFrom[i], !0, argFrom); for (i = pathTo.length; i-- > 0; ) fn(pathTo[i], !1, argTo); } var invariant = __webpack_require__(18); module.exports = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; }).call(exports, __webpack_require__(17)); }, /* 133 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextComponent */ "use strict"; var _assign = __webpack_require__(30), DOMChildrenOperations = __webpack_require__(66), DOMLazyTree = __webpack_require__(67), ReactDOMComponentTree = __webpack_require__(38), ReactInstrumentation = __webpack_require__(44), escapeTextContentForBrowser = __webpack_require__(71), invariant = __webpack_require__(18), validateDOMNesting = __webpack_require__(130), ReactDOMTextComponent = function(text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text, this._stringText = "" + text, // ReactDOMComponentTree uses these: this._nativeNode = null, this._nativeParent = null, // Properties this._domID = null, this._mountIndex = 0, this._closingComment = null, this._commentNodes = null; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function(transaction, nativeParent, nativeContainerInfo, context) { if ("production" !== process.env.NODE_ENV) { ReactInstrumentation.debugTool.onSetText(this._debugID, this._stringText); var parentInfo; null != nativeParent ? parentInfo = nativeParent._ancestorInfo : null != nativeContainerInfo && (parentInfo = nativeContainerInfo._ancestorInfo), parentInfo && // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting("#text", this, parentInfo); } var domID = nativeContainerInfo._idCounter++, openingValue = " react-text: " + domID + " ", closingValue = " /react-text "; if (this._domID = domID, this._nativeParent = nativeParent, transaction.useCreateElement) { var ownerDocument = nativeContainerInfo._ownerDocument, openingComment = ownerDocument.createComment(openingValue), closingComment = ownerDocument.createComment(closingValue), lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment()); return DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)), this._stringText && DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))), DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)), ReactDOMComponentTree.precacheNode(this, openingComment), this._closingComment = closingComment, lazyTree; } var escapedText = escapeTextContentForBrowser(this._stringText); return transaction.renderToStaticMarkup ? escapedText : "<!--" + openingValue + "-->" + escapedText + "<!--" + closingValue + "-->"; }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function(nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = "" + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getNativeNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onSetText(this._debugID, nextStringText); } } }, getNativeNode: function() { var nativeNode = this._commentNodes; if (nativeNode) return nativeNode; if (!this._closingComment) for (var openingComment = ReactDOMComponentTree.getNodeFromInstance(this), node = openingComment.nextSibling; ;) { if (null == node ? "production" !== process.env.NODE_ENV ? invariant(!1, "Missing closing comment for text component %s", this._domID) : invariant(!1) : void 0, 8 === node.nodeType && " /react-text " === node.nodeValue) { this._closingComment = node; break; } node = node.nextSibling; } return nativeNode = [ this._nativeNode, this._closingComment ], this._commentNodes = nativeNode, nativeNode; }, unmountComponent: function() { this._closingComment = null, this._commentNodes = null, ReactDOMComponentTree.uncacheNode(this); } }), module.exports = ReactDOMTextComponent; }).call(exports, __webpack_require__(17)); }, /* 134 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ "use strict"; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } var _assign = __webpack_require__(30), ReactUpdates = __webpack_require__(41), Transaction = __webpack_require__(54), emptyFunction = __webpack_require__(25), RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function() { ReactDefaultBatchingStrategy.isBatchingUpdates = !1; } }, FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }, TRANSACTION_WRAPPERS = [ FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES ]; _assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(), ReactDefaultBatchingStrategy = { isBatchingUpdates: !1, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function(callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = !0, // The code is written this way to avoid extra allocations alreadyBatchingUpdates ? callback(a, b, c, d, e) : transaction.perform(callback, null, a, b, c, d, e); } }; module.exports = ReactDefaultBatchingStrategy; }, /* 135 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener */ "use strict"; /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findParent(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. for (;inst._nativeParent; ) inst = inst._nativeParent; var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst), container = rootNode.parentNode; return ReactDOMComponentTree.getClosestInstanceFromNode(container); } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType, this.nativeEvent = nativeEvent, this.ancestors = []; } function handleTopLevelImpl(bookKeeping) { var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent), targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget), ancestor = targetInst; do bookKeeping.ancestors.push(ancestor), ancestor = ancestor && findParent(ancestor); while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) targetInst = bookKeeping.ancestors[i], ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var _assign = __webpack_require__(30), EventListener = __webpack_require__(136), ExecutionEnvironment = __webpack_require__(28), PooledClass = __webpack_require__(31), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), getEventTarget = __webpack_require__(55), getUnboundedScrollPosition = __webpack_require__(137); _assign(TopLevelCallbackBookKeeping.prototype, { destructor: function() { this.topLevelType = null, this.nativeEvent = null, this.ancestors.length = 0; } }), PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); var ReactEventListener = { _enabled: !0, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function(handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function(enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function() { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { var element = handle; return element ? EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)) : null; }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { var element = handle; return element ? EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)) : null; }, monitorScrollValue: function(refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, "scroll", callback); }, dispatchEvent: function(topLevelType, nativeEvent) { if (ReactEventListener._enabled) { var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } } }; module.exports = ReactEventListener; }, /* 136 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { "use strict"; /** * Copyright (c) 2013-present, Facebook, 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. * * @typechecks */ var emptyFunction = __webpack_require__(25), EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function(target, eventType, callback) { return target.addEventListener ? (target.addEventListener(eventType, callback, !1), { remove: function() { target.removeEventListener(eventType, callback, !1); } }) : target.attachEvent ? (target.attachEvent("on" + eventType, callback), { remove: function() { target.detachEvent("on" + eventType, callback); } }) : void 0; }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function(target, eventType, callback) { return target.addEventListener ? (target.addEventListener(eventType, callback, !0), { remove: function() { target.removeEventListener(eventType, callback, !0); } }) : ("production" !== process.env.NODE_ENV && console.error("Attempted to listen to events during the capture phase on a browser that does not support the capture phase. Your application will not receive some events."), { remove: emptyFunction }); }, registerDefault: function() {} }; module.exports = EventListener; }).call(exports, __webpack_require__(17)); }, /* 137 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ "use strict"; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { return scrollable === window ? { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop } : { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; }, /* 138 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ "use strict"; var DOMProperty = __webpack_require__(39), EventPluginHub = __webpack_require__(20), EventPluginUtils = __webpack_require__(22), ReactComponentEnvironment = __webpack_require__(116), ReactClass = __webpack_require__(139), ReactEmptyComponent = __webpack_require__(125), ReactBrowserEventEmitter = __webpack_require__(95), ReactNativeComponent = __webpack_require__(126), ReactUpdates = __webpack_require__(41), ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventPluginUtils: EventPluginUtils.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; }, /* 139 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactClass */ "use strict"; // noop function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) typeDef.hasOwnProperty(propName) && ("production" !== process.env.NODE_ENV ? warning("function" == typeof typeDef[propName], "%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.", Constructor.displayName || "ReactClass", ReactPropTypeLocationNames[location], propName) : void 0); } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. ReactClassMixin.hasOwnProperty(name) && (specPolicy !== SpecPolicy.OVERRIDE_BASE ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.", name) : invariant(!1) : void 0), // Disallow defining methods more than once unless explicitly allowed. isAlreadyDefined && (specPolicy !== SpecPolicy.DEFINE_MANY && specPolicy !== SpecPolicy.DEFINE_MANY_MERGED ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.", name) : invariant(!1) : void 0); } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (spec) { "function" == typeof spec ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClass: You're attempting to use a component class or function as a mixin. Instead, just use a regular object.") : invariant(!1) : void 0, ReactElement.isValidElement(spec) ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object.") : invariant(!1) : void 0; var proto = Constructor.prototype, autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. spec.hasOwnProperty(MIXINS_KEY) && RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); for (var name in spec) if (spec.hasOwnProperty(name) && name !== MIXINS_KEY) { var property = spec[name], isAlreadyDefined = proto.hasOwnProperty(name); if (validateMethodOverride(isAlreadyDefined, name), RESERVED_SPEC_KEYS.hasOwnProperty(name)) RESERVED_SPEC_KEYS[name](Constructor, property); else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name), isFunction = "function" == typeof property, shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== !1; if (shouldAutoBind) autoBindPairs.push(name, property), proto[name] = property; else if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; !isReactClassMethod || specPolicy !== SpecPolicy.DEFINE_MANY_MERGED && specPolicy !== SpecPolicy.DEFINE_MANY ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.", specPolicy, name) : invariant(!1) : void 0, // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. specPolicy === SpecPolicy.DEFINE_MANY_MERGED ? proto[name] = createMergedResultFunction(proto[name], property) : specPolicy === SpecPolicy.DEFINE_MANY && (proto[name] = createChainedFunction(proto[name], property)); } else proto[name] = property, "production" !== process.env.NODE_ENV && "function" == typeof property && spec.displayName && (proto[name].displayName = spec.displayName + "_" + name); } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (statics) for (var name in statics) { var property = statics[name]; if (statics.hasOwnProperty(name)) { var isReserved = name in RESERVED_SPEC_KEYS; isReserved ? "production" !== process.env.NODE_ENV ? invariant(!1, 'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.', name) : invariant(!1) : void 0; var isInherited = name in Constructor; isInherited ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.", name) : invariant(!1) : void 0, Constructor[name] = property; } } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { one && two && "object" == typeof one && "object" == typeof two ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.") : invariant(!1); for (var key in two) two.hasOwnProperty(key) && (void 0 !== one[key] ? "production" !== process.env.NODE_ENV ? invariant(!1, "mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.", key) : invariant(!1) : void 0, one[key] = two[key]); return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function() { var a = one.apply(this, arguments), b = two.apply(this, arguments); if (null == a) return b; if (null == b) return a; var c = {}; return mergeIntoWithNoDuplicateKeys(c, a), mergeIntoWithNoDuplicateKeys(c, b), c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function() { one.apply(this, arguments), two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if ("production" !== process.env.NODE_ENV) { boundMethod.__reactBoundContext = component, boundMethod.__reactBoundMethod = method, boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName, _bind = boundMethod.bind; boundMethod.bind = function(newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _len > _key; _key++) args[_key - 1] = arguments[_key]; // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && null !== newThis) "production" !== process.env.NODE_ENV ? warning(!1, "bind(): React component methods may only be bound to the component instance. See %s", componentName) : void 0; else if (!args.length) return "production" !== process.env.NODE_ENV ? warning(!1, "bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See %s", componentName) : void 0, boundMethod; var reboundMethod = _bind.apply(boundMethod, arguments); return reboundMethod.__reactBoundContext = component, reboundMethod.__reactBoundMethod = method, reboundMethod.__reactBoundArguments = args, reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { for (var pairs = component.__reactAutoBindPairs, i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i], method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } var _assign = __webpack_require__(30), ReactComponent = __webpack_require__(140), ReactElement = __webpack_require__(103), ReactPropTypeLocations = __webpack_require__(108), ReactPropTypeLocationNames = __webpack_require__(106), ReactNoopUpdateQueue = __webpack_require__(141), emptyObject = __webpack_require__(123), invariant = __webpack_require__(18), keyMirror = __webpack_require__(16), keyOf = __webpack_require__(36), warning = __webpack_require__(24), MIXINS_KEY = keyOf({ mixins: null }), SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }), injectedMixins = [], ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }, RESERVED_SPEC_KEYS = { displayName: function(Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function(Constructor, mixins) { if (mixins) for (var i = 0; i < mixins.length; i++) mixSpecIntoComponent(Constructor, mixins[i]); }, childContextTypes: function(Constructor, childContextTypes) { "production" !== process.env.NODE_ENV && validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext), Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function(Constructor, contextTypes) { "production" !== process.env.NODE_ENV && validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context), Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function(Constructor, getDefaultProps) { Constructor.getDefaultProps ? Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps) : Constructor.getDefaultProps = getDefaultProps; }, propTypes: function(Constructor, propTypes) { "production" !== process.env.NODE_ENV && validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop), Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function() {} }, ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function(newState, callback) { this.updater.enqueueReplaceState(this, newState), callback && this.updater.enqueueCallback(this, callback, "replaceState"); }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { return this.updater.isMounted(this); } }, ReactClassComponent = function() {}; _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function(spec) { var Constructor = function(props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(this instanceof Constructor, "Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory") : void 0), // Wire up auto-binding this.__reactAutoBindPairs.length && bindAutoBindMethods(this), this.props = props, this.context = context, this.refs = emptyObject, this.updater = updater || ReactNoopUpdateQueue, this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; "production" !== process.env.NODE_ENV && void 0 === initialState && this.getInitialState._isMockFunction && (// This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null), "object" != typeof initialState || Array.isArray(initialState) ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s.getInitialState(): must return an object or null", Constructor.displayName || "ReactCompositeComponent") : invariant(!1) : void 0, this.state = initialState; }; Constructor.prototype = new ReactClassComponent(), Constructor.prototype.constructor = Constructor, Constructor.prototype.__reactAutoBindPairs = [], injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)), mixSpecIntoComponent(Constructor, spec), // Initialize the defaultProps property after all mixins have been merged. Constructor.getDefaultProps && (Constructor.defaultProps = Constructor.getDefaultProps()), "production" !== process.env.NODE_ENV && (// This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. Constructor.getDefaultProps && (Constructor.getDefaultProps.isReactClassApproved = {}), Constructor.prototype.getInitialState && (Constructor.prototype.getInitialState.isReactClassApproved = {})), Constructor.prototype.render ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "createClass(...): Class specification must implement a `render` method.") : invariant(!1), "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!Constructor.prototype.componentShouldUpdate, "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", spec.displayName || "A component") : void 0, "production" !== process.env.NODE_ENV ? warning(!Constructor.prototype.componentWillRecieveProps, "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", spec.displayName || "A component") : void 0); // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) Constructor.prototype[methodName] || (Constructor.prototype[methodName] = null); return Constructor; }, injection: { injectMixin: function(mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; }).call(exports, __webpack_require__(17)); }, /* 140 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ "use strict"; /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props, this.context = context, this.refs = emptyObject, // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } var ReactNoopUpdateQueue = __webpack_require__(141), ReactInstrumentation = __webpack_require__(44), canDefineProperty = __webpack_require__(105), emptyObject = __webpack_require__(123), invariant = __webpack_require__(18), warning = __webpack_require__(24); /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (ReactComponent.prototype.isReactComponent = {}, /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function(partialState, callback) { "object" != typeof partialState && "function" != typeof partialState && null != partialState ? "production" !== process.env.NODE_ENV ? invariant(!1, "setState(...): takes an object of state variables to update or a function which returns an object of state variables.") : invariant(!1) : void 0, "production" !== process.env.NODE_ENV && (ReactInstrumentation.debugTool.onSetState(), "production" !== process.env.NODE_ENV ? warning(null != partialState, "setState(...): You passed an undefined or null state object; instead, use forceUpdate().") : void 0), this.updater.enqueueSetState(this, partialState), callback && this.updater.enqueueCallback(this, callback, "setState"); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function(callback) { this.updater.enqueueForceUpdate(this), callback && this.updater.enqueueCallback(this, callback, "forceUpdate"); }, "production" !== process.env.NODE_ENV) { var deprecatedAPIs = { isMounted: [ "isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks." ], replaceState: [ "replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)." ] }, defineDeprecationWarning = function(methodName, info) { canDefineProperty && Object.defineProperty(ReactComponent.prototype, methodName, { get: function() { "production" !== process.env.NODE_ENV ? warning(!1, "%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]) : void 0; } }); }; for (var fnName in deprecatedAPIs) deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } module.exports = ReactComponent; }).call(exports, __webpack_require__(17)); }, /* 141 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNoopUpdateQueue */ "use strict"; function warnTDZ(publicInstance, callerName) { "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!1, "%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op. Please check the code for the %s component.", callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || "") : void 0); } var warning = __webpack_require__(24), ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function(publicInstance) { return !1; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function(publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function(publicInstance) { warnTDZ(publicInstance, "forceUpdate"); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function(publicInstance, completeState) { warnTDZ(publicInstance, "replaceState"); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function(publicInstance, partialState) { warnTDZ(publicInstance, "setState"); } }; module.exports = ReactNoopUpdateQueue; }).call(exports, __webpack_require__(17)); }, /* 142 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction */ "use strict"; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(useCreateElement) { this.reinitializeTransaction(), // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = !1, this.reactMountReady = CallbackQueue.getPooled(null), this.useCreateElement = useCreateElement; } var _assign = __webpack_require__(30), CallbackQueue = __webpack_require__(42), PooledClass = __webpack_require__(31), ReactBrowserEventEmitter = __webpack_require__(95), ReactInputSelection = __webpack_require__(143), Transaction = __webpack_require__(54), SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }, EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function() { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); return ReactBrowserEventEmitter.setEnabled(!1), currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function(previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }, ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function() { this.reactMountReady.notifyAll(); } }, TRANSACTION_WRAPPERS = [ SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING ], Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function() { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function(checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function() { CallbackQueue.release(this.reactMountReady), this.reactMountReady = null; } }; _assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin), PooledClass.addPoolingTo(ReactReconcileTransaction), module.exports = ReactReconcileTransaction; }, /* 143 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ "use strict"; function isInDocument(node) { return containsNode(document.documentElement, node); } var ReactDOMSelection = __webpack_require__(144), containsNode = __webpack_require__(146), focusNode = __webpack_require__(81), getActiveElement = __webpack_require__(149), ReactInputSelection = { hasSelectionCapabilities: function(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && ("input" === nodeName && "text" === elem.type || "textarea" === nodeName || "true" === elem.contentEditable); }, getSelectionInformation: function() { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function(priorSelectionInformation) { var curFocusedElem = getActiveElement(), priorFocusedElem = priorSelectionInformation.focusedElem, priorSelectionRange = priorSelectionInformation.selectionRange; curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem) && (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem) && ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange), focusNode(priorFocusedElem)); }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function(input) { var selection; if ("selectionStart" in input) // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; else if (document.selection && input.nodeName && "input" === input.nodeName.toLowerCase()) { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. range.parentElement() === input && (selection = { start: -range.moveStart("character", -input.value.length), end: -range.moveEnd("character", -input.value.length) }); } else // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function(input, offsets) { var start = offsets.start, end = offsets.end; if (void 0 === end && (end = start), "selectionStart" in input) input.selectionStart = start, input.selectionEnd = Math.min(end, input.value.length); else if (document.selection && input.nodeName && "input" === input.nodeName.toLowerCase()) { var range = input.createTextRange(); range.collapse(!0), range.moveStart("character", start), range.moveEnd("character", end - start), range.select(); } else ReactDOMSelection.setOffsets(input, offsets); } }; module.exports = ReactInputSelection; }, /* 144 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ "use strict"; /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection, selectedRange = selection.createRange(), selectedLength = selectedRange.text.length, fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node), fromStart.setEndPoint("EndToStart", selectedRange); var startOffset = fromStart.text.length, endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || 0 === selection.rangeCount) return null; var anchorNode = selection.anchorNode, anchorOffset = selection.anchorOffset, focusNode = selection.focusNode, focusOffset = selection.focusOffset, currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType, currentRange.endContainer.nodeType; } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset), rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length, tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node), tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset), start = isTempRangeCollapsed ? 0 : tempRange.toString().length, end = start + rangeLength, detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset), detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var start, end, range = document.selection.createRange().duplicate(); void 0 === offsets.end ? (start = offsets.start, end = start) : offsets.start > offsets.end ? (start = offsets.end, end = offsets.start) : (start = offsets.start, end = offsets.end), range.moveToElementText(node), range.moveStart("character", start), range.setEndPoint("EndToStart", range), range.moveEnd("character", end - start), range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (window.getSelection) { var selection = window.getSelection(), length = node[getTextContentAccessor()].length, start = Math.min(offsets.start, length), end = void 0 === offsets.end ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start, start = temp; } var startMarker = getNodeForCharacterOffset(node, start), endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset), selection.removeAllRanges(), start > end ? (selection.addRange(range), selection.extend(endMarker.node, endMarker.offset)) : (range.setEnd(endMarker.node, endMarker.offset), selection.addRange(range)); } } } var ExecutionEnvironment = __webpack_require__(28), getNodeForCharacterOffset = __webpack_require__(145), getTextContentAccessor = __webpack_require__(32), useIEOffsets = ExecutionEnvironment.canUseDOM && "selection" in document && !("getSelection" in window), ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; }, /* 145 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNodeForCharacterOffset */ "use strict"; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { for (;node && node.firstChild; ) node = node.firstChild; return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { for (;node; ) { if (node.nextSibling) return node.nextSibling; node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { for (var node = getLeafNode(root), nodeStart = 0, nodeEnd = 0; node; ) { if (3 === node.nodeType) { if (nodeEnd = nodeStart + node.textContent.length, offset >= nodeStart && nodeEnd >= offset) return { node: node, offset: offset - nodeStart }; nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; }, /* 146 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. */ function containsNode(outerNode, innerNode) { return outerNode && innerNode ? outerNode === innerNode ? !0 : isTextNode(outerNode) ? !1 : isTextNode(innerNode) ? containsNode(outerNode, innerNode.parentNode) : "contains" in outerNode ? outerNode.contains(innerNode) : outerNode.compareDocumentPosition ? !!(16 & outerNode.compareDocumentPosition(innerNode)) : !1 : !1; } /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var isTextNode = __webpack_require__(147); module.exports = containsNode; }, /* 147 */ /***/ function(module, exports, __webpack_require__) { "use strict"; /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && 3 == object.nodeType; } /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var isNode = __webpack_require__(148); module.exports = isTextNode; }, /* 148 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !(!object || !("function" == typeof Node ? object instanceof Node : "object" == typeof object && "number" == typeof object.nodeType && "string" == typeof object.nodeName)); } module.exports = isNode; }, /* 149 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ function getActiveElement() { if ("undefined" == typeof document) return null; try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; }, /* 150 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ "use strict"; var NS = { xlink: "http://www.w3.org/1999/xlink", xml: "http://www.w3.org/XML/1998/namespace" }, ATTRS = { accentHeight: "accent-height", accumulate: 0, additive: 0, alignmentBaseline: "alignment-baseline", allowReorder: "allowReorder", alphabetic: 0, amplitude: 0, arabicForm: "arabic-form", ascent: 0, attributeName: "attributeName", attributeType: "attributeType", autoReverse: "autoReverse", azimuth: 0, baseFrequency: "baseFrequency", baseProfile: "baseProfile", baselineShift: "baseline-shift", bbox: 0, begin: 0, bias: 0, by: 0, calcMode: "calcMode", capHeight: "cap-height", clip: 0, clipPath: "clip-path", clipRule: "clip-rule", clipPathUnits: "clipPathUnits", colorInterpolation: "color-interpolation", colorInterpolationFilters: "color-interpolation-filters", colorProfile: "color-profile", colorRendering: "color-rendering", contentScriptType: "contentScriptType", contentStyleType: "contentStyleType", cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: "diffuseConstant", direction: 0, display: 0, divisor: 0, dominantBaseline: "dominant-baseline", dur: 0, dx: 0, dy: 0, edgeMode: "edgeMode", elevation: 0, enableBackground: "enable-background", end: 0, exponent: 0, externalResourcesRequired: "externalResourcesRequired", fill: 0, fillOpacity: "fill-opacity", fillRule: "fill-rule", filter: 0, filterRes: "filterRes", filterUnits: "filterUnits", floodColor: "flood-color", floodOpacity: "flood-opacity", focusable: 0, fontFamily: "font-family", fontSize: "font-size", fontSizeAdjust: "font-size-adjust", fontStretch: "font-stretch", fontStyle: "font-style", fontVariant: "font-variant", fontWeight: "font-weight", format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: "glyph-name", glyphOrientationHorizontal: "glyph-orientation-horizontal", glyphOrientationVertical: "glyph-orientation-vertical", glyphRef: "glyphRef", gradientTransform: "gradientTransform", gradientUnits: "gradientUnits", hanging: 0, horizAdvX: "horiz-adv-x", horizOriginX: "horiz-origin-x", ideographic: 0, imageRendering: "image-rendering", "in": 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: "kernelMatrix", kernelUnitLength: "kernelUnitLength", kerning: 0, keyPoints: "keyPoints", keySplines: "keySplines", keyTimes: "keyTimes", lengthAdjust: "lengthAdjust", letterSpacing: "letter-spacing", lightingColor: "lighting-color", limitingConeAngle: "limitingConeAngle", local: 0, markerEnd: "marker-end", markerMid: "marker-mid", markerStart: "marker-start", markerHeight: "markerHeight", markerUnits: "markerUnits", markerWidth: "markerWidth", mask: 0, maskContentUnits: "maskContentUnits", maskUnits: "maskUnits", mathematical: 0, mode: 0, numOctaves: "numOctaves", offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: "overline-position", overlineThickness: "overline-thickness", paintOrder: "paint-order", panose1: "panose-1", pathLength: "pathLength", patternContentUnits: "patternContentUnits", patternTransform: "patternTransform", patternUnits: "patternUnits", pointerEvents: "pointer-events", points: 0, pointsAtX: "pointsAtX", pointsAtY: "pointsAtY", pointsAtZ: "pointsAtZ", preserveAlpha: "preserveAlpha", preserveAspectRatio: "preserveAspectRatio", primitiveUnits: "primitiveUnits", r: 0, radius: 0, refX: "refX", refY: "refY", renderingIntent: "rendering-intent", repeatCount: "repeatCount", repeatDur: "repeatDur", requiredExtensions: "requiredExtensions", requiredFeatures: "requiredFeatures", restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: "shape-rendering", slope: 0, spacing: 0, specularConstant: "specularConstant", specularExponent: "specularExponent", speed: 0, spreadMethod: "spreadMethod", startOffset: "startOffset", stdDeviation: "stdDeviation", stemh: 0, stemv: 0, stitchTiles: "stitchTiles", stopColor: "stop-color", stopOpacity: "stop-opacity", strikethroughPosition: "strikethrough-position", strikethroughThickness: "strikethrough-thickness", string: 0, stroke: 0, strokeDasharray: "stroke-dasharray", strokeDashoffset: "stroke-dashoffset", strokeLinecap: "stroke-linecap", strokeLinejoin: "stroke-linejoin", strokeMiterlimit: "stroke-miterlimit", strokeOpacity: "stroke-opacity", strokeWidth: "stroke-width", surfaceScale: "surfaceScale", systemLanguage: "systemLanguage", tableValues: "tableValues", targetX: "targetX", targetY: "targetY", textAnchor: "text-anchor", textDecoration: "text-decoration", textRendering: "text-rendering", textLength: "textLength", to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: "underline-position", underlineThickness: "underline-thickness", unicode: 0, unicodeBidi: "unicode-bidi", unicodeRange: "unicode-range", unitsPerEm: "units-per-em", vAlphabetic: "v-alphabetic", vHanging: "v-hanging", vIdeographic: "v-ideographic", vMathematical: "v-mathematical", values: 0, vectorEffect: "vector-effect", version: 0, vertAdvY: "vert-adv-y", vertOriginX: "vert-origin-x", vertOriginY: "vert-origin-y", viewBox: "viewBox", viewTarget: "viewTarget", visibility: 0, widths: 0, wordSpacing: "word-spacing", writingMode: "writing-mode", x: 0, xHeight: "x-height", x1: 0, x2: 0, xChannelSelector: "xChannelSelector", xlinkActuate: "xlink:actuate", xlinkArcrole: "xlink:arcrole", xlinkHref: "xlink:href", xlinkRole: "xlink:role", xlinkShow: "xlink:show", xlinkTitle: "xlink:title", xlinkType: "xlink:type", xmlBase: "xml:base", xmlLang: "xml:lang", xmlSpace: "xml:space", y: 0, y1: 0, y2: 0, yChannelSelector: "yChannelSelector", z: 0, zoomAndPan: "zoomAndPan" }, SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function(key) { SVGDOMPropertyConfig.Properties[key] = 0, ATTRS[key] && (SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]); }), module.exports = SVGDOMPropertyConfig; }, /* 151 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ "use strict"; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ("selectionStart" in node && ReactInputSelection.hasSelectionCapabilities(node)) return { start: node.selectionStart, end: node.selectionEnd }; if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || null == activeElement || activeElement !== getActiveElement()) return null; // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); return syntheticEvent.type = "select", syntheticEvent.target = activeElement, EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent), syntheticEvent; } return null; } var EventConstants = __webpack_require__(15), EventPropagators = __webpack_require__(19), ExecutionEnvironment = __webpack_require__(28), ReactDOMComponentTree = __webpack_require__(38), ReactInputSelection = __webpack_require__(143), SyntheticEvent = __webpack_require__(34), getActiveElement = __webpack_require__(149), isTextInputElement = __webpack_require__(57), keyOf = __webpack_require__(36), shallowEqual = __webpack_require__(129), topLevelTypes = EventConstants.topLevelTypes, skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && "documentMode" in document && document.documentMode <= 11, eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({ onSelect: null }), captured: keyOf({ onSelectCapture: null }) }, dependencies: [ topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange ] } }, activeElement = null, activeElementInst = null, lastSelection = null, mouseDown = !1, hasListener = !1, ON_SELECT_KEY = keyOf({ onSelect: null }), SelectEventPlugin = { eventTypes: eventTypes, extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (!hasListener) return null; var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: (isTextInputElement(targetNode) || "true" === targetNode.contentEditable) && (activeElement = targetNode, activeElementInst = targetInst, lastSelection = null); break; case topLevelTypes.topBlur: activeElement = null, activeElementInst = null, lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = !0; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: return mouseDown = !1, constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case topLevelTypes.topSelectionChange: if (skipSelectionChangeEvent) break; // falls through case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function(inst, registrationName, listener) { registrationName === ON_SELECT_KEY && (hasListener = !0); } }; module.exports = SelectEventPlugin; }, /* 152 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ "use strict"; var EventConstants = __webpack_require__(15), EventListener = __webpack_require__(136), EventPropagators = __webpack_require__(19), ReactDOMComponentTree = __webpack_require__(38), SyntheticAnimationEvent = __webpack_require__(153), SyntheticClipboardEvent = __webpack_require__(154), SyntheticEvent = __webpack_require__(34), SyntheticFocusEvent = __webpack_require__(155), SyntheticKeyboardEvent = __webpack_require__(156), SyntheticMouseEvent = __webpack_require__(60), SyntheticDragEvent = __webpack_require__(159), SyntheticTouchEvent = __webpack_require__(160), SyntheticTransitionEvent = __webpack_require__(161), SyntheticUIEvent = __webpack_require__(61), SyntheticWheelEvent = __webpack_require__(162), emptyFunction = __webpack_require__(25), getEventCharCode = __webpack_require__(157), invariant = __webpack_require__(18), keyOf = __webpack_require__(36), topLevelTypes = EventConstants.topLevelTypes, eventTypes = { abort: { phasedRegistrationNames: { bubbled: keyOf({ onAbort: !0 }), captured: keyOf({ onAbortCapture: !0 }) } }, animationEnd: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationEnd: !0 }), captured: keyOf({ onAnimationEndCapture: !0 }) } }, animationIteration: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationIteration: !0 }), captured: keyOf({ onAnimationIterationCapture: !0 }) } }, animationStart: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationStart: !0 }), captured: keyOf({ onAnimationStartCapture: !0 }) } }, blur: { phasedRegistrationNames: { bubbled: keyOf({ onBlur: !0 }), captured: keyOf({ onBlurCapture: !0 }) } }, canPlay: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlay: !0 }), captured: keyOf({ onCanPlayCapture: !0 }) } }, canPlayThrough: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlayThrough: !0 }), captured: keyOf({ onCanPlayThroughCapture: !0 }) } }, click: { phasedRegistrationNames: { bubbled: keyOf({ onClick: !0 }), captured: keyOf({ onClickCapture: !0 }) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({ onContextMenu: !0 }), captured: keyOf({ onContextMenuCapture: !0 }) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({ onCopy: !0 }), captured: keyOf({ onCopyCapture: !0 }) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({ onCut: !0 }), captured: keyOf({ onCutCapture: !0 }) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({ onDoubleClick: !0 }), captured: keyOf({ onDoubleClickCapture: !0 }) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({ onDrag: !0 }), captured: keyOf({ onDragCapture: !0 }) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnd: !0 }), captured: keyOf({ onDragEndCapture: !0 }) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnter: !0 }), captured: keyOf({ onDragEnterCapture: !0 }) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({ onDragExit: !0 }), captured: keyOf({ onDragExitCapture: !0 }) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({ onDragLeave: !0 }), captured: keyOf({ onDragLeaveCapture: !0 }) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({ onDragOver: !0 }), captured: keyOf({ onDragOverCapture: !0 }) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({ onDragStart: !0 }), captured: keyOf({ onDragStartCapture: !0 }) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({ onDrop: !0 }), captured: keyOf({ onDropCapture: !0 }) } }, durationChange: { phasedRegistrationNames: { bubbled: keyOf({ onDurationChange: !0 }), captured: keyOf({ onDurationChangeCapture: !0 }) } }, emptied: { phasedRegistrationNames: { bubbled: keyOf({ onEmptied: !0 }), captured: keyOf({ onEmptiedCapture: !0 }) } }, encrypted: { phasedRegistrationNames: { bubbled: keyOf({ onEncrypted: !0 }), captured: keyOf({ onEncryptedCapture: !0 }) } }, ended: { phasedRegistrationNames: { bubbled: keyOf({ onEnded: !0 }), captured: keyOf({ onEndedCapture: !0 }) } }, error: { phasedRegistrationNames: { bubbled: keyOf({ onError: !0 }), captured: keyOf({ onErrorCapture: !0 }) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({ onFocus: !0 }), captured: keyOf({ onFocusCapture: !0 }) } }, input: { phasedRegistrationNames: { bubbled: keyOf({ onInput: !0 }), captured: keyOf({ onInputCapture: !0 }) } }, invalid: { phasedRegistrationNames: { bubbled: keyOf({ onInvalid: !0 }), captured: keyOf({ onInvalidCapture: !0 }) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({ onKeyDown: !0 }), captured: keyOf({ onKeyDownCapture: !0 }) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({ onKeyPress: !0 }), captured: keyOf({ onKeyPressCapture: !0 }) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({ onKeyUp: !0 }), captured: keyOf({ onKeyUpCapture: !0 }) } }, load: { phasedRegistrationNames: { bubbled: keyOf({ onLoad: !0 }), captured: keyOf({ onLoadCapture: !0 }) } }, loadedData: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedData: !0 }), captured: keyOf({ onLoadedDataCapture: !0 }) } }, loadedMetadata: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedMetadata: !0 }), captured: keyOf({ onLoadedMetadataCapture: !0 }) } }, loadStart: { phasedRegistrationNames: { bubbled: keyOf({ onLoadStart: !0 }), captured: keyOf({ onLoadStartCapture: !0 }) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({ onMouseDown: !0 }), captured: keyOf({ onMouseDownCapture: !0 }) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({ onMouseMove: !0 }), captured: keyOf({ onMouseMoveCapture: !0 }) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOut: !0 }), captured: keyOf({ onMouseOutCapture: !0 }) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOver: !0 }), captured: keyOf({ onMouseOverCapture: !0 }) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({ onMouseUp: !0 }), captured: keyOf({ onMouseUpCapture: !0 }) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({ onPaste: !0 }), captured: keyOf({ onPasteCapture: !0 }) } }, pause: { phasedRegistrationNames: { bubbled: keyOf({ onPause: !0 }), captured: keyOf({ onPauseCapture: !0 }) } }, play: { phasedRegistrationNames: { bubbled: keyOf({ onPlay: !0 }), captured: keyOf({ onPlayCapture: !0 }) } }, playing: { phasedRegistrationNames: { bubbled: keyOf({ onPlaying: !0 }), captured: keyOf({ onPlayingCapture: !0 }) } }, progress: { phasedRegistrationNames: { bubbled: keyOf({ onProgress: !0 }), captured: keyOf({ onProgressCapture: !0 }) } }, rateChange: { phasedRegistrationNames: { bubbled: keyOf({ onRateChange: !0 }), captured: keyOf({ onRateChangeCapture: !0 }) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({ onReset: !0 }), captured: keyOf({ onResetCapture: !0 }) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({ onScroll: !0 }), captured: keyOf({ onScrollCapture: !0 }) } }, seeked: { phasedRegistrationNames: { bubbled: keyOf({ onSeeked: !0 }), captured: keyOf({ onSeekedCapture: !0 }) } }, seeking: { phasedRegistrationNames: { bubbled: keyOf({ onSeeking: !0 }), captured: keyOf({ onSeekingCapture: !0 }) } }, stalled: { phasedRegistrationNames: { bubbled: keyOf({ onStalled: !0 }), captured: keyOf({ onStalledCapture: !0 }) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({ onSubmit: !0 }), captured: keyOf({ onSubmitCapture: !0 }) } }, suspend: { phasedRegistrationNames: { bubbled: keyOf({ onSuspend: !0 }), captured: keyOf({ onSuspendCapture: !0 }) } }, timeUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onTimeUpdate: !0 }), captured: keyOf({ onTimeUpdateCapture: !0 }) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({ onTouchCancel: !0 }), captured: keyOf({ onTouchCancelCapture: !0 }) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTouchEnd: !0 }), captured: keyOf({ onTouchEndCapture: !0 }) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({ onTouchMove: !0 }), captured: keyOf({ onTouchMoveCapture: !0 }) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({ onTouchStart: !0 }), captured: keyOf({ onTouchStartCapture: !0 }) } }, transitionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTransitionEnd: !0 }), captured: keyOf({ onTransitionEndCapture: !0 }) } }, volumeChange: { phasedRegistrationNames: { bubbled: keyOf({ onVolumeChange: !0 }), captured: keyOf({ onVolumeChangeCapture: !0 }) } }, waiting: { phasedRegistrationNames: { bubbled: keyOf({ onWaiting: !0 }), captured: keyOf({ onWaitingCapture: !0 }) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({ onWheel: !0 }), captured: keyOf({ onWheelCapture: !0 }) } } }, topLevelEventsToDispatchConfig = { topAbort: eventTypes.abort, topAnimationEnd: eventTypes.animationEnd, topAnimationIteration: eventTypes.animationIteration, topAnimationStart: eventTypes.animationStart, topBlur: eventTypes.blur, topCanPlay: eventTypes.canPlay, topCanPlayThrough: eventTypes.canPlayThrough, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topDurationChange: eventTypes.durationChange, topEmptied: eventTypes.emptied, topEncrypted: eventTypes.encrypted, topEnded: eventTypes.ended, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topInvalid: eventTypes.invalid, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topLoadedData: eventTypes.loadedData, topLoadedMetadata: eventTypes.loadedMetadata, topLoadStart: eventTypes.loadStart, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topPause: eventTypes.pause, topPlay: eventTypes.play, topPlaying: eventTypes.playing, topProgress: eventTypes.progress, topRateChange: eventTypes.rateChange, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSeeked: eventTypes.seeked, topSeeking: eventTypes.seeking, topStalled: eventTypes.stalled, topSubmit: eventTypes.submit, topSuspend: eventTypes.suspend, topTimeUpdate: eventTypes.timeUpdate, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topTransitionEnd: eventTypes.transitionEnd, topVolumeChange: eventTypes.volumeChange, topWaiting: eventTypes.waiting, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) topLevelEventsToDispatchConfig[type].dependencies = [ type ]; var ON_CLICK_KEY = keyOf({ onClick: null }), onClickListeners = {}, SimpleEventPlugin = { eventTypes: eventTypes, extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) return null; var EventConstructor; switch (topLevelType) { case topLevelTypes.topAbort: case topLevelTypes.topCanPlay: case topLevelTypes.topCanPlayThrough: case topLevelTypes.topDurationChange: case topLevelTypes.topEmptied: case topLevelTypes.topEncrypted: case topLevelTypes.topEnded: case topLevelTypes.topError: case topLevelTypes.topInput: case topLevelTypes.topInvalid: case topLevelTypes.topLoad: case topLevelTypes.topLoadedData: case topLevelTypes.topLoadedMetadata: case topLevelTypes.topLoadStart: case topLevelTypes.topPause: case topLevelTypes.topPlay: case topLevelTypes.topPlaying: case topLevelTypes.topProgress: case topLevelTypes.topRateChange: case topLevelTypes.topReset: case topLevelTypes.topSeeked: case topLevelTypes.topSeeking: case topLevelTypes.topStalled: case topLevelTypes.topSubmit: case topLevelTypes.topSuspend: case topLevelTypes.topTimeUpdate: case topLevelTypes.topVolumeChange: case topLevelTypes.topWaiting: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (0 === getEventCharCode(nativeEvent)) return null; /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (2 === nativeEvent.button) return null; /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topAnimationEnd: case topLevelTypes.topAnimationIteration: case topLevelTypes.topAnimationStart: EventConstructor = SyntheticAnimationEvent; break; case topLevelTypes.topTransitionEnd: EventConstructor = SyntheticTransitionEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; } EventConstructor ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "SimpleEventPlugin: Unhandled event type, `%s`.", topLevelType) : invariant(!1); var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); return EventPropagators.accumulateTwoPhaseDispatches(event), event; }, didPutListener: function(inst, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. if (registrationName === ON_CLICK_KEY) { var id = inst._rootNodeID, node = ReactDOMComponentTree.getNodeFromInstance(inst); onClickListeners[id] || (onClickListeners[id] = EventListener.listen(node, "click", emptyFunction)); } }, willDeleteListener: function(inst, registrationName) { if (registrationName === ON_CLICK_KEY) { var id = inst._rootNodeID; onClickListeners[id].remove(), delete onClickListeners[id]; } } }; module.exports = SimpleEventPlugin; }).call(exports, __webpack_require__(17)); }, /* 153 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticAnimationEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticEvent = __webpack_require__(34), AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface), module.exports = SyntheticAnimationEvent; }, /* 154 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticEvent = __webpack_require__(34), ClipboardEventInterface = { clipboardData: function(event) { return "clipboardData" in event ? event.clipboardData : window.clipboardData; } }; SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface), module.exports = SyntheticClipboardEvent; }, /* 155 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticUIEvent = __webpack_require__(61), FocusEventInterface = { relatedTarget: null }; SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface), module.exports = SyntheticFocusEvent; }, /* 156 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticUIEvent = __webpack_require__(61), getEventCharCode = __webpack_require__(157), getEventKey = __webpack_require__(158), getEventModifierState = __webpack_require__(63), KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function(event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. return "keypress" === event.type ? getEventCharCode(event) : 0; }, keyCode: function(event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. return "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0; }, which: function(event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. return "keypress" === event.type ? getEventCharCode(event) : "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0; } }; SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface), module.exports = SyntheticKeyboardEvent; }, /* 157 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode */ "use strict"; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode, keyCode = nativeEvent.keyCode; // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. // FF does not set `charCode` for the Enter-key, check against `keyCode`. // IE8 does not implement `charCode`, but `keyCode` has the correct value. // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. return "charCode" in nativeEvent ? (charCode = nativeEvent.charCode, 0 === charCode && 13 === keyCode && (charCode = 13)) : charCode = keyCode, charCode >= 32 || 13 === charCode ? charCode : 0; } module.exports = getEventCharCode; }, /* 158 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey */ "use strict"; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if ("Unidentified" !== key) return key; } // Browser does not implement `key`, polyfill as much of it as we can. if ("keypress" === nativeEvent.type) { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return 13 === charCode ? "Enter" : String.fromCharCode(charCode); } return "keydown" === nativeEvent.type || "keyup" === nativeEvent.type ? translateToKey[nativeEvent.keyCode] || "Unidentified" : ""; } var getEventCharCode = __webpack_require__(157), normalizeKey = { Esc: "Escape", Spacebar: " ", Left: "ArrowLeft", Up: "ArrowUp", Right: "ArrowRight", Down: "ArrowDown", Del: "Delete", Win: "OS", Menu: "ContextMenu", Apps: "ContextMenu", Scroll: "ScrollLock", MozPrintableKey: "Unidentified" }, translateToKey = { 8: "Backspace", 9: "Tab", 12: "Clear", 13: "Enter", 16: "Shift", 17: "Control", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Escape", 32: " ", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "ArrowLeft", 38: "ArrowUp", 39: "ArrowRight", 40: "ArrowDown", 45: "Insert", 46: "Delete", 112: "F1", 113: "F2", 114: "F3", 115: "F4", 116: "F5", 117: "F6", 118: "F7", 119: "F8", 120: "F9", 121: "F10", 122: "F11", 123: "F12", 144: "NumLock", 145: "ScrollLock", 224: "Meta" }; module.exports = getEventKey; }, /* 159 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticMouseEvent = __webpack_require__(60), DragEventInterface = { dataTransfer: null }; SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface), module.exports = SyntheticDragEvent; }, /* 160 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticUIEvent = __webpack_require__(61), getEventModifierState = __webpack_require__(63), TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface), module.exports = SyntheticTouchEvent; }, /* 161 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTransitionEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticEvent = __webpack_require__(34), TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface), module.exports = SyntheticTransitionEvent; }, /* 162 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent */ "use strict"; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } var SyntheticMouseEvent = __webpack_require__(60), WheelEventInterface = { deltaX: function(event) { // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). return "deltaX" in event ? event.deltaX : "wheelDeltaX" in event ? -event.wheelDeltaX : 0; }, deltaY: function(event) { // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). return "deltaY" in event ? event.deltaY : "wheelDeltaY" in event ? -event.wheelDeltaY : "wheelDelta" in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface), module.exports = SyntheticWheelEvent; }, /* 163 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRendering */ "use strict"; /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToStringImpl(element, makeStaticMarkup) { var transaction; try { return ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy), transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup), transaction.perform(function() { "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onBeginFlush(); var componentInstance = instantiateReactComponent(element), markup = ReactReconciler.mountComponent(componentInstance, transaction, null, ReactDOMContainerInfo(), emptyObject); return "production" !== process.env.NODE_ENV && (ReactInstrumentation.debugTool.onUnmountComponent(componentInstance._debugID), ReactInstrumentation.debugTool.onEndFlush()), makeStaticMarkup || (markup = ReactMarkupChecksum.addChecksumToMarkup(markup)), markup; }, null); } finally { ReactServerRenderingTransaction.release(transaction), // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } /** * Render a ReactElement to its initial HTML. This should only be used on the * server. * See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring */ function renderToString(element) { return ReactElement.isValidElement(element) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "renderToString(): You must pass a valid ReactElement.") : invariant(!1), renderToStringImpl(element, !1); } /** * Similar to renderToString, except this doesn't create extra DOM attributes * such as data-react-id that React uses internally. * See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostaticmarkup */ function renderToStaticMarkup(element) { return ReactElement.isValidElement(element) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "renderToStaticMarkup(): You must pass a valid ReactElement.") : invariant(!1), renderToStringImpl(element, !0); } var ReactDOMContainerInfo = __webpack_require__(164), ReactDefaultBatchingStrategy = __webpack_require__(134), ReactElement = __webpack_require__(103), ReactInstrumentation = __webpack_require__(44), ReactMarkupChecksum = __webpack_require__(165), ReactReconciler = __webpack_require__(51), ReactServerBatchingStrategy = __webpack_require__(167), ReactServerRenderingTransaction = __webpack_require__(128), ReactUpdates = __webpack_require__(41), emptyObject = __webpack_require__(123), instantiateReactComponent = __webpack_require__(118), invariant = __webpack_require__(18); module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; }).call(exports, __webpack_require__(17)); }, /* 164 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMContainerInfo */ "use strict"; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; return "production" !== process.env.NODE_ENV && (info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null), info; } var validateDOMNesting = __webpack_require__(130), DOC_NODE_TYPE = 9; module.exports = ReactDOMContainerInfo; }).call(exports, __webpack_require__(17)); }, /* 165 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ "use strict"; var adler32 = __webpack_require__(166), TAG_END = /\/?>/, COMMENT_START = /^<\!\-\-/, ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: "data-react-checksum", /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function(markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags, comments and self-closing tags) // Add checksum (handle both parent tags, comments and self-closing tags) return COMMENT_START.test(markup) ? markup : markup.replace(TAG_END, " " + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function(markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; }, /* 166 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 */ "use strict"; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { for (var a = 1, b = 0, i = 0, l = data.length, m = -4 & l; m > i; ) { for (var n = Math.min(i + 4096, m); n > i; i += 4) b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); a %= MOD, b %= MOD; } for (;l > i; i++) b += a += data.charCodeAt(i); return a %= MOD, b %= MOD, a | b << 16; } var MOD = 65521; module.exports = adler32; }, /* 167 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerBatchingStrategy */ "use strict"; var ReactServerBatchingStrategy = { isBatchingUpdates: !1, batchedUpdates: function(callback) {} }; module.exports = ReactServerBatchingStrategy; }, /* 168 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactVersion */ "use strict"; module.exports = "15.1.0"; }, /* 169 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.Collection = exports["default"] = void 0; var _Collection2 = __webpack_require__(170), _Collection3 = _interopRequireDefault(_Collection2); exports["default"] = _Collection3["default"], exports.Collection = _Collection3["default"]; }, /* 170 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (target[i] = obj[i]); return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function defaultCellGroupRenderer(_ref4) { var cellRenderer = _ref4.cellRenderer, cellSizeAndPositionGetter = _ref4.cellSizeAndPositionGetter, indices = _ref4.indices, isScrolling = _ref4.isScrolling; return indices.map(function(index) { var cellMetadata = cellSizeAndPositionGetter({ index: index }), renderedCell = cellRenderer({ index: index, isScrolling: isScrolling }); return null == renderedCell || renderedCell === !1 ? null : _react2["default"].createElement("div", { className: "Collection__cell", key: index, style: { height: cellMetadata.height, left: cellMetadata.x, top: cellMetadata.y, width: cellMetadata.width } }, renderedCell); }).filter(function(renderedCell) { return !!renderedCell; }); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _CollectionView = __webpack_require__(171), _CollectionView2 = _interopRequireDefault(_CollectionView), _calculateSizeAndPositionData2 = __webpack_require__(178), _calculateSizeAndPositionData3 = _interopRequireDefault(_calculateSizeAndPositionData2), _getUpdatedOffsetForIndex = __webpack_require__(181), _getUpdatedOffsetForIndex2 = _interopRequireDefault(_getUpdatedOffsetForIndex), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), Collection = function(_Component) { function Collection(props, context) { _classCallCheck(this, Collection); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Collection).call(this, props, context)); return _this._cellMetadata = [], _this._lastRenderedCellIndices = [], _this; } return _inherits(Collection, _Component), _createClass(Collection, [ { key: "recomputeCellSizesAndPositions", value: function() { this.refs.CollectionView.recomputeCellSizesAndPositions(); } }, { key: "render", value: function() { var props = _objectWithoutProperties(this.props, []); return _react2["default"].createElement(_CollectionView2["default"], _extends({ cellLayoutManager: this, ref: "CollectionView" }, props)); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "calculateSizeAndPositionData", value: function() { var _props = this.props, cellCount = _props.cellCount, cellSizeAndPositionGetter = _props.cellSizeAndPositionGetter, sectionSize = _props.sectionSize, data = (0, _calculateSizeAndPositionData3["default"])({ cellCount: cellCount, cellSizeAndPositionGetter: cellSizeAndPositionGetter, sectionSize: sectionSize }); this._cellMetadata = data.cellMetadata, this._sectionManager = data.sectionManager, this._height = data.height, this._width = data.width; } }, { key: "getLastRenderedIndices", value: function() { return this._lastRenderedCellIndices; } }, { key: "getScrollPositionForCell", value: function(_ref) { var align = _ref.align, cellIndex = _ref.cellIndex, height = _ref.height, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, width = _ref.width, cellCount = this.props.cellCount; if (cellIndex >= 0 && cellCount > cellIndex) { var cellMetadata = this._cellMetadata[cellIndex]; scrollLeft = (0, _getUpdatedOffsetForIndex2["default"])({ align: align, cellOffset: cellMetadata.x, cellSize: cellMetadata.width, containerSize: width, currentOffset: scrollLeft, targetIndex: cellIndex }), scrollTop = (0, _getUpdatedOffsetForIndex2["default"])({ align: align, cellOffset: cellMetadata.y, cellSize: cellMetadata.height, containerSize: height, currentOffset: scrollTop, targetIndex: cellIndex }); } return { scrollLeft: scrollLeft, scrollTop: scrollTop }; } }, { key: "getTotalSize", value: function() { return { height: this._height, width: this._width }; } }, { key: "cellRenderers", value: function(_ref2) { var _this2 = this, height = _ref2.height, isScrolling = _ref2.isScrolling, width = _ref2.width, x = _ref2.x, y = _ref2.y, _props2 = this.props, cellGroupRenderer = _props2.cellGroupRenderer, cellRenderer = _props2.cellRenderer; return this._lastRenderedCellIndices = this._sectionManager.getCellIndices({ height: height, width: width, x: x, y: y }), cellGroupRenderer({ cellRenderer: cellRenderer, cellSizeAndPositionGetter: function(_ref3) { var index = _ref3.index; return _this2._sectionManager.getCellMetadata({ index: index }); }, indices: this._lastRenderedCellIndices, isScrolling: isScrolling }); } } ]), Collection; }(_react.Component); Collection.propTypes = { "aria-label": _react.PropTypes.string, cellCount: _react.PropTypes.number.isRequired, cellGroupRenderer: _react.PropTypes.func.isRequired, cellRenderer: _react.PropTypes.func.isRequired, cellSizeAndPositionGetter: _react.PropTypes.func.isRequired, sectionSize: _react.PropTypes.number }, Collection.defaultProps = { "aria-label": "grid", cellGroupRenderer: defaultCellGroupRenderer }, exports["default"] = Collection; }, /* 171 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _createCallbackMemoizer = __webpack_require__(173), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _scrollbarSize = __webpack_require__(174), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _raf = __webpack_require__(176), _raf2 = _interopRequireDefault(_raf), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), IS_SCROLLING_TIMEOUT = 150, SCROLL_POSITION_CHANGE_REASONS = { OBSERVED: "observed", REQUESTED: "requested" }, CollectionView = function(_Component) { function CollectionView(props, context) { _classCallCheck(this, CollectionView); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(CollectionView).call(this, props, context)); return _this.state = { calculateSizeAndPositionDataOnNextUpdate: !1, isScrolling: !1, scrollLeft: 0, scrollTop: 0 }, _this._onSectionRenderedMemoizer = (0, _createCallbackMemoizer2["default"])(), _this._onScrollMemoizer = (0, _createCallbackMemoizer2["default"])(!1), _this._invokeOnSectionRenderedHelper = _this._invokeOnSectionRenderedHelper.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._updateScrollPositionForScrollToCell = _this._updateScrollPositionForScrollToCell.bind(_this), _this; } return _inherits(CollectionView, _Component), _createClass(CollectionView, [ { key: "recomputeCellSizesAndPositions", value: function() { this.setState({ calculateSizeAndPositionDataOnNextUpdate: !0 }); } }, { key: "componentDidMount", value: function() { var _props = this.props, cellLayoutManager = _props.cellLayoutManager, scrollLeft = _props.scrollLeft, scrollToCell = _props.scrollToCell, scrollTop = _props.scrollTop; this._scrollbarSizeMeasured || (this._scrollbarSize = (0, _scrollbarSize2["default"])(), this._scrollbarSizeMeasured = !0, this.setState({})), scrollToCell >= 0 ? this._updateScrollPositionForScrollToCell() : (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({ scrollLeft: scrollLeft, scrollTop: scrollTop }), this._invokeOnSectionRenderedHelper(); var _cellLayoutManager$ge = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge.height, totalWidth = _cellLayoutManager$ge.width; this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft || 0, scrollTop: scrollTop || 0, totalHeight: totalHeight, totalWidth: totalWidth }); } }, { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props2 = this.props, height = _props2.height, scrollToCell = _props2.scrollToCell, width = _props2.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollToAlignment = _state.scrollToAlignment, scrollTop = _state.scrollTop; scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this.refs.scrollingContainer.scrollLeft && (this.refs.scrollingContainer.scrollLeft = scrollLeft), scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this.refs.scrollingContainer.scrollTop && (this.refs.scrollingContainer.scrollTop = scrollTop)), height === prevProps.height && scrollToAlignment === prevProps.scrollToAlignment && scrollToCell === prevProps.scrollToCell && width === prevProps.width || this._updateScrollPositionForScrollToCell(), this._invokeOnSectionRenderedHelper(); } }, { key: "componentWillMount", value: function() { var cellLayoutManager = this.props.cellLayoutManager; cellLayoutManager.calculateSizeAndPositionData(), this._scrollbarSize = (0, _scrollbarSize2["default"])(), void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1, this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0; } }, { key: "componentWillUnmount", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { 0 !== nextProps.cellCount || 0 === nextState.scrollLeft && 0 === nextState.scrollTop ? nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({ scrollLeft: nextProps.scrollLeft, scrollTop: nextProps.scrollTop }) : this._setScrollPosition({ scrollLeft: 0, scrollTop: 0 }), (nextProps.cellCount !== this.props.cellCount || nextProps.cellLayoutManager !== this.props.cellLayoutManager || nextState.calculateSizeAndPositionDataOnNextUpdate) && nextProps.cellLayoutManager.calculateSizeAndPositionData(), nextState.calculateSizeAndPositionDataOnNextUpdate && this.setState({ calculateSizeAndPositionDataOnNextUpdate: !1 }); } }, { key: "render", value: function() { var _props3 = this.props, cellLayoutManager = _props3.cellLayoutManager, className = _props3.className, height = _props3.height, noContentRenderer = _props3.noContentRenderer, style = _props3.style, width = _props3.width, _state2 = this.state, isScrolling = _state2.isScrolling, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop, childrenToDisplay = height > 0 && width > 0 ? cellLayoutManager.cellRenderers({ height: height, isScrolling: isScrolling, width: width, x: scrollLeft, y: scrollTop }) : [], _cellLayoutManager$ge2 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge2.height, totalWidth = _cellLayoutManager$ge2.width, collectionStyle = _extends({}, style, { height: height, width: width }), verticalScrollBarSize = totalHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalWidth > width ? this._scrollbarSize : 0; return width >= totalWidth + verticalScrollBarSize && (collectionStyle.overflowX = "hidden"), height >= totalHeight + horizontalScrollBarSize && (collectionStyle.overflowY = "hidden"), _react2["default"].createElement("div", { ref: "scrollingContainer", "aria-label": this.props["aria-label"], className: (0, _classnames2["default"])("Collection", className), onScroll: this._onScroll, role: "grid", style: collectionStyle, tabIndex: 0 }, childrenToDisplay.length > 0 && _react2["default"].createElement("div", { className: "Collection__innerScrollContainer", style: { height: totalHeight, maxHeight: totalHeight, maxWidth: totalWidth, pointerEvents: isScrolling ? "none" : "auto", width: totalWidth } }, childrenToDisplay), 0 === childrenToDisplay.length && noContentRenderer()); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_enablePointerEventsAfterDelay", value: function() { var _this2 = this; this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._disablePointerEventsTimeoutId = setTimeout(function() { _this2._disablePointerEventsTimeoutId = null, _this2.setState({ isScrolling: !1 }); }, IS_SCROLLING_TIMEOUT); } }, { key: "_invokeOnSectionRenderedHelper", value: function() { var _props4 = this.props, cellLayoutManager = _props4.cellLayoutManager, onSectionRendered = _props4.onSectionRendered; this._onSectionRenderedMemoizer({ callback: onSectionRendered, indices: { indices: cellLayoutManager.getLastRenderedIndices() } }); } }, { key: "_invokeOnScrollMemoizer", value: function(_ref) { var _this3 = this, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, totalHeight = _ref.totalHeight, totalWidth = _ref.totalWidth; this._onScrollMemoizer({ callback: function(_ref2) { var scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, _props5 = _this3.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width; onScroll({ clientHeight: height, clientWidth: width, scrollHeight: totalHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: totalWidth }); }, indices: { scrollLeft: scrollLeft, scrollTop: scrollTop } }); } }, { key: "_setNextState", value: function(state) { var _this4 = this; this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId), this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() { _this4._setNextStateAnimationFrameId = null, _this4.setState(state); }); } }, { key: "_setScrollPosition", value: function(_ref3) { var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, newState = { scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED }; scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop), (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState); } }, { key: "_updateScrollPositionForScrollToCell", value: function() { var _props6 = this.props, cellLayoutManager = _props6.cellLayoutManager, height = _props6.height, scrollToAlignment = _props6.scrollToAlignment, scrollToCell = _props6.scrollToCell, width = _props6.width, _state3 = this.state, scrollLeft = _state3.scrollLeft, scrollTop = _state3.scrollTop; if (scrollToCell >= 0) { var scrollPosition = cellLayoutManager.getScrollPositionForCell({ align: scrollToAlignment, cellIndex: scrollToCell, height: height, scrollLeft: scrollLeft, scrollTop: scrollTop, width: width }); scrollPosition.scrollLeft === scrollLeft && scrollPosition.scrollTop === scrollTop || this._setScrollPosition(scrollPosition); } } }, { key: "_onScroll", value: function(event) { if (event.target === this.refs.scrollingContainer) { this._enablePointerEventsAfterDelay(); var _props7 = this.props, cellLayoutManager = _props7.cellLayoutManager, height = _props7.height, width = _props7.width, scrollbarSize = this._scrollbarSize, _cellLayoutManager$ge3 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge3.height, totalWidth = _cellLayoutManager$ge3.width, scrollLeft = Math.max(0, Math.min(totalWidth - width + scrollbarSize, event.target.scrollLeft)), scrollTop = Math.max(0, Math.min(totalHeight - height + scrollbarSize, event.target.scrollTop)); if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED; this.state.isScrolling || this.setState({ isScrolling: !0 }), this._setNextState({ isScrolling: !0, scrollLeft: scrollLeft, scrollPositionChangeReason: scrollPositionChangeReason, scrollTop: scrollTop }); } this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft, scrollTop: scrollTop, totalWidth: totalWidth, totalHeight: totalHeight }); } } } ]), CollectionView; }(_react.Component); CollectionView.propTypes = { "aria-label": _react.PropTypes.string, cellCount: _react.PropTypes.number.isRequired, cellLayoutManager: _react.PropTypes.object.isRequired, className: _react.PropTypes.string, height: _react.PropTypes.number.isRequired, noContentRenderer: _react.PropTypes.func.isRequired, onScroll: _react.PropTypes.func.isRequired, onSectionRendered: _react.PropTypes.func.isRequired, scrollLeft: _react.PropTypes.number, scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired, scrollToCell: _react.PropTypes.number, scrollTop: _react.PropTypes.number, style: _react.PropTypes.object, width: _react.PropTypes.number.isRequired }, CollectionView.defaultProps = { "aria-label": "grid", noContentRenderer: function() { return null; }, onScroll: function() { return null; }, onSectionRendered: function() { return null; }, scrollToAlignment: "auto", style: {} }, exports["default"] = CollectionView; }, /* 172 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ !function() { "use strict"; function classNames() { for (var classes = [], i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { var argType = typeof arg; if ("string" === argType || "number" === argType) classes.push(arg); else if (Array.isArray(arg)) classes.push(classNames.apply(null, arg)); else if ("object" === argType) for (var key in arg) hasOwn.call(arg, key) && arg[key] && classes.push(key); } } return classes.join(" "); } var hasOwn = {}.hasOwnProperty; "undefined" != typeof module && module.exports ? module.exports = classNames : (__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), !(void 0 !== __WEBPACK_AMD_DEFINE_RESULT__ && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))); }(); }, /* 173 */ /***/ function(module, exports) { "use strict"; function createCallbackMemoizer() { var requireAllKeys = arguments.length <= 0 || void 0 === arguments[0] ? !0 : arguments[0], cachedIndices = {}; return function(_ref) { var callback = _ref.callback, indices = _ref.indices, keys = Object.keys(indices), allInitialized = !requireAllKeys || keys.every(function(key) { var value = indices[key]; return Array.isArray(value) ? value.length > 0 : value >= 0; }), indexChanged = keys.length !== Object.keys(cachedIndices).length || keys.some(function(key) { var cachedValue = cachedIndices[key], value = indices[key]; return Array.isArray(value) ? cachedValue.join(",") !== value.join(",") : cachedValue !== value; }); cachedIndices = indices, allInitialized && indexChanged && callback(indices); }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = createCallbackMemoizer; }, /* 174 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var size, canUseDOM = __webpack_require__(175); module.exports = function(recalc) { if ((!size || recalc) && canUseDOM) { var scrollDiv = document.createElement("div"); scrollDiv.style.position = "absolute", scrollDiv.style.top = "-9999px", scrollDiv.style.width = "50px", scrollDiv.style.height = "50px", scrollDiv.style.overflow = "scroll", document.body.appendChild(scrollDiv), size = scrollDiv.offsetWidth - scrollDiv.clientWidth, document.body.removeChild(scrollDiv); } return size; }; }, /* 175 */ /***/ function(module, exports) { "use strict"; module.exports = !("undefined" == typeof window || !window.document || !window.document.createElement); }, /* 176 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(global) { for (var now = __webpack_require__(177), root = "undefined" == typeof window ? global : window, vendors = [ "moz", "webkit" ], suffix = "AnimationFrame", raf = root["request" + suffix], caf = root["cancel" + suffix] || root["cancelRequest" + suffix], i = 0; !raf && i < vendors.length; i++) raf = root[vendors[i] + "Request" + suffix], caf = root[vendors[i] + "Cancel" + suffix] || root[vendors[i] + "CancelRequest" + suffix]; // Some versions of FF have rAF but not cAF if (!raf || !caf) { var last = 0, id = 0, queue = [], frameDuration = 1e3 / 60; raf = function(callback) { if (0 === queue.length) { var _now = now(), next = Math.max(0, frameDuration - (_now - last)); last = next + _now, setTimeout(function() { var cp = queue.slice(0); // Clear queue here to prevent // callbacks from appending listeners // to the current frame's queue queue.length = 0; for (var i = 0; i < cp.length; i++) if (!cp[i].cancelled) try { cp[i].callback(last); } catch (e) { setTimeout(function() { throw e; }, 0); } }, Math.round(next)); } return queue.push({ handle: ++id, callback: callback, cancelled: !1 }), id; }, caf = function(handle) { for (var i = 0; i < queue.length; i++) queue[i].handle === handle && (queue[i].cancelled = !0); }; } module.exports = function(fn) { // Wrap in a new function to prevent // `cancel` potentially being assigned // to the native rAF function return raf.call(root, fn); }, module.exports.cancel = function() { caf.apply(root, arguments); }, module.exports.polyfill = function() { root.requestAnimationFrame = raf, root.cancelAnimationFrame = caf; }; }).call(exports, function() { return this; }()); }, /* 177 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { // Generated by CoffeeScript 1.7.1 (function() { var getNanoSeconds, hrtime, loadTime; "undefined" != typeof performance && null !== performance && performance.now ? module.exports = function() { return performance.now(); } : "undefined" != typeof process && null !== process && process.hrtime ? (module.exports = function() { return (getNanoSeconds() - loadTime) / 1e6; }, hrtime = process.hrtime, getNanoSeconds = function() { var hr; return hr = hrtime(), 1e9 * hr[0] + hr[1]; }, loadTime = getNanoSeconds()) : Date.now ? (module.exports = function() { return Date.now() - loadTime; }, loadTime = Date.now()) : (module.exports = function() { return new Date().getTime() - loadTime; }, loadTime = new Date().getTime()); }).call(this); }).call(exports, __webpack_require__(17)); }, /* 178 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function calculateSizeAndPositionData(_ref) { for (var cellCount = _ref.cellCount, cellSizeAndPositionGetter = _ref.cellSizeAndPositionGetter, sectionSize = _ref.sectionSize, cellMetadata = [], sectionManager = new _SectionManager2["default"](sectionSize), height = 0, width = 0, index = 0; cellCount > index; index++) { var cellMetadatum = cellSizeAndPositionGetter({ index: index }); if (null == cellMetadatum.height || isNaN(cellMetadatum.height) || null == cellMetadatum.width || isNaN(cellMetadatum.width) || null == cellMetadatum.x || isNaN(cellMetadatum.x) || null == cellMetadatum.y || isNaN(cellMetadatum.y)) throw Error("Invalid metadata returned for cell " + index + ":\n x:" + cellMetadatum.x + ", y:" + cellMetadatum.y + ", width:" + cellMetadatum.width + ", height:" + cellMetadatum.height); height = Math.max(height, cellMetadatum.y + cellMetadatum.height), width = Math.max(width, cellMetadatum.x + cellMetadatum.width), cellMetadata[index] = cellMetadatum, sectionManager.registerCell({ cellMetadatum: cellMetadatum, index: index }); } return { cellMetadata: cellMetadata, height: height, sectionManager: sectionManager, width: width }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = calculateSizeAndPositionData; var _SectionManager = __webpack_require__(179), _SectionManager2 = _interopRequireDefault(_SectionManager); }, /* 179 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _Section = __webpack_require__(180), _Section2 = _interopRequireDefault(_Section), SECTION_SIZE = 100, SectionManager = function() { function SectionManager() { var sectionSize = arguments.length <= 0 || void 0 === arguments[0] ? SECTION_SIZE : arguments[0]; _classCallCheck(this, SectionManager), this._sectionSize = sectionSize, this._cellMetadata = [], this._sections = {}; } return _createClass(SectionManager, [ { key: "getCellIndices", value: function(_ref) { var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y, indices = {}; return this.getSections({ height: height, width: width, x: x, y: y }).forEach(function(section) { return section.getCellIndices().forEach(function(index) { indices[index] = index; }); }), Object.keys(indices).map(function(index) { return indices[index]; }); } }, { key: "getCellMetadata", value: function(_ref2) { var index = _ref2.index; return this._cellMetadata[index]; } }, { key: "getSections", value: function(_ref3) { for (var height = _ref3.height, width = _ref3.width, x = _ref3.x, y = _ref3.y, sectionXStart = Math.floor(x / this._sectionSize), sectionXStop = Math.floor((x + width - 1) / this._sectionSize), sectionYStart = Math.floor(y / this._sectionSize), sectionYStop = Math.floor((y + height - 1) / this._sectionSize), sections = [], sectionX = sectionXStart; sectionXStop >= sectionX; sectionX++) for (var sectionY = sectionYStart; sectionYStop >= sectionY; sectionY++) { var key = sectionX + "." + sectionY; this._sections[key] || (this._sections[key] = new _Section2["default"]({ height: this._sectionSize, width: this._sectionSize, x: sectionX * this._sectionSize, y: sectionY * this._sectionSize })), sections.push(this._sections[key]); } return sections; } }, { key: "getTotalSectionCount", value: function() { return Object.keys(this._sections).length; } }, { key: "toString", value: function() { var _this = this; return Object.keys(this._sections).map(function(index) { return _this._sections[index].toString(); }); } }, { key: "registerCell", value: function(_ref4) { var cellMetadatum = _ref4.cellMetadatum, index = _ref4.index; this._cellMetadata[index] = cellMetadatum, this.getSections(cellMetadatum).forEach(function(section) { return section.addCellIndex({ index: index }); }); } } ]), SectionManager; }(); exports["default"] = SectionManager; }, /* 180 */ /***/ function(module, exports) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), Section = function() { function Section(_ref) { var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y; _classCallCheck(this, Section), this.height = height, this.width = width, this.x = x, this.y = y, this._indexMap = {}, this._indices = []; } return _createClass(Section, [ { key: "addCellIndex", value: function(_ref2) { var index = _ref2.index; this._indexMap[index] || (this._indexMap[index] = !0, this._indices.push(index)); } }, { key: "getCellIndices", value: function() { return this._indices; } }, { key: "toString", value: function() { return this.x + "," + this.y + " " + this.width + "x" + this.height; } } ]), Section; }(); exports["default"] = Section; }, /* 181 */ /***/ function(module, exports) { "use strict"; function getUpdatedOffsetForIndex(_ref) { var _ref$align = _ref.align, align = void 0 === _ref$align ? "auto" : _ref$align, cellOffset = _ref.cellOffset, cellSize = _ref.cellSize, containerSize = _ref.containerSize, currentOffset = _ref.currentOffset, maxOffset = cellOffset, minOffset = maxOffset - containerSize + cellSize; switch (align) { case "start": return maxOffset; case "end": return minOffset; case "center": return maxOffset - (containerSize + cellSize) / 2; default: return Math.max(minOffset, Math.min(maxOffset, currentOffset)); } } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = getUpdatedOffsetForIndex; }, /* 182 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ColumnSizer = exports["default"] = void 0; var _ColumnSizer2 = __webpack_require__(183), _ColumnSizer3 = _interopRequireDefault(_ColumnSizer2); exports["default"] = _ColumnSizer3["default"], exports.ColumnSizer = _ColumnSizer3["default"]; }, /* 183 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(184), _Grid2 = _interopRequireDefault(_Grid), ColumnSizer = function(_Component) { function ColumnSizer(props, context) { _classCallCheck(this, ColumnSizer); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ColumnSizer).call(this, props, context)); return _this._registerChild = _this._registerChild.bind(_this), _this; } return _inherits(ColumnSizer, _Component), _createClass(ColumnSizer, [ { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props = this.props, columnMaxWidth = _props.columnMaxWidth, columnMinWidth = _props.columnMinWidth, columnCount = _props.columnCount, width = _props.width; columnMaxWidth === prevProps.columnMaxWidth && columnMinWidth === prevProps.columnMinWidth && columnCount === prevProps.columnCount && width === prevProps.width || this._registeredChild && this._registeredChild.recomputeGridSize(); } }, { key: "render", value: function() { var _props2 = this.props, children = _props2.children, columnMaxWidth = _props2.columnMaxWidth, columnMinWidth = _props2.columnMinWidth, columnCount = _props2.columnCount, width = _props2.width, safeColumnMinWidth = columnMinWidth || 1, safeColumnMaxWidth = columnMaxWidth ? Math.min(columnMaxWidth, width) : width, columnWidth = width / columnCount; columnWidth = Math.max(safeColumnMinWidth, columnWidth), columnWidth = Math.min(safeColumnMaxWidth, columnWidth), columnWidth = Math.floor(columnWidth); var adjustedWidth = Math.min(width, columnWidth * columnCount); return children({ adjustedWidth: adjustedWidth, getColumnWidth: function() { return columnWidth; }, registerChild: this._registerChild }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_registerChild", value: function(child) { if (null !== child && !(child instanceof _Grid2["default"])) throw Error("Unexpected child type registered; only Grid children are supported."); this._registeredChild = child, this._registeredChild && this._registeredChild.recomputeGridSize(); } } ]), ColumnSizer; }(_react.Component); ColumnSizer.propTypes = { children: _react.PropTypes.func.isRequired, columnMaxWidth: _react.PropTypes.number, columnMinWidth: _react.PropTypes.number, columnCount: _react.PropTypes.number.isRequired, width: _react.PropTypes.number.isRequired }, exports["default"] = ColumnSizer; }, /* 184 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.defaultCellRangeRenderer = exports.Grid = exports["default"] = void 0; var _Grid2 = __webpack_require__(185), _Grid3 = _interopRequireDefault(_Grid2), _defaultCellRangeRenderer2 = __webpack_require__(191), _defaultCellRangeRenderer3 = _interopRequireDefault(_defaultCellRangeRenderer2); exports["default"] = _Grid3["default"], exports.Grid = _Grid3["default"], exports.defaultCellRangeRenderer = _defaultCellRangeRenderer3["default"]; }, /* 185 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _calculateSizeAndPositionDataAndUpdateScrollOffset = __webpack_require__(186), _calculateSizeAndPositionDataAndUpdateScrollOffset2 = _interopRequireDefault(_calculateSizeAndPositionDataAndUpdateScrollOffset), _ScalingCellSizeAndPositionManager = __webpack_require__(187), _ScalingCellSizeAndPositionManager2 = _interopRequireDefault(_ScalingCellSizeAndPositionManager), _createCallbackMemoizer = __webpack_require__(173), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _getOverscanIndices = __webpack_require__(189), _getOverscanIndices2 = _interopRequireDefault(_getOverscanIndices), _scrollbarSize = __webpack_require__(174), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _raf = __webpack_require__(176), _raf2 = _interopRequireDefault(_raf), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _updateScrollIndexHelper = __webpack_require__(190), _updateScrollIndexHelper2 = _interopRequireDefault(_updateScrollIndexHelper), _defaultCellRangeRenderer = __webpack_require__(191), _defaultCellRangeRenderer2 = _interopRequireDefault(_defaultCellRangeRenderer), IS_SCROLLING_TIMEOUT = 150, SCROLL_POSITION_CHANGE_REASONS = { OBSERVED: "observed", REQUESTED: "requested" }, Grid = function(_Component) { function Grid(props, context) { _classCallCheck(this, Grid); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Grid).call(this, props, context)); return _this.state = { isScrolling: !1, scrollLeft: 0, scrollTop: 0 }, _this._onGridRenderedMemoizer = (0, _createCallbackMemoizer2["default"])(), _this._onScrollMemoizer = (0, _createCallbackMemoizer2["default"])(!1), _this._enablePointerEventsAfterDelayCallback = _this._enablePointerEventsAfterDelayCallback.bind(_this), _this._invokeOnGridRenderedHelper = _this._invokeOnGridRenderedHelper.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._setNextStateCallback = _this._setNextStateCallback.bind(_this), _this._updateScrollLeftForScrollToColumn = _this._updateScrollLeftForScrollToColumn.bind(_this), _this._updateScrollTopForScrollToRow = _this._updateScrollTopForScrollToRow.bind(_this), _this._columnWidthGetter = _this._wrapSizeGetter(props.columnWidth), _this._rowHeightGetter = _this._wrapSizeGetter(props.rowHeight), _this._columnSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2["default"]({ cellCount: props.columnCount, cellSizeGetter: function(index) { return _this._columnWidthGetter(index); }, estimatedCellSize: _this._getEstimatedColumnSize(props) }), _this._rowSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2["default"]({ cellCount: props.rowCount, cellSizeGetter: function(index) { return _this._rowHeightGetter(index); }, estimatedCellSize: _this._getEstimatedRowSize(props) }), _this._cellCache = {}, _this; } return _inherits(Grid, _Component), _createClass(Grid, [ { key: "measureAllCells", value: function() { var _props = this.props, columnCount = _props.columnCount, rowCount = _props.rowCount; this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnCount - 1), this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowCount - 1); } }, { key: "recomputeGridSize", value: function() { var _ref = arguments.length <= 0 || void 0 === arguments[0] ? {} : arguments[0], _ref$columnIndex = _ref.columnIndex, columnIndex = void 0 === _ref$columnIndex ? 0 : _ref$columnIndex, _ref$rowIndex = _ref.rowIndex, rowIndex = void 0 === _ref$rowIndex ? 0 : _ref$rowIndex; this._columnSizeAndPositionManager.resetCell(columnIndex), this._rowSizeAndPositionManager.resetCell(rowIndex), this.forceUpdate(); } }, { key: "componentDidMount", value: function() { var _props2 = this.props, scrollLeft = _props2.scrollLeft, scrollToColumn = _props2.scrollToColumn, scrollTop = _props2.scrollTop, scrollToRow = _props2.scrollToRow; this._scrollbarSizeMeasured || (this._scrollbarSize = (0, _scrollbarSize2["default"])(), this._scrollbarSizeMeasured = !0, this.setState({})), (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({ scrollLeft: scrollLeft, scrollTop: scrollTop }), (scrollToColumn >= 0 || scrollToRow >= 0) && (this._updateScrollLeftForScrollToColumn(), this._updateScrollTopForScrollToRow()), this._invokeOnGridRenderedHelper(), this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft || 0, scrollTop: scrollTop || 0, totalColumnsWidth: this._columnSizeAndPositionManager.getTotalSize(), totalRowsHeight: this._rowSizeAndPositionManager.getTotalSize() }); } }, { key: "componentDidUpdate", value: function(prevProps, prevState) { var _this2 = this, _props3 = this.props, autoHeight = _props3.autoHeight, height = _props3.height, scrollToAlignment = _props3.scrollToAlignment, scrollToColumn = _props3.scrollToColumn, scrollToRow = _props3.scrollToRow, width = _props3.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollTop = _state.scrollTop; scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this.refs.scrollingContainer.scrollLeft && (this.refs.scrollingContainer.scrollLeft = scrollLeft), !autoHeight && scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this.refs.scrollingContainer.scrollTop && (this.refs.scrollingContainer.scrollTop = scrollTop)), (0, _updateScrollIndexHelper2["default"])({ cellSizeAndPositionManager: this._columnSizeAndPositionManager, previousCellsCount: prevProps.columnCount, previousCellSize: prevProps.columnWidth, previousScrollToAlignment: prevProps.scrollToAlignment, previousScrollToIndex: prevProps.scrollToColumn, previousSize: prevProps.width, scrollOffset: scrollLeft, scrollToAlignment: scrollToAlignment, scrollToIndex: scrollToColumn, size: width, updateScrollIndexCallback: function(scrollToColumn) { return _this2._updateScrollLeftForScrollToColumn(_extends({}, _this2.props, { scrollToColumn: scrollToColumn })); } }), (0, _updateScrollIndexHelper2["default"])({ cellSizeAndPositionManager: this._rowSizeAndPositionManager, previousCellsCount: prevProps.rowCount, previousCellSize: prevProps.rowHeight, previousScrollToAlignment: prevProps.scrollToAlignment, previousScrollToIndex: prevProps.scrollToRow, previousSize: prevProps.height, scrollOffset: scrollTop, scrollToAlignment: scrollToAlignment, scrollToIndex: scrollToRow, size: height, updateScrollIndexCallback: function(scrollToRow) { return _this2._updateScrollTopForScrollToRow(_extends({}, _this2.props, { scrollToRow: scrollToRow })); } }), this._invokeOnGridRenderedHelper(); } }, { key: "componentWillMount", value: function() { this._scrollbarSize = (0, _scrollbarSize2["default"])(), void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1, this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0; } }, { key: "componentWillUnmount", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { var _this3 = this; 0 === nextProps.columnCount && 0 !== nextState.scrollLeft || 0 === nextProps.rowCount && 0 !== nextState.scrollTop ? this._setScrollPosition({ scrollLeft: 0, scrollTop: 0 }) : nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({ scrollLeft: nextProps.scrollLeft, scrollTop: nextProps.scrollTop }), this._columnWidthGetter = this._wrapSizeGetter(nextProps.columnWidth), this._rowHeightGetter = this._wrapSizeGetter(nextProps.rowHeight), this._columnSizeAndPositionManager.configure({ cellCount: nextProps.columnCount, estimatedCellSize: this._getEstimatedColumnSize(nextProps) }), this._rowSizeAndPositionManager.configure({ cellCount: nextProps.rowCount, estimatedCellSize: this._getEstimatedRowSize(nextProps) }), (0, _calculateSizeAndPositionDataAndUpdateScrollOffset2["default"])({ cellCount: this.props.columnCount, cellSize: this.props.columnWidth, computeMetadataCallback: function() { return _this3._columnSizeAndPositionManager.resetCell(0); }, computeMetadataCallbackProps: nextProps, nextCellsCount: nextProps.columnCount, nextCellSize: nextProps.columnWidth, nextScrollToIndex: nextProps.scrollToColumn, scrollToIndex: this.props.scrollToColumn, updateScrollOffsetForScrollToIndex: function() { return _this3._updateScrollLeftForScrollToColumn(nextProps, nextState); } }), (0, _calculateSizeAndPositionDataAndUpdateScrollOffset2["default"])({ cellCount: this.props.rowCount, cellSize: this.props.rowHeight, computeMetadataCallback: function() { return _this3._rowSizeAndPositionManager.resetCell(0); }, computeMetadataCallbackProps: nextProps, nextCellsCount: nextProps.rowCount, nextCellSize: nextProps.rowHeight, nextScrollToIndex: nextProps.scrollToRow, scrollToIndex: this.props.scrollToRow, updateScrollOffsetForScrollToIndex: function() { return _this3._updateScrollTopForScrollToRow(nextProps, nextState); } }); } }, { key: "render", value: function() { var _props4 = this.props, autoHeight = _props4.autoHeight, cellClassName = _props4.cellClassName, cellRenderer = _props4.cellRenderer, cellRangeRenderer = _props4.cellRangeRenderer, cellStyle = _props4.cellStyle, className = _props4.className, columnCount = _props4.columnCount, height = _props4.height, noContentRenderer = _props4.noContentRenderer, overscanColumnCount = _props4.overscanColumnCount, overscanRowCount = _props4.overscanRowCount, rowCount = _props4.rowCount, style = _props4.style, tabIndex = _props4.tabIndex, width = _props4.width, _state2 = this.state, isScrolling = _state2.isScrolling, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop, childrenToDisplay = []; if (height > 0 && width > 0) { var visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange({ containerSize: width, offset: scrollLeft }), visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange({ containerSize: height, offset: scrollTop }), horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment({ containerSize: width, offset: scrollLeft }), verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment({ containerSize: height, offset: scrollTop }); this._renderedColumnStartIndex = visibleColumnIndices.start, this._renderedColumnStopIndex = visibleColumnIndices.stop, this._renderedRowStartIndex = visibleRowIndices.start, this._renderedRowStopIndex = visibleRowIndices.stop; var overscanColumnIndices = (0, _getOverscanIndices2["default"])({ cellCount: columnCount, overscanCellsCount: overscanColumnCount, startIndex: this._renderedColumnStartIndex, stopIndex: this._renderedColumnStopIndex }), overscanRowIndices = (0, _getOverscanIndices2["default"])({ cellCount: rowCount, overscanCellsCount: overscanRowCount, startIndex: this._renderedRowStartIndex, stopIndex: this._renderedRowStopIndex }); this._columnStartIndex = overscanColumnIndices.overscanStartIndex, this._columnStopIndex = overscanColumnIndices.overscanStopIndex, this._rowStartIndex = overscanRowIndices.overscanStartIndex, this._rowStopIndex = overscanRowIndices.overscanStopIndex, childrenToDisplay = cellRangeRenderer({ cellCache: this._cellCache, cellClassName: this._wrapCellClassNameGetter(cellClassName), cellRenderer: cellRenderer, cellStyle: this._wrapCellStyleGetter(cellStyle), columnSizeAndPositionManager: this._columnSizeAndPositionManager, columnStartIndex: this._columnStartIndex, columnStopIndex: this._columnStopIndex, horizontalOffsetAdjustment: horizontalOffsetAdjustment, isScrolling: isScrolling, rowSizeAndPositionManager: this._rowSizeAndPositionManager, rowStartIndex: this._rowStartIndex, rowStopIndex: this._rowStopIndex, scrollLeft: scrollLeft, scrollTop: scrollTop, verticalOffsetAdjustment: verticalOffsetAdjustment }); } var gridStyle = _extends({}, style, { height: autoHeight ? "auto" : height, width: width }), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), verticalScrollBarSize = totalRowsHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalColumnsWidth > width ? this._scrollbarSize : 0; width >= totalColumnsWidth + verticalScrollBarSize && (gridStyle.overflowX = "hidden"), height >= totalRowsHeight + horizontalScrollBarSize && (gridStyle.overflowY = "hidden"); var showNoContentRenderer = 0 === childrenToDisplay.length && height > 0 && width > 0; return _react2["default"].createElement("div", { ref: "scrollingContainer", "aria-label": this.props["aria-label"], className: (0, _classnames2["default"])("Grid", className), onScroll: this._onScroll, role: "grid", style: gridStyle, tabIndex: tabIndex }, childrenToDisplay.length > 0 && _react2["default"].createElement("div", { className: "Grid__innerScrollContainer", style: { width: 1 === columnCount ? "auto" : totalColumnsWidth, height: totalRowsHeight, maxWidth: totalColumnsWidth, maxHeight: totalRowsHeight, pointerEvents: isScrolling ? "none" : "auto" } }, childrenToDisplay), showNoContentRenderer && noContentRenderer()); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_enablePointerEventsAfterDelay", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._disablePointerEventsTimeoutId = setTimeout(this._enablePointerEventsAfterDelayCallback, IS_SCROLLING_TIMEOUT); } }, { key: "_enablePointerEventsAfterDelayCallback", value: function() { this._disablePointerEventsTimeoutId = null, this._cellCache = {}, this.setState({ isScrolling: !1 }); } }, { key: "_getEstimatedColumnSize", value: function(props) { return "number" == typeof props.columnWidth ? props.columnWidth : props.estimatedColumnSize; } }, { key: "_getEstimatedRowSize", value: function(props) { return "number" == typeof props.rowHeight ? props.rowHeight : props.estimatedRowSize; } }, { key: "_invokeOnGridRenderedHelper", value: function() { var onSectionRendered = this.props.onSectionRendered; this._onGridRenderedMemoizer({ callback: onSectionRendered, indices: { columnOverscanStartIndex: this._columnStartIndex, columnOverscanStopIndex: this._columnStopIndex, columnStartIndex: this._renderedColumnStartIndex, columnStopIndex: this._renderedColumnStopIndex, rowOverscanStartIndex: this._rowStartIndex, rowOverscanStopIndex: this._rowStopIndex, rowStartIndex: this._renderedRowStartIndex, rowStopIndex: this._renderedRowStopIndex } }); } }, { key: "_invokeOnScrollMemoizer", value: function(_ref2) { var _this4 = this, scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, totalColumnsWidth = _ref2.totalColumnsWidth, totalRowsHeight = _ref2.totalRowsHeight; this._onScrollMemoizer({ callback: function(_ref3) { var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, _props5 = _this4.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width; onScroll({ clientHeight: height, clientWidth: width, scrollHeight: totalRowsHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: totalColumnsWidth }); }, indices: { scrollLeft: scrollLeft, scrollTop: scrollTop } }); } }, { key: "_setNextState", value: function(state) { this._nextState = state, this._setNextStateAnimationFrameId || (this._setNextStateAnimationFrameId = (0, _raf2["default"])(this._setNextStateCallback)); } }, { key: "_setNextStateCallback", value: function() { var state = this._nextState; this._setNextStateAnimationFrameId = null, this._nextState = null, this.setState(state); } }, { key: "_setScrollPosition", value: function(_ref4) { var scrollLeft = _ref4.scrollLeft, scrollTop = _ref4.scrollTop, newState = { scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED }; scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop), (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState); } }, { key: "_wrapCellClassNameGetter", value: function(className) { return this._wrapPropertyGetter(className); } }, { key: "_wrapCellStyleGetter", value: function(style) { return this._wrapPropertyGetter(style); } }, { key: "_wrapPropertyGetter", value: function(value) { return value instanceof Function ? value : function() { return value; }; } }, { key: "_wrapSizeGetter", value: function(size) { return this._wrapPropertyGetter(size); } }, { key: "_updateScrollLeftForScrollToColumn", value: function() { var props = arguments.length <= 0 || void 0 === arguments[0] ? this.props : arguments[0], state = arguments.length <= 1 || void 0 === arguments[1] ? this.state : arguments[1], columnCount = props.columnCount, scrollToAlignment = props.scrollToAlignment, scrollToColumn = props.scrollToColumn, width = props.width, scrollLeft = state.scrollLeft; if (scrollToColumn >= 0 && columnCount > 0) { var targetIndex = Math.max(0, Math.min(columnCount - 1, scrollToColumn)), calculatedScrollLeft = this._columnSizeAndPositionManager.getUpdatedOffsetForIndex({ align: scrollToAlignment, containerSize: width, currentOffset: scrollLeft, targetIndex: targetIndex }); scrollLeft !== calculatedScrollLeft && this._setScrollPosition({ scrollLeft: calculatedScrollLeft }); } } }, { key: "_updateScrollTopForScrollToRow", value: function() { var props = arguments.length <= 0 || void 0 === arguments[0] ? this.props : arguments[0], state = arguments.length <= 1 || void 0 === arguments[1] ? this.state : arguments[1], height = props.height, rowCount = props.rowCount, scrollToAlignment = props.scrollToAlignment, scrollToRow = props.scrollToRow, scrollTop = state.scrollTop; if (scrollToRow >= 0 && rowCount > 0) { var targetIndex = Math.max(0, Math.min(rowCount - 1, scrollToRow)), calculatedScrollTop = this._rowSizeAndPositionManager.getUpdatedOffsetForIndex({ align: scrollToAlignment, containerSize: height, currentOffset: scrollTop, targetIndex: targetIndex }); scrollTop !== calculatedScrollTop && this._setScrollPosition({ scrollTop: calculatedScrollTop }); } } }, { key: "_onScroll", value: function(event) { if (event.target === this.refs.scrollingContainer) { this._enablePointerEventsAfterDelay(); var _props6 = this.props, height = _props6.height, width = _props6.width, scrollbarSize = this._scrollbarSize, totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), scrollLeft = Math.min(Math.max(0, totalColumnsWidth - width + scrollbarSize), event.target.scrollLeft), scrollTop = Math.min(Math.max(0, totalRowsHeight - height + scrollbarSize), event.target.scrollTop); if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED; this.state.isScrolling || this.setState({ isScrolling: !0 }), this._setNextState({ isScrolling: !0, scrollLeft: scrollLeft, scrollPositionChangeReason: scrollPositionChangeReason, scrollTop: scrollTop }); } this._invokeOnScrollMemoizer({ scrollLeft: scrollLeft, scrollTop: scrollTop, totalColumnsWidth: totalColumnsWidth, totalRowsHeight: totalRowsHeight }); } } } ]), Grid; }(_react.Component); Grid.propTypes = { "aria-label": _react.PropTypes.string, autoHeight: _react.PropTypes.bool, cellClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), cellStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]), cellRenderer: _react.PropTypes.func.isRequired, cellRangeRenderer: _react.PropTypes.func.isRequired, className: _react.PropTypes.string, columnCount: _react.PropTypes.number.isRequired, columnWidth: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, estimatedColumnSize: _react.PropTypes.number.isRequired, estimatedRowSize: _react.PropTypes.number.isRequired, height: _react.PropTypes.number.isRequired, noContentRenderer: _react.PropTypes.func.isRequired, onScroll: _react.PropTypes.func.isRequired, onSectionRendered: _react.PropTypes.func.isRequired, overscanColumnCount: _react.PropTypes.number.isRequired, overscanRowCount: _react.PropTypes.number.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowCount: _react.PropTypes.number.isRequired, scrollLeft: _react.PropTypes.number, scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired, scrollToColumn: _react.PropTypes.number, scrollTop: _react.PropTypes.number, scrollToRow: _react.PropTypes.number, style: _react.PropTypes.object, tabIndex: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, Grid.defaultProps = { "aria-label": "grid", cellStyle: {}, cellRangeRenderer: _defaultCellRangeRenderer2["default"], estimatedColumnSize: 100, estimatedRowSize: 30, noContentRenderer: function() { return null; }, onScroll: function() { return null; }, onSectionRendered: function() { return null; }, overscanColumnCount: 0, overscanRowCount: 10, scrollToAlignment: "auto", style: {}, tabIndex: 0 }, exports["default"] = Grid; }, /* 186 */ /***/ function(module, exports) { "use strict"; function calculateSizeAndPositionDataAndUpdateScrollOffset(_ref) { var cellCount = _ref.cellCount, cellSize = _ref.cellSize, computeMetadataCallback = _ref.computeMetadataCallback, computeMetadataCallbackProps = _ref.computeMetadataCallbackProps, nextCellsCount = _ref.nextCellsCount, nextCellSize = _ref.nextCellSize, nextScrollToIndex = _ref.nextScrollToIndex, scrollToIndex = _ref.scrollToIndex, updateScrollOffsetForScrollToIndex = _ref.updateScrollOffsetForScrollToIndex; cellCount === nextCellsCount && ("number" != typeof cellSize && "number" != typeof nextCellSize || cellSize === nextCellSize) || (computeMetadataCallback(computeMetadataCallbackProps), scrollToIndex >= 0 && scrollToIndex === nextScrollToIndex && updateScrollOffsetForScrollToIndex()); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = calculateSizeAndPositionDataAndUpdateScrollOffset; }, /* 187 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (target[i] = obj[i]); return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.DEFAULT_MAX_SCROLL_SIZE = void 0; var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _CellSizeAndPositionManager = __webpack_require__(188), _CellSizeAndPositionManager2 = _interopRequireDefault(_CellSizeAndPositionManager), DEFAULT_MAX_SCROLL_SIZE = exports.DEFAULT_MAX_SCROLL_SIZE = 1e7, ScalingCellSizeAndPositionManager = function() { function ScalingCellSizeAndPositionManager(_ref) { var _ref$maxScrollSize = _ref.maxScrollSize, maxScrollSize = void 0 === _ref$maxScrollSize ? DEFAULT_MAX_SCROLL_SIZE : _ref$maxScrollSize, params = _objectWithoutProperties(_ref, [ "maxScrollSize" ]); _classCallCheck(this, ScalingCellSizeAndPositionManager), this._cellSizeAndPositionManager = new _CellSizeAndPositionManager2["default"](params), this._maxScrollSize = maxScrollSize; } return _createClass(ScalingCellSizeAndPositionManager, [ { key: "configure", value: function(params) { this._cellSizeAndPositionManager.configure(params); } }, { key: "getCellCount", value: function() { return this._cellSizeAndPositionManager.getCellCount(); } }, { key: "getEstimatedCellSize", value: function() { return this._cellSizeAndPositionManager.getEstimatedCellSize(); } }, { key: "getLastMeasuredIndex", value: function() { return this._cellSizeAndPositionManager.getLastMeasuredIndex(); } }, { key: "getOffsetAdjustment", value: function(_ref2) { var containerSize = _ref2.containerSize, offset = _ref2.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(), offsetPercentage = this._getOffsetPercentage({ containerSize: containerSize, offset: offset, totalSize: safeTotalSize }); return Math.round(offsetPercentage * (safeTotalSize - totalSize)); } }, { key: "getSizeAndPositionOfCell", value: function(index) { return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(index); } }, { key: "getSizeAndPositionOfLastMeasuredCell", value: function() { return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell(); } }, { key: "getTotalSize", value: function() { return Math.min(this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize()); } }, { key: "getUpdatedOffsetForIndex", value: function(_ref3) { var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex; currentOffset = this._safeOffsetToOffset({ containerSize: containerSize, offset: currentOffset }); var offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({ align: align, containerSize: containerSize, currentOffset: currentOffset, targetIndex: targetIndex }); return this._offsetToSafeOffset({ containerSize: containerSize, offset: offset }); } }, { key: "getVisibleCellRange", value: function(_ref4) { var containerSize = _ref4.containerSize, offset = _ref4.offset; return offset = this._safeOffsetToOffset({ containerSize: containerSize, offset: offset }), this._cellSizeAndPositionManager.getVisibleCellRange({ containerSize: containerSize, offset: offset }); } }, { key: "resetCell", value: function(index) { this._cellSizeAndPositionManager.resetCell(index); } }, { key: "_getOffsetPercentage", value: function(_ref5) { var containerSize = _ref5.containerSize, offset = _ref5.offset, totalSize = _ref5.totalSize; return containerSize >= totalSize ? 0 : offset / (totalSize - containerSize); } }, { key: "_offsetToSafeOffset", value: function(_ref6) { var containerSize = _ref6.containerSize, offset = _ref6.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(); if (totalSize === safeTotalSize) return offset; var offsetPercentage = this._getOffsetPercentage({ containerSize: containerSize, offset: offset, totalSize: totalSize }); return Math.round(offsetPercentage * (safeTotalSize - containerSize)); } }, { key: "_safeOffsetToOffset", value: function(_ref7) { var containerSize = _ref7.containerSize, offset = _ref7.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(); if (totalSize === safeTotalSize) return offset; var offsetPercentage = this._getOffsetPercentage({ containerSize: containerSize, offset: offset, totalSize: safeTotalSize }); return Math.round(offsetPercentage * (totalSize - containerSize)); } } ]), ScalingCellSizeAndPositionManager; }(); exports["default"] = ScalingCellSizeAndPositionManager; }, /* 188 */ /***/ function(module, exports) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), CellSizeAndPositionManager = function() { function CellSizeAndPositionManager(_ref) { var cellCount = _ref.cellCount, cellSizeGetter = _ref.cellSizeGetter, estimatedCellSize = _ref.estimatedCellSize; _classCallCheck(this, CellSizeAndPositionManager), this._cellSizeGetter = cellSizeGetter, this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize, this._cellSizeAndPositionData = {}, this._lastMeasuredIndex = -1; } return _createClass(CellSizeAndPositionManager, [ { key: "configure", value: function(_ref2) { var cellCount = _ref2.cellCount, estimatedCellSize = _ref2.estimatedCellSize; this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize; } }, { key: "getCellCount", value: function() { return this._cellCount; } }, { key: "getEstimatedCellSize", value: function() { return this._estimatedCellSize; } }, { key: "getLastMeasuredIndex", value: function() { return this._lastMeasuredIndex; } }, { key: "getSizeAndPositionOfCell", value: function(index) { if (0 > index || index >= this._cellCount) throw Error("Requested index " + index + " is outside of range 0.." + this._cellCount); if (index > this._lastMeasuredIndex) { for (var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), _offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size, i = this._lastMeasuredIndex + 1; index >= i; i++) { var _size = this._cellSizeGetter({ index: i }); if (null == _size || isNaN(_size)) throw Error("Invalid size returned for cell " + i + " of value " + _size); this._cellSizeAndPositionData[i] = { offset: _offset, size: _size }, _offset += _size; } this._lastMeasuredIndex = index; } return this._cellSizeAndPositionData[index]; } }, { key: "getSizeAndPositionOfLastMeasuredCell", value: function() { return this._lastMeasuredIndex >= 0 ? this._cellSizeAndPositionData[this._lastMeasuredIndex] : { offset: 0, size: 0 }; } }, { key: "getTotalSize", value: function() { var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); return lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size + (this._cellCount - this._lastMeasuredIndex - 1) * this._estimatedCellSize; } }, { key: "getUpdatedOffsetForIndex", value: function(_ref3) { var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex, datum = this.getSizeAndPositionOfCell(targetIndex), maxOffset = datum.offset, minOffset = maxOffset - containerSize + datum.size; switch (align) { case "start": return maxOffset; case "end": return minOffset; case "center": return maxOffset - (containerSize + datum.size) / 2; default: return Math.max(minOffset, Math.min(maxOffset, currentOffset)); } } }, { key: "getVisibleCellRange", value: function(_ref4) { var containerSize = _ref4.containerSize, offset = _ref4.offset, totalSize = this.getTotalSize(); if (0 === totalSize) return {}; var maxOffset = offset + containerSize, start = this._findNearestCell(offset), datum = this.getSizeAndPositionOfCell(start); offset = datum.offset + datum.size; for (var stop = start; maxOffset > offset && stop < this._cellCount - 1; ) stop++, offset += this.getSizeAndPositionOfCell(stop).size; return { start: start, stop: stop }; } }, { key: "resetCell", value: function(index) { this._lastMeasuredIndex = index - 1; } }, { key: "_binarySearch", value: function(_ref5) { for (var high = _ref5.high, low = _ref5.low, offset = _ref5.offset, middle = void 0, currentOffset = void 0; high >= low; ) { if (middle = low + Math.floor((high - low) / 2), currentOffset = this.getSizeAndPositionOfCell(middle).offset, currentOffset === offset) return middle; offset > currentOffset ? low = middle + 1 : currentOffset > offset && (high = middle - 1); } return low > 0 ? low - 1 : void 0; } }, { key: "_exponentialSearch", value: function(_ref6) { for (var index = _ref6.index, offset = _ref6.offset, interval = 1; index < this._cellCount && this.getSizeAndPositionOfCell(index).offset < offset; ) index += interval, interval *= 2; return this._binarySearch({ high: Math.min(index, this._cellCount - 1), low: Math.floor(index / 2), offset: offset }); } }, { key: "_findNearestCell", value: function(offset) { if (isNaN(offset)) throw Error("Invalid offset " + offset + " specified"); offset = Math.max(0, offset); var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex); return lastMeasuredCellSizeAndPosition.offset >= offset ? this._binarySearch({ high: lastMeasuredIndex, low: 0, offset: offset }) : this._exponentialSearch({ index: lastMeasuredIndex, offset: offset }); } } ]), CellSizeAndPositionManager; }(); exports["default"] = CellSizeAndPositionManager; }, /* 189 */ /***/ function(module, exports) { "use strict"; function getOverscanIndices(_ref) { var cellCount = _ref.cellCount, overscanCellsCount = _ref.overscanCellsCount, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex; return { overscanStartIndex: Math.max(0, startIndex - overscanCellsCount), overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount) }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = getOverscanIndices; }, /* 190 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function updateScrollIndexHelper(_ref) { var cellSize = _ref.cellSize, cellSizeAndPositionManager = _ref.cellSizeAndPositionManager, previousCellsCount = _ref.previousCellsCount, previousCellSize = _ref.previousCellSize, previousScrollToAlignment = _ref.previousScrollToAlignment, previousScrollToIndex = _ref.previousScrollToIndex, previousSize = _ref.previousSize, scrollOffset = _ref.scrollOffset, scrollToAlignment = _ref.scrollToAlignment, scrollToIndex = _ref.scrollToIndex, size = _ref.size, updateScrollIndexCallback = _ref.updateScrollIndexCallback, cellCount = cellSizeAndPositionManager.getCellCount(), hasScrollToIndex = scrollToIndex >= 0 && cellCount > scrollToIndex, sizeHasChanged = size !== previousSize || !previousCellSize || "number" == typeof cellSize && cellSize !== previousCellSize; if (hasScrollToIndex && (sizeHasChanged || scrollToAlignment !== previousScrollToAlignment || scrollToIndex !== previousScrollToIndex)) updateScrollIndexCallback(scrollToIndex); else if (!hasScrollToIndex && cellCount > 0 && (previousSize > size || previousCellsCount > cellCount)) { scrollToIndex = cellCount - 1; var cellMetadatum = cellSizeAndPositionManager.getSizeAndPositionOfCell(scrollToIndex), calculatedScrollOffset = (0, _getUpdatedOffsetForIndex2["default"])({ cellOffset: cellMetadatum.offset, cellSize: cellMetadatum.size, containerSize: size, currentOffset: scrollOffset }); scrollOffset > calculatedScrollOffset && updateScrollIndexCallback(cellCount - 1); } } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = updateScrollIndexHelper; var _getUpdatedOffsetForIndex = __webpack_require__(181), _getUpdatedOffsetForIndex2 = _interopRequireDefault(_getUpdatedOffsetForIndex); }, /* 191 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function defaultCellRangeRenderer(_ref) { for (var cellCache = _ref.cellCache, cellClassName = _ref.cellClassName, cellRenderer = _ref.cellRenderer, cellStyle = _ref.cellStyle, columnSizeAndPositionManager = _ref.columnSizeAndPositionManager, columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, horizontalOffsetAdjustment = _ref.horizontalOffsetAdjustment, isScrolling = _ref.isScrolling, rowSizeAndPositionManager = _ref.rowSizeAndPositionManager, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex, verticalOffsetAdjustment = (_ref.scrollLeft, _ref.scrollTop, _ref.verticalOffsetAdjustment), renderedCells = [], rowIndex = rowStartIndex; rowStopIndex >= rowIndex; rowIndex++) for (var rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex), columnIndex = columnStartIndex; columnStopIndex >= columnIndex; columnIndex++) { var columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex), key = rowIndex + "-" + columnIndex, cellStyleObject = cellStyle({ rowIndex: rowIndex, columnIndex: columnIndex }), renderedCell = void 0; if (isScrolling ? (cellCache[key] || (cellCache[key] = cellRenderer({ columnIndex: columnIndex, isScrolling: isScrolling, rowIndex: rowIndex })), renderedCell = cellCache[key]) : renderedCell = cellRenderer({ columnIndex: columnIndex, isScrolling: isScrolling, rowIndex: rowIndex }), null != renderedCell && renderedCell !== !1) { var className = cellClassName({ columnIndex: columnIndex, rowIndex: rowIndex }), child = _react2["default"].createElement("div", { key: key, className: (0, _classnames2["default"])("Grid__cell", className), style: _extends({ height: rowDatum.size, left: columnDatum.offset + horizontalOffsetAdjustment, top: rowDatum.offset + verticalOffsetAdjustment, width: columnDatum.size }, cellStyleObject) }, renderedCell); renderedCells.push(child); } } return renderedCells; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }; exports["default"] = defaultCellRangeRenderer; var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames); }, /* 192 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.SortIndicator = exports.SortDirection = exports.FlexColumn = exports.FlexTable = exports["default"] = void 0; var _FlexTable2 = __webpack_require__(193), _FlexTable3 = _interopRequireDefault(_FlexTable2), _FlexColumn2 = __webpack_require__(194), _FlexColumn3 = _interopRequireDefault(_FlexColumn2), _SortDirection2 = __webpack_require__(197), _SortDirection3 = _interopRequireDefault(_SortDirection2), _SortIndicator2 = __webpack_require__(196), _SortIndicator3 = _interopRequireDefault(_SortIndicator2); exports["default"] = _FlexTable3["default"], exports.FlexTable = _FlexTable3["default"], exports.FlexColumn = _FlexColumn3["default"], exports.SortDirection = _SortDirection3["default"], exports.SortIndicator = _SortIndicator3["default"]; }, /* 193 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _FlexColumn = __webpack_require__(194), _FlexColumn2 = _interopRequireDefault(_FlexColumn), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(10), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(184), _Grid2 = _interopRequireDefault(_Grid), _SortDirection = __webpack_require__(197), _SortDirection2 = _interopRequireDefault(_SortDirection), FlexTable = function(_Component) { function FlexTable(props) { _classCallCheck(this, FlexTable); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(FlexTable).call(this, props)); return _this.state = { scrollbarWidth: 0 }, _this._cellClassName = _this._cellClassName.bind(_this), _this._cellStyle = _this._cellStyle.bind(_this), _this._createRow = _this._createRow.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this), _this; } return _inherits(FlexTable, _Component), _createClass(FlexTable, [ { key: "forceUpdateGrid", value: function() { this.refs.Grid.forceUpdate(); } }, { key: "measureAllRows", value: function() { this.refs.Grid.measureAllCells(); } }, { key: "recomputeRowHeights", value: function() { var index = arguments.length <= 0 || void 0 === arguments[0] ? 0 : arguments[0]; this.refs.Grid.recomputeGridSize({ rowIndex: index }), this.forceUpdateGrid(); } }, { key: "componentDidMount", value: function() { this._setScrollbarWidth(); } }, { key: "componentDidUpdate", value: function() { this._setScrollbarWidth(); } }, { key: "render", value: function() { var _this2 = this, _props = this.props, children = _props.children, className = _props.className, disableHeader = _props.disableHeader, gridClassName = _props.gridClassName, gridStyle = _props.gridStyle, headerHeight = _props.headerHeight, height = _props.height, noRowsRenderer = _props.noRowsRenderer, rowClassName = _props.rowClassName, rowStyle = _props.rowStyle, scrollToIndex = _props.scrollToIndex, style = _props.style, width = _props.width, scrollbarWidth = this.state.scrollbarWidth, availableRowsHeight = height - headerHeight, rowClass = rowClassName instanceof Function ? rowClassName({ index: -1 }) : rowClassName; return this._cachedColumnStyles = [], _react2["default"].Children.toArray(children).forEach(function(column, index) { _this2._cachedColumnStyles[index] = _this2._getFlexStyleForColumn(column, column.props.style); }), _react2["default"].createElement("div", { className: (0, _classnames2["default"])("FlexTable", className), style: style }, !disableHeader && _react2["default"].createElement("div", { className: (0, _classnames2["default"])("FlexTable__headerRow", rowClass), style: _extends({}, rowStyle, { height: headerHeight, paddingRight: scrollbarWidth, width: width }) }, this._getRenderedHeaderRow()), _react2["default"].createElement(_Grid2["default"], _extends({}, this.props, { className: (0, _classnames2["default"])("FlexTable__Grid", gridClassName), cellClassName: this._cellClassName, cellRenderer: this._createRow, cellStyle: this._cellStyle, columnWidth: width, columnCount: 1, height: availableRowsHeight, noContentRenderer: noRowsRenderer, onScroll: this._onScroll, onSectionRendered: this._onSectionRendered, ref: "Grid", scrollbarWidth: scrollbarWidth, scrollToRow: scrollToIndex, style: gridStyle }))); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_cellClassName", value: function(_ref) { var rowIndex = _ref.rowIndex, rowWrapperClassName = this.props.rowWrapperClassName; return rowWrapperClassName instanceof Function ? rowWrapperClassName({ index: rowIndex - 1 }) : rowWrapperClassName; } }, { key: "_cellStyle", value: function(_ref2) { var rowIndex = _ref2.rowIndex, rowWrapperStyle = this.props.rowWrapperStyle; return rowWrapperStyle instanceof Function ? rowWrapperStyle({ index: rowIndex - 1 }) : rowWrapperStyle; } }, { key: "_createColumn", value: function(_ref3) { var column = _ref3.column, columnIndex = _ref3.columnIndex, isScrolling = _ref3.isScrolling, rowData = _ref3.rowData, rowIndex = _ref3.rowIndex, _column$props = column.props, cellDataGetter = _column$props.cellDataGetter, cellRenderer = _column$props.cellRenderer, className = _column$props.className, columnData = _column$props.columnData, dataKey = _column$props.dataKey, cellData = cellDataGetter({ columnData: columnData, dataKey: dataKey, rowData: rowData }), renderedCell = cellRenderer({ cellData: cellData, columnData: columnData, dataKey: dataKey, isScrolling: isScrolling, rowData: rowData, rowIndex: rowIndex }), style = this._cachedColumnStyles[columnIndex], title = "string" == typeof renderedCell ? renderedCell : null; return _react2["default"].createElement("div", { key: "Row" + rowIndex + "-Col" + columnIndex, className: (0, _classnames2["default"])("FlexTable__rowColumn", className), style: style, title: title }, renderedCell); } }, { key: "_createHeader", value: function(column, columnIndex) { var _props2 = this.props, headerClassName = _props2.headerClassName, headerStyle = _props2.headerStyle, onHeaderClick = _props2.onHeaderClick, sort = _props2.sort, sortBy = _props2.sortBy, sortDirection = _props2.sortDirection, _column$props2 = column.props, dataKey = _column$props2.dataKey, disableSort = _column$props2.disableSort, headerRenderer = _column$props2.headerRenderer, label = _column$props2.label, columnData = _column$props2.columnData, sortEnabled = !disableSort && sort, classNames = (0, _classnames2["default"])("FlexTable__headerColumn", headerClassName, column.props.headerClassName, { FlexTable__sortableHeaderColumn: sortEnabled }), style = this._getFlexStyleForColumn(column, headerStyle), renderedHeader = headerRenderer({ columnData: columnData, dataKey: dataKey, disableSort: disableSort, label: label, sortBy: sortBy, sortDirection: sortDirection }), a11yProps = {}; return (sortEnabled || onHeaderClick) && !function() { var newSortDirection = sortBy !== dataKey || sortDirection === _SortDirection2["default"].DESC ? _SortDirection2["default"].ASC : _SortDirection2["default"].DESC, onClick = function() { sortEnabled && sort({ sortBy: dataKey, sortDirection: newSortDirection }), onHeaderClick && onHeaderClick({ columnData: columnData, dataKey: dataKey }); }, onKeyDown = function(event) { "Enter" !== event.key && " " !== event.key || onClick(); }; a11yProps["aria-label"] = column.props["aria-label"] || label || dataKey, a11yProps.role = "rowheader", a11yProps.tabIndex = 0, a11yProps.onClick = onClick, a11yProps.onKeyDown = onKeyDown; }(), _react2["default"].createElement("div", _extends({}, a11yProps, { key: "Header-Col" + columnIndex, className: classNames, style: style }), renderedHeader); } }, { key: "_createRow", value: function(_ref4) { var _this3 = this, index = _ref4.rowIndex, isScrolling = _ref4.isScrolling, _props3 = this.props, children = _props3.children, onRowClick = _props3.onRowClick, onRowMouseOver = _props3.onRowMouseOver, onRowMouseOut = _props3.onRowMouseOut, rowClassName = _props3.rowClassName, rowGetter = _props3.rowGetter, rowStyle = _props3.rowStyle, scrollbarWidth = this.state.scrollbarWidth, rowClass = rowClassName instanceof Function ? rowClassName({ index: index }) : rowClassName, rowData = rowGetter({ index: index }), renderedRow = _react2["default"].Children.toArray(children).map(function(column, columnIndex) { return _this3._createColumn({ column: column, columnIndex: columnIndex, isScrolling: isScrolling, rowData: rowData, rowIndex: index }); }), a11yProps = {}; return (onRowClick || onRowMouseOver || onRowMouseOut) && (a11yProps["aria-label"] = "row", a11yProps.role = "row", a11yProps.tabIndex = 0, onRowClick && (a11yProps.onClick = function() { return onRowClick({ index: index }); }), onRowMouseOut && (a11yProps.onMouseOut = function() { return onRowMouseOut({ index: index }); }), onRowMouseOver && (a11yProps.onMouseOver = function() { return onRowMouseOver({ index: index }); })), _react2["default"].createElement("div", _extends({}, a11yProps, { key: index, className: (0, _classnames2["default"])("FlexTable__row", rowClass), style: _extends({}, rowStyle, { height: this._getRowHeight(index), paddingRight: scrollbarWidth }) }), renderedRow); } }, { key: "_getFlexStyleForColumn", value: function(column) { var customStyle = arguments.length <= 1 || void 0 === arguments[1] ? {} : arguments[1], flexValue = column.props.flexGrow + " " + column.props.flexShrink + " " + column.props.width + "px", style = _extends({}, customStyle, { flex: flexValue, msFlex: flexValue, WebkitFlex: flexValue }); return column.props.maxWidth && (style.maxWidth = column.props.maxWidth), column.props.minWidth && (style.minWidth = column.props.minWidth), style; } }, { key: "_getRenderedHeaderRow", value: function() { var _this4 = this, _props4 = this.props, children = _props4.children, disableHeader = _props4.disableHeader, items = disableHeader ? [] : _react2["default"].Children.toArray(children); return items.map(function(column, index) { return _this4._createHeader(column, index); }); } }, { key: "_getRowHeight", value: function(rowIndex) { var rowHeight = this.props.rowHeight; return rowHeight instanceof Function ? rowHeight({ index: rowIndex }) : rowHeight; } }, { key: "_onScroll", value: function(_ref5) { var clientHeight = _ref5.clientHeight, scrollHeight = _ref5.scrollHeight, scrollTop = _ref5.scrollTop, onScroll = this.props.onScroll; onScroll({ clientHeight: clientHeight, scrollHeight: scrollHeight, scrollTop: scrollTop }); } }, { key: "_onSectionRendered", value: function(_ref6) { var rowOverscanStartIndex = _ref6.rowOverscanStartIndex, rowOverscanStopIndex = _ref6.rowOverscanStopIndex, rowStartIndex = _ref6.rowStartIndex, rowStopIndex = _ref6.rowStopIndex, onRowsRendered = this.props.onRowsRendered; onRowsRendered({ overscanStartIndex: rowOverscanStartIndex, overscanStopIndex: rowOverscanStopIndex, startIndex: rowStartIndex, stopIndex: rowStopIndex }); } }, { key: "_setScrollbarWidth", value: function() { var Grid = (0, _reactDom.findDOMNode)(this.refs.Grid), clientWidth = Grid.clientWidth || 0, offsetWidth = Grid.offsetWidth || 0, scrollbarWidth = offsetWidth - clientWidth; this.setState({ scrollbarWidth: scrollbarWidth }); } } ]), FlexTable; }(_react.Component); FlexTable.propTypes = { "aria-label": _react.PropTypes.string, autoHeight: _react.PropTypes.bool, children: function children(props, propName, componentName) { for (var children = _react2["default"].Children.toArray(props.children), i = 0; i < children.length; i++) if (children[i].type !== _FlexColumn2["default"]) return new Error("FlexTable only accepts children of type FlexColumn"); }, className: _react.PropTypes.string, disableHeader: _react.PropTypes.bool, estimatedRowSize: _react.PropTypes.number.isRequired, gridClassName: _react.PropTypes.string, gridStyle: _react.PropTypes.object, headerClassName: _react.PropTypes.string, headerHeight: _react.PropTypes.number.isRequired, height: _react.PropTypes.number.isRequired, noRowsRenderer: _react.PropTypes.func, onHeaderClick: _react.PropTypes.func, headerStyle: _react.PropTypes.object, onRowClick: _react.PropTypes.func, onRowMouseOut: _react.PropTypes.func, onRowMouseOver: _react.PropTypes.func, onRowsRendered: _react.PropTypes.func, onScroll: _react.PropTypes.func.isRequired, overscanRowCount: _react.PropTypes.number.isRequired, rowClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), rowGetter: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowCount: _react.PropTypes.number.isRequired, rowStyle: _react.PropTypes.object, rowWrapperClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), rowWrapperStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]), scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired, scrollToIndex: _react.PropTypes.number, scrollTop: _react.PropTypes.number, sort: _react.PropTypes.func, sortBy: _react.PropTypes.string, sortDirection: _react.PropTypes.oneOf([ _SortDirection2["default"].ASC, _SortDirection2["default"].DESC ]), style: _react.PropTypes.object, tabIndex: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, FlexTable.defaultProps = { disableHeader: !1, estimatedRowSize: 30, headerHeight: 0, headerStyle: {}, noRowsRenderer: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; }, overscanRowCount: 10, rowStyle: {}, scrollToAlignment: "auto", style: {} }, exports["default"] = FlexTable; }, /* 194 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _react = __webpack_require__(3), _defaultHeaderRenderer = __webpack_require__(195), _defaultHeaderRenderer2 = _interopRequireDefault(_defaultHeaderRenderer), _defaultCellRenderer = __webpack_require__(198), _defaultCellRenderer2 = _interopRequireDefault(_defaultCellRenderer), _defaultCellDataGetter = __webpack_require__(199), _defaultCellDataGetter2 = _interopRequireDefault(_defaultCellDataGetter), Column = function(_Component) { function Column() { return _classCallCheck(this, Column), _possibleConstructorReturn(this, Object.getPrototypeOf(Column).apply(this, arguments)); } return _inherits(Column, _Component), Column; }(_react.Component); Column.defaultProps = { cellDataGetter: _defaultCellDataGetter2["default"], cellRenderer: _defaultCellRenderer2["default"], cellStyle: {}, flexGrow: 0, flexShrink: 1, headerRenderer: _defaultHeaderRenderer2["default"] }, Column.propTypes = { "aria-label": _react.PropTypes.string, cellDataGetter: _react.PropTypes.func, cellRenderer: _react.PropTypes.func, className: _react.PropTypes.string, columnData: _react.PropTypes.object, dataKey: _react.PropTypes.any.isRequired, disableSort: _react.PropTypes.bool, flexGrow: _react.PropTypes.number, flexShrink: _react.PropTypes.number, headerClassName: _react.PropTypes.string, headerRenderer: _react.PropTypes.func.isRequired, label: _react.PropTypes.string, maxWidth: _react.PropTypes.number, minWidth: _react.PropTypes.number, style: _react.PropTypes.object, width: _react.PropTypes.number.isRequired }, exports["default"] = Column; }, /* 195 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function defaultHeaderRenderer(_ref) { var dataKey = (_ref.columnData, _ref.dataKey), label = (_ref.disableSort, _ref.label), sortBy = _ref.sortBy, sortDirection = _ref.sortDirection, showSortIndicator = sortBy === dataKey, children = [ _react2["default"].createElement("span", { className: "FlexTable__headerTruncatedText", key: "label", title: label }, label) ]; return showSortIndicator && children.push(_react2["default"].createElement(_SortIndicator2["default"], { key: "SortIndicator", sortDirection: sortDirection })), children; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = defaultHeaderRenderer; var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _SortIndicator = __webpack_require__(196), _SortIndicator2 = _interopRequireDefault(_SortIndicator); }, /* 196 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function SortIndicator(_ref) { var sortDirection = _ref.sortDirection, classNames = (0, _classnames2["default"])("FlexTable__sortableHeaderIcon", { "FlexTable__sortableHeaderIcon--ASC": sortDirection === _SortDirection2["default"].ASC, "FlexTable__sortableHeaderIcon--DESC": sortDirection === _SortDirection2["default"].DESC }); return _react2["default"].createElement("svg", { className: classNames, width: 18, height: 18, viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg" }, sortDirection === _SortDirection2["default"].ASC ? _react2["default"].createElement("path", { d: "M7 14l5-5 5 5z" }) : _react2["default"].createElement("path", { d: "M7 10l5 5 5-5z" }), _react2["default"].createElement("path", { d: "M0 0h24v24H0z", fill: "none" })); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = SortIndicator; var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _SortDirection = __webpack_require__(197), _SortDirection2 = _interopRequireDefault(_SortDirection); SortIndicator.propTypes = { sortDirection: _react.PropTypes.oneOf([ _SortDirection2["default"].ASC, _SortDirection2["default"].DESC ]) }; }, /* 197 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var SortDirection = { ASC: "ASC", DESC: "DESC" }; exports["default"] = SortDirection; }, /* 198 */ /***/ function(module, exports) { "use strict"; function defaultCellRenderer(_ref) { var cellData = _ref.cellData; _ref.cellDataKey, _ref.columnData, _ref.rowData, _ref.rowIndex; return null == cellData ? "" : String(cellData); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = defaultCellRenderer; }, /* 199 */ /***/ function(module, exports) { "use strict"; function defaultCellDataGetter(_ref) { var dataKey = (_ref.columnData, _ref.dataKey), rowData = _ref.rowData; return rowData.get instanceof Function ? rowData.get(dataKey) : rowData[dataKey]; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports["default"] = defaultCellDataGetter; }, /* 200 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.InfiniteLoader = exports["default"] = void 0; var _InfiniteLoader2 = __webpack_require__(201), _InfiniteLoader3 = _interopRequireDefault(_InfiniteLoader2); exports["default"] = _InfiniteLoader3["default"], exports.InfiniteLoader = _InfiniteLoader3["default"]; }, /* 201 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function isRangeVisible(_ref2) { var lastRenderedStartIndex = _ref2.lastRenderedStartIndex, lastRenderedStopIndex = _ref2.lastRenderedStopIndex, startIndex = _ref2.startIndex, stopIndex = _ref2.stopIndex; return !(startIndex > lastRenderedStopIndex || lastRenderedStartIndex > stopIndex); } function scanForUnloadedRanges(_ref3) { for (var isRowLoaded = _ref3.isRowLoaded, minimumBatchSize = _ref3.minimumBatchSize, rowCount = _ref3.rowCount, startIndex = _ref3.startIndex, stopIndex = _ref3.stopIndex, unloadedRanges = [], rangeStartIndex = null, rangeStopIndex = null, index = startIndex; stopIndex >= index; index++) { var loaded = isRowLoaded({ index: index }); loaded ? null !== rangeStopIndex && (unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }), rangeStartIndex = rangeStopIndex = null) : (rangeStopIndex = index, null === rangeStartIndex && (rangeStartIndex = index)); } if (null !== rangeStopIndex) { for (var potentialStopIndex = Math.min(Math.max(rangeStopIndex, rangeStartIndex + minimumBatchSize - 1), rowCount - 1), _index = rangeStopIndex + 1; potentialStopIndex >= _index && !isRowLoaded({ index: _index }); _index++) rangeStopIndex = _index; unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }); } if (unloadedRanges.length) for (var firstUnloadedRange = unloadedRanges[0]; firstUnloadedRange.stopIndex - firstUnloadedRange.startIndex + 1 < minimumBatchSize && firstUnloadedRange.startIndex > 0; ) { var _index2 = firstUnloadedRange.startIndex - 1; if (isRowLoaded({ index: _index2 })) break; firstUnloadedRange.startIndex = _index2; } return unloadedRanges; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(); exports.isRangeVisible = isRangeVisible, exports.scanForUnloadedRanges = scanForUnloadedRanges; var _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), InfiniteLoader = function(_Component) { function InfiniteLoader(props, context) { _classCallCheck(this, InfiniteLoader); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(InfiniteLoader).call(this, props, context)); return _this._onRowsRendered = _this._onRowsRendered.bind(_this), _this._registerChild = _this._registerChild.bind(_this), _this; } return _inherits(InfiniteLoader, _Component), _createClass(InfiniteLoader, [ { key: "render", value: function() { var children = this.props.children; return children({ onRowsRendered: this._onRowsRendered, registerChild: this._registerChild }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onRowsRendered", value: function(_ref) { var _this2 = this, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex, _props = this.props, isRowLoaded = _props.isRowLoaded, loadMoreRows = _props.loadMoreRows, minimumBatchSize = _props.minimumBatchSize, rowCount = _props.rowCount, threshold = _props.threshold; this._lastRenderedStartIndex = startIndex, this._lastRenderedStopIndex = stopIndex; var unloadedRanges = scanForUnloadedRanges({ isRowLoaded: isRowLoaded, minimumBatchSize: minimumBatchSize, rowCount: rowCount, startIndex: Math.max(0, startIndex - threshold), stopIndex: Math.min(rowCount - 1, stopIndex + threshold) }); unloadedRanges.forEach(function(unloadedRange) { var promise = loadMoreRows(unloadedRange); promise && promise.then(function() { isRangeVisible({ lastRenderedStartIndex: _this2._lastRenderedStartIndex, lastRenderedStopIndex: _this2._lastRenderedStopIndex, startIndex: unloadedRange.startIndex, stopIndex: unloadedRange.stopIndex }) && _this2._registeredChild && _this2._registeredChild.forceUpdate(); }); }); } }, { key: "_registerChild", value: function(registeredChild) { this._registeredChild = registeredChild; } } ]), InfiniteLoader; }(_react.Component); InfiniteLoader.propTypes = { children: _react.PropTypes.func.isRequired, isRowLoaded: _react.PropTypes.func.isRequired, loadMoreRows: _react.PropTypes.func.isRequired, minimumBatchSize: _react.PropTypes.number.isRequired, rowCount: _react.PropTypes.number.isRequired, threshold: _react.PropTypes.number.isRequired }, InfiniteLoader.defaultProps = { minimumBatchSize: 10, rowCount: 0, threshold: 15 }, exports["default"] = InfiniteLoader; }, /* 202 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ScrollSync = exports["default"] = void 0; var _ScrollSync2 = __webpack_require__(203), _ScrollSync3 = _interopRequireDefault(_ScrollSync2); exports["default"] = _ScrollSync3["default"], exports.ScrollSync = _ScrollSync3["default"]; }, /* 203 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ScrollSync = function(_Component) { function ScrollSync(props, context) { _classCallCheck(this, ScrollSync); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ScrollSync).call(this, props, context)); return _this.state = { clientHeight: 0, clientWidth: 0, scrollHeight: 0, scrollLeft: 0, scrollTop: 0, scrollWidth: 0 }, _this._onScroll = _this._onScroll.bind(_this), _this; } return _inherits(ScrollSync, _Component), _createClass(ScrollSync, [ { key: "render", value: function() { var children = this.props.children, _state = this.state, clientHeight = _state.clientHeight, clientWidth = _state.clientWidth, scrollHeight = _state.scrollHeight, scrollLeft = _state.scrollLeft, scrollTop = _state.scrollTop, scrollWidth = _state.scrollWidth; return children({ clientHeight: clientHeight, clientWidth: clientWidth, onScroll: this._onScroll, scrollHeight: scrollHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: scrollWidth }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_onScroll", value: function(_ref) { var clientHeight = _ref.clientHeight, clientWidth = _ref.clientWidth, scrollHeight = _ref.scrollHeight, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, scrollWidth = _ref.scrollWidth; this.setState({ clientHeight: clientHeight, clientWidth: clientWidth, scrollHeight: scrollHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: scrollWidth }); } } ]), ScrollSync; }(_react.Component); ScrollSync.propTypes = { children: _react.PropTypes.func.isRequired }, exports["default"] = ScrollSync; }, /* 204 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.VirtualScroll = exports["default"] = void 0; var _VirtualScroll2 = __webpack_require__(205), _VirtualScroll3 = _interopRequireDefault(_VirtualScroll2); exports["default"] = _VirtualScroll3["default"], exports.VirtualScroll = _VirtualScroll3["default"]; }, /* 205 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }, _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _Grid = __webpack_require__(184), _Grid2 = _interopRequireDefault(_Grid), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), VirtualScroll = function(_Component) { function VirtualScroll(props, context) { _classCallCheck(this, VirtualScroll); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(VirtualScroll).call(this, props, context)); return _this._cellRenderer = _this._cellRenderer.bind(_this), _this._createRowClassNameGetter = _this._createRowClassNameGetter.bind(_this), _this._createRowStyleGetter = _this._createRowStyleGetter.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this), _this; } return _inherits(VirtualScroll, _Component), _createClass(VirtualScroll, [ { key: "forceUpdateGrid", value: function() { this.refs.Grid.forceUpdate(); } }, { key: "measureAllRows", value: function() { this.refs.Grid.measureAllCells(); } }, { key: "recomputeRowHeights", value: function() { var index = arguments.length <= 0 || void 0 === arguments[0] ? 0 : arguments[0]; this.refs.Grid.recomputeGridSize({ rowIndex: index }), this.forceUpdateGrid(); } }, { key: "render", value: function() { var _props = this.props, autoHeight = _props.autoHeight, className = _props.className, estimatedRowSize = _props.estimatedRowSize, height = _props.height, noRowsRenderer = _props.noRowsRenderer, rowHeight = _props.rowHeight, overscanRowCount = _props.overscanRowCount, rowCount = _props.rowCount, scrollToAlignment = _props.scrollToAlignment, scrollToIndex = _props.scrollToIndex, scrollTop = _props.scrollTop, style = _props.style, tabIndex = _props.tabIndex, width = _props.width, classNames = (0, _classnames2["default"])("VirtualScroll", className); return _react2["default"].createElement(_Grid2["default"], { autoHeight: autoHeight, "aria-label": this.props["aria-label"], className: classNames, cellRenderer: this._cellRenderer, cellClassName: this._createRowClassNameGetter(), cellStyle: this._createRowStyleGetter(), columnWidth: width, columnCount: 1, estimatedRowSize: estimatedRowSize, height: height, noContentRenderer: noRowsRenderer, onScroll: this._onScroll, onSectionRendered: this._onSectionRendered, overscanRowCount: overscanRowCount, ref: "Grid", rowHeight: rowHeight, rowCount: rowCount, scrollToAlignment: scrollToAlignment, scrollToRow: scrollToIndex, scrollTop: scrollTop, style: style, tabIndex: tabIndex, width: width }); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_cellRenderer", value: function(_ref) { var isScrolling = (_ref.columnIndex, _ref.isScrolling), rowIndex = _ref.rowIndex, rowRenderer = this.props.rowRenderer; return rowRenderer({ index: rowIndex, isScrolling: isScrolling }); } }, { key: "_createRowClassNameGetter", value: function() { var rowClassName = this.props.rowClassName; return rowClassName instanceof Function ? function(_ref2) { var rowIndex = _ref2.rowIndex; return rowClassName({ index: rowIndex }); } : function() { return rowClassName; }; } }, { key: "_createRowStyleGetter", value: function() { var rowStyle = this.props.rowStyle, wrapped = rowStyle instanceof Function ? rowStyle : function() { return rowStyle; }; return function(_ref3) { var rowIndex = _ref3.rowIndex; return _extends({ width: "100%" }, wrapped({ index: rowIndex })); }; } }, { key: "_onScroll", value: function(_ref4) { var clientHeight = _ref4.clientHeight, scrollHeight = _ref4.scrollHeight, scrollTop = _ref4.scrollTop, onScroll = this.props.onScroll; onScroll({ clientHeight: clientHeight, scrollHeight: scrollHeight, scrollTop: scrollTop }); } }, { key: "_onSectionRendered", value: function(_ref5) { var rowOverscanStartIndex = _ref5.rowOverscanStartIndex, rowOverscanStopIndex = _ref5.rowOverscanStopIndex, rowStartIndex = _ref5.rowStartIndex, rowStopIndex = _ref5.rowStopIndex, onRowsRendered = this.props.onRowsRendered; onRowsRendered({ overscanStartIndex: rowOverscanStartIndex, overscanStopIndex: rowOverscanStopIndex, startIndex: rowStartIndex, stopIndex: rowStopIndex }); } } ]), VirtualScroll; }(_react.Component); VirtualScroll.propTypes = { "aria-label": _react.PropTypes.string, autoHeight: _react.PropTypes.bool, className: _react.PropTypes.string, estimatedRowSize: _react.PropTypes.number.isRequired, height: _react.PropTypes.number.isRequired, noRowsRenderer: _react.PropTypes.func.isRequired, onRowsRendered: _react.PropTypes.func.isRequired, overscanRowCount: _react.PropTypes.number.isRequired, onScroll: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowRenderer: _react.PropTypes.func.isRequired, rowClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), rowCount: _react.PropTypes.number.isRequired, rowStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]), scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired, scrollToIndex: _react.PropTypes.number, scrollTop: _react.PropTypes.number, style: _react.PropTypes.object, tabIndex: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, VirtualScroll.defaultProps = { estimatedRowSize: 30, noRowsRenderer: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; }, overscanRowCount: 10, scrollToAlignment: "auto", style: {} }, exports["default"] = VirtualScroll; }, /* 206 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.WindowScroller = exports["default"] = void 0; var _WindowScroller2 = __webpack_require__(207), _WindowScroller3 = _interopRequireDefault(_WindowScroller2); exports["default"] = _WindowScroller3["default"], exports.WindowScroller = _WindowScroller3["default"]; }, /* 207 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(10), _reactDom2 = _interopRequireDefault(_reactDom), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _raf = __webpack_require__(176), _raf2 = _interopRequireDefault(_raf), IS_SCROLLING_TIMEOUT = 150, WindowScroller = function(_Component) { function WindowScroller(props) { _classCallCheck(this, WindowScroller); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(WindowScroller).call(this, props)); return _this.state = { scrollTop: 0, height: 0 }, _this._onScrollWindow = _this._onScrollWindow.bind(_this), _this._onResizeWindow = _this._onResizeWindow.bind(_this), _this._enablePointerEventsAfterDelayCallback = _this._enablePointerEventsAfterDelayCallback.bind(_this), _this; } return _inherits(WindowScroller, _Component), _createClass(WindowScroller, [ { key: "componentDidMount", value: function() { this._positionFromTop = _reactDom2["default"].findDOMNode(this).getBoundingClientRect().top, this.setState({ height: window.innerHeight }), window.addEventListener("scroll", this._onScrollWindow, !1), window.addEventListener("resize", this._onResizeWindow, !1); } }, { key: "componentWillUnmount", value: function() { window.removeEventListener("scroll", this._onScrollWindow, !1), window.removeEventListener("resize", this._onResizeWindow, !1); } }, { key: "_setNextState", value: function(state) { var _this2 = this; this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId), this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() { _this2._setNextStateAnimationFrameId = null, _this2.setState(state); }); } }, { key: "render", value: function() { var children = this.props.children, _state = this.state, scrollTop = _state.scrollTop, height = _state.height; return _react2["default"].createElement("div", null, children({ height: height, scrollTop: scrollTop })); } }, { key: "shouldComponentUpdate", value: function(nextProps, nextState) { return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState); } }, { key: "_enablePointerEventsAfterDelay", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._disablePointerEventsTimeoutId = setTimeout(this._enablePointerEventsAfterDelayCallback, IS_SCROLLING_TIMEOUT); } }, { key: "_enablePointerEventsAfterDelayCallback", value: function() { this._disablePointerEventsTimeoutId = null, document.body.style.pointerEvents = this._originalBodyPointerEvents, this._originalBodyPointerEvents = null; } }, { key: "_onResizeWindow", value: function(event) { var onResize = this.props.onResize, height = window.innerHeight || 0; this.setState({ height: height }), onResize({ height: height }); } }, { key: "_onScrollWindow", value: function(event) { var onScroll = this.props.onScroll, scrollY = "scrollY" in window ? window.scrollY : document.documentElement.scrollTop, scrollTop = Math.max(0, scrollY - this._positionFromTop); this._setNextState({ scrollTop: scrollTop }), null == this._originalBodyPointerEvents && (this._originalBodyPointerEvents = document.body.style.pointerEvents, document.body.style.pointerEvents = "none", this._enablePointerEventsAfterDelay()), onScroll({ scrollTop: scrollTop }); } } ]), WindowScroller; }(_react.Component); WindowScroller.propTypes = { children: _react.PropTypes.func.isRequired, onResize: _react.PropTypes.func.isRequired, onScroll: _react.PropTypes.func.isRequired }, WindowScroller.defaultProps = { onResize: function() {}, onScroll: function() {} }, exports["default"] = WindowScroller; } ]); }); //# sourceMappingURL=react-virtualized.js.map
src/index.js
chrisbuttery/react-tape
import './css/style.css'; import React from 'react'; import Hello from './js/component'; (function () { React.render(<Hello />, document.getElementById('root')); }());
examples/src/components/SelectedValuesField.js
urvashi01/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 SelectedValuesField = React.createClass({ displayName: 'SelectedValuesField', propTypes: { allowCreate: React.PropTypes.bool, hint: React.PropTypes.string, label: React.PropTypes.string, options: React.PropTypes.array, }, onLabelClick (data, event) { console.log(data, event); }, renderHint () { if (!this.props.hint) return null; return ( <div className="hint">{this.props.hint}</div> ); }, render () { return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select allowCreate={this.props.allowCreate} onOptionLabelClick={this.onLabelClick} value={this.props.options.slice(1,3)} multi={true} placeholder="Select your favourite(s)" options={this.props.options} onChange={logChange} /> {this.renderHint()} </div> ); } }); module.exports = SelectedValuesField;