code
stringlengths
2
1.05M
/** * A wrapper around a native element inside of a View. * * An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM * element. */ // Note: We don't expose things like `Injector`, `ViewContainer`, ... here, // i.e. users have to ask for what they need. With that, we can build better analysis tools // and could do better codegen in the future. export class ElementRef { constructor(nativeElement) { this.nativeElement = nativeElement; } }
var MarchingOrder = (() => { 'use strict'; const MENU_CMD = '!showMarchingOrderMenu'; const FOLLOW_CMD = '!marchingOrderFollow'; const STOP_ALL_CMD = '!marchingOrderStopAll'; const DEFAULT_USE_CMD = '!marchingOrderUseDefault'; const DEFAULT_SET_CMD = '!marchingOrderSetDefault'; /** * Makes tokens follow each other in order of some compass direction. * @param {Graphic[]} tokens * @param {String} direction */ function _cmdFollowDirection(tokens, direction) { tokens.sort((a,b) => { let aX = parseFloat(a.get("left")); let bX = parseFloat(b.get("left")); let aY = parseFloat(a.get("top")); let bY = parseFloat(b.get("top")); if(direction === "north") return (aY - bY); else if(direction === "south") return (bY - aY); else if(direction === "west") return (aX - bX); else // east return (bX - aX); }); setMarchingOrder(tokens); } /** * Makes the tokens follow a token with the specified name. * The tokens behind the leader form a line in no particular order. * @param {Graphic[]} tokens * @param {Graphic} leader */ function _cmdFollowTargetToken(playerid, follower, leader) { // Can't follow self. if(follower === leader) return; // Include the follower's previous followers in the marching order. let tokens = [follower]; let next = follower.follower; while(next) { if(next === leader) throw new Error('Cyclical marching orders are not allowed!'); tokens.push(next); next = next.follower; } tokens.unshift(leader); setMarchingOrder(tokens); } /** * Makes a token's followers move to the token's previous position. * @param {Graphic} leader */ function _doFollowMovement(leader) { let follower = leader.follower; follower.prevLeft = follower.get("left"); follower.prevTop = follower.get("top"); follower.prevRotation = follower.get("rotation"); follower.set("left",leader.prevLeft); follower.set("top",leader.prevTop); follower.set("rotation", leader.prevRotation); if(typeof CustomStatusMarkers !== 'undefined') CustomStatusMarkers.repositionStatusMarkers(follower); } /** * Makes a token follow another token. * @param {Graphic} leader * @param {Graphic} follower */ function follow(leader, follower) { if(!leader || !follower) return; // unbind all of follower's following links. unfollow(follower); let prevFollower = leader.follower; follower.leader = leader; follower.follower = prevFollower; leader.follower = follower; if(prevFollower) prevFollower.leader = follower; } /** * Gets the persisted state for this script. * @return {MarchingOrderState} */ function getState() { if(!state.marchingOrder) state.marchingOrder = { defaultOrder: [] }; return state.marchingOrder; } /** * Tries to parse an API command argument as a compass direction. * @param {String} msgTxt * @return {String} The compass direction, or null if it couldn't be parsed. */ function _parseDirection(msgTxt) { if(msgTxt.includes('north')) return "north"; else if(msgTxt.includes('south')) return "south"; else if(msgTxt.includes('west')) return "west"; else if(msgTxt.includes('east')) return "east"; else return null; } /** * Sets the default marching order, given whoever is the leader of a * marching order line. * @param {string} playerId * @param {graphic} leader */ function setDefaultMarchingOrder(playerId, leader) { let items = []; let next = leader; while(next) { let represents = next.get('represents'); if(!represents) throw new Error('All tokens in the default marching order must represent a character.'); items.push({ represents, imgsrc: next.get('imgsrc'), name: next.get('name') }); next = next.follower; } getState().defaultOrder = items; _showMenu(playerId); } /** * Sets a marching order for an array of tokens, with the token at index 0 * being the leader. * @param {Graphic[]} */ function setMarchingOrder(tokens) { _.each(_.range(tokens.length-1), i => { let leader = tokens[i]; let follower = tokens[i+1]; sendChat("Marching Order", follower.get("name") + " is following " + leader.get("name")); follow(leader, follower); }); } /** * Shows the menu for Marching Order in the chat. */ function _showMenu(playerId) { let moState = getState(); let html = ''; // Menu options let actionsHtml = '<div style="text-align: center;">[Follow](' + FOLLOW_CMD + ' &#64;{selected|token_id} &#64;{target|token_id})</div>'; if(playerIsGM(playerId)) { // Cardinal directions (GM only) actionsHtml += '<div style="text-align: center;">March in order:</div>'; actionsHtml += '<div><table style="width: 100%;">'; actionsHtml += '<tr><td></td><td>[North](' + FOLLOW_CMD + ' north)</td><td></td></tr>'; actionsHtml += '<tr><td>[West](' + FOLLOW_CMD + ' west)</td><td></td><td>[East](' + FOLLOW_CMD + ' east)</td></tr>'; actionsHtml += '<tr><td></td><td>[South](' + FOLLOW_CMD + ' south)</td><td></td></tr>'; actionsHtml += '</table></div>'; // Stop all following actionsHtml += '<div style="padding-top: 1em; text-align: center;">[Stop All Following](' + STOP_ALL_CMD + ')</div>'; // Default marching order actionsHtml += '<div style="padding-top: 1em; text-align: center;">Default Marching Order:</div>'; if(moState.defaultOrder.length > 0) { actionsHtml += '<div style="text-align: center; vertical-allign: middle;">'; _.each(moState.defaultOrder, (item, index) => { actionsHtml += '<span style="display: inline-block;">' if(index != 0) actionsHtml += ' ◀ '; actionsHtml += `<img src="${item.imgsrc}" title="${item.name}" style="height: 35px; vertical-align: middle; width: 35px;"></span>`; }); actionsHtml += '</div>'; actionsHtml += '<div style="text-align: center;">[Use Default](' + DEFAULT_USE_CMD + ') [Set Default](' + DEFAULT_SET_CMD + ' &#64;{selected|token_id})</div>'; } else { actionsHtml += '<div style="font-size: 0.8em; text-align: center;">No default order has been set.</div>'; actionsHtml += '<div style="text-align: center;">[Set Default](' + DEFAULT_SET_CMD + ' &#64;{selected|token_id})'; } } html += _showMenuPanel('Menu Actions', actionsHtml); _whisper(playerId, html); } function _showMenuPanel(header, content) { let html = '<div style="background: #fff; border: solid 1px #000; border-radius: 5px; font-weight: bold; margin-bottom: 1em; overflow: hidden;">'; html += '<div style="background: #000; color: #fff; text-align: center;">' + header + '</div>'; html += '<div style="padding: 5px;">' + content + '</div>'; html += '</div>'; return html; } /** * Makes a token stop following other tokens. * @param {Graphic} token */ function unfollow(token) { if(token.leader) token.leader.follower = token.follower; if(token.follower) token.follower.leader = token.leader; token.leader = null; token.follower = null; } /** * Makes all tokens stop following each other. */ function _unfollowAll() { let allObjs = findObjs({ _type: 'graphic', layer: 'objects' }); _.each(allObjs, obj => { unfollow(obj); }); sendChat("Marching Order", "Tokens are no longer following each other."); } /** * Applies the default marching order to the page that currently has the * player ribbon. */ function useDefaultMarchingOrder() { let playerpageid = Campaign().get('playerpageid'); let tokens = []; let defaultOrder = getState().defaultOrder; _.each(defaultOrder, item => { let token = findObjs({ _type: 'graphic', _pageid: playerpageid, represents: item.represents })[0]; if(token) tokens.push(token); }); setMarchingOrder(tokens); } /** * @private * Whispers a Marching Order message to someone. */ function _whisper(playerId, msg) { let name = (getObj('player', playerId)||{get:()=>'API'}).get('_displayname'); sendChat('Marching Order', '/w "' + name + '" ' + msg); } // When the API is loaded, install the Custom Status Marker menu macro // if it isn't already installed. on('ready', () => { let macro = findObjs({ _type: 'macro', name: 'MarchingOrderMenu' })[0]; if(!macro) { let players = findObjs({ _type: 'player' }); _.each(players, player => { createObj('macro', { _playerid: player.get('_id'), name: 'MarchingOrderMenu', action: MENU_CMD }); }); } log('→→→ Initialized Marching Order →→→'); }); /** * Set up our chat command handler. */ on("chat:message", msg => { try { if(msg.content.startsWith(FOLLOW_CMD)) { let argv = msg.content.split(' '); let dirMatch = argv[1].match(/(north|south|east|west)/); if(dirMatch) { let selected = []; _.each(msg.selected, item => { if(item._type === 'graphic') { let token = getObj('graphic', item._id); selected.push(token); } }); _cmdFollowDirection(selected, dirMatch[0]); } else { log(argv); let follower = getObj('graphic', argv[1]); let leader = getObj('graphic', argv[2]); if(follower && leader) _cmdFollowTargetToken(msg.playerid, follower, leader); } } else if(msg.content.startsWith(STOP_ALL_CMD)) { _unfollowAll(); } else if(msg.content.startsWith(DEFAULT_SET_CMD)) { let argv = msg.content.split(' '); let leader = getObj('graphic', argv[1]); if(leader) setDefaultMarchingOrder(msg.playerid, leader); } else if(msg.content.startsWith(DEFAULT_USE_CMD)) { useDefaultMarchingOrder(); } else if(msg.content.startsWith(MENU_CMD)) _showMenu(msg.playerid); } catch(err) { log(err.message); log(err.stack); _whisper(msg.playerid, 'ERROR: ' + err.message); } }); /** * Set up an event handler to do the marching order effect when the * leader tokens move! */ on("change:graphic", (obj, prev) => { try { let leader = obj; leader.prevLeft = prev["left"]; leader.prevTop = prev["top"]; leader.prevRotation = prev["rotation"]; // Only move the followers if there was a change in either the leader's // left or top attributes. if(leader.get("left") != leader.prevLeft || leader.get("top") != leader.prevTop) { // We stepped out of line. Stop following the guy in front of us. if(leader.leader) unfollow(leader); // move everyone to the previous position of the token in front of them. while(leader.follower) { _doFollowMovement(leader); leader = leader.follower; // avoid cycles. if(leader == obj) return; } } } catch(err) { log(err.message); log(err.stack); _whisper(msg.playerid, 'ERROR: ' + err.message); } }); // The exposed API. return { follow, set: setMarchingOrder, unfollow }; })();
var common = require("./common") , odbc = require("../") , assert = require("assert") , openCallback = 0 , closeCallback = 0 , openCount = 10 , connections = [] ; for (var x = 0; x < openCount; x++ ) { (function () { var db = new odbc.Database(); connections.push(db); db.open(common.connectionString, function(err) { assert.equal(err, null); openCallback += 1; maybeClose(); }); })(); } function maybeClose() { if (openCount == openCallback) { doClose(); } } function doClose() { connections.forEach(function (db) { db.close(function () { closeCallback += 1; maybeFinish(); }); }); } function maybeFinish() { if (openCount == closeCallback) { console.log('Done'); } }
export default require('@trails/generator-util').service
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * Namespace: OpenLayers.Date * Contains implementations of Date.parse and date.toISOString that match the * ECMAScript 5 specification for parsing RFC 3339 dates. * http://tools.ietf.org/html/rfc3339 */ OpenLayers.Date = { /** * APIMethod: toISOString * Generates a string representing a date. The format of the string follows * the profile of ISO 8601 for date and time on the Internet (see * http://tools.ietf.org/html/rfc3339). If the toISOString method is * available on the Date prototype, that is used. The toISOString * method for Date instances is defined in ECMA-262. * * Parameters: * date - {Date} A date object. * * Returns: * {String} A string representing the date (e.g. * "2010-08-07T16:58:23.123Z"). If the date does not have a valid time * (i.e. isNaN(date.getTime())) this method returns the string "Invalid * Date". The ECMA standard says the toISOString method should throw * RangeError in this case, but Firefox returns a string instead. For * best results, use isNaN(date.getTime()) to determine date validity * before generating date strings. */ toISOString: (function() { if ("toISOString" in Date.prototype) { return function(date) { return date.toISOString(); }; } else { function pad(num, len) { var str = num + ""; while (str.length < len) { str = "0" + str; } return str; } return function(date) { var str; if (isNaN(date.getTime())) { // ECMA-262 says throw RangeError, Firefox returns // "Invalid Date" str = "Invalid Date"; } else { str = date.getUTCFullYear() + "-" + pad(date.getUTCMonth() + 1, 2) + "-" + pad(date.getUTCDate(), 2) + "T" + pad(date.getUTCHours(), 2) + ":" + pad(date.getUTCMinutes(), 2) + ":" + pad(date.getUTCSeconds(), 2) + "." + pad(date.getUTCMilliseconds(), 3) + "Z"; } return str; }; } })(), /** * APIMethod: parse * Generate a date object from a string. The format for the string follows * the profile of ISO 8601 for date and time on the Internet (see * http://tools.ietf.org/html/rfc3339). We don't call the native * Date.parse because of inconsistency between implmentations. In * Chrome, calling Date.parse with a string that doesn't contain any * indication of the timezone (e.g. "2011"), the date is interpreted * in local time. On Firefox, the assumption is UTC. * * Parameters: * str - {String} A string representing the date (e.g. * "2010", "2010-08", "2010-08-07", "2010-08-07T16:58:23.123Z", * "2010-08-07T11:58:23.123-06"). * * Returns: * {Date} A date object. If the string could not be parsed, an invalid * date is returned (i.e. isNaN(date.getTime())). */ parse: function(str) { var date; var match = str.match(/^(?:(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?)?(?:(?:T(\d{1,2}):(\d{2}):(\d{2}(?:\.\d+)?)(Z|(?:[+-]\d{1,2}(?::(\d{2}))?)))|Z)?$/); if (match && (match[1] || match[7])) { // must have at least year or time var year = parseInt(match[1], 10) || 0; var month = (parseInt(match[2], 10) - 1) || 0; var day = parseInt(match[3], 10) || 1; date = new Date(Date.UTC(year, month, day)); // optional time var type = match[7]; if (type) { var hours = parseInt(match[4], 10); var minutes = parseInt(match[5], 10); var secFrac = parseFloat(match[6]); var seconds = secFrac | 0; var milliseconds = Math.round(1000 * (secFrac - seconds)); date.setUTCHours(hours, minutes, seconds, milliseconds); // check offset if (type !== "Z") { var hoursOffset = parseInt(type, 10); var minutesOffset = parseInt(match[8], 10) || 0; var offset = -1000 * (60 * (hoursOffset * 60) + minutesOffset * 60); date = new Date(date.getTime() + offset); } } } else { date = new Date("invalid"); } return date; } };
"use strict"; var config = require("./../config"); var utils = require("./../utils"); var logger = require("./../logger").logger; var fs = require("fs"); var _ = require("lodash"); var path = require("path"); var info = { /** * Version info * @param {Object} pjson * @returns {String} */ getVersion: function (pjson) { console.log(pjson.version); return pjson.version; }, /** * Retrieve the config file * @returns {*} * @private * @param filePath */ getConfigFile: function (filePath) { return require(path.resolve(process.cwd() + "/" + filePath)); }, /** * Generate an example Config file. */ makeConfig: function (cwd) { var opts = require(__dirname + "/../" + config.configFile); var userOpts = {}; var ignore = ["excludedFileTypes", "injectFileTypes", "snippetOptions"]; Object.keys(opts).forEach(function (key) { if (!_.contains(ignore, key)) { userOpts[key] = opts[key]; } }); var file = fs.readFileSync(__dirname + config.template); file = file.toString().replace("//OPTS", JSON.stringify(userOpts, null, 4)); var path = cwd + config.userFile; fs.writeFile(path, file, function () { logger.info("Config file created {magenta:%s}", utils.resolveRelativeFilePath(path, cwd)); logger.info( "To use it, in the same directory run: " + "{cyan:browser-sync start --config bs-config.js}" ); }); } }; module.exports = info;
/** * @fileoverview Tests for no-fixed rule * @author Beau Gunderson <beau@beaugunderson.com> */ "use strict"; let Solium = require("solium"); let wrappers = require("./utils/wrappers"); let toContract = wrappers.toContract; let userConfig = { rules: { "security/no-fixed": "error" } }; // Generate all fixedMxN and ufixedMxN declarations for testing. // http://solidity.readthedocs.io/en/develop/types.html#fixed-point-numbers const N = Array.from(Array(81).keys()), M = Array.from(Array(32).keys()).map(i => { return 8 * (i+1); }); const fixedWithMNSuffix = [], ufixedWithMNSuffix = []; M.forEach(m => { N.forEach(n => { fixedWithMNSuffix.push(`fixed${m}x${n} foo;`); ufixedWithMNSuffix.push(`ufixed${m}x${n} bar;`); }); }); const fixedDeclarations = fixedWithMNSuffix.join("\n"), ufixedDeclarations = ufixedWithMNSuffix.join("\n"); describe("[RULE] no-fixed: Rejections", () => { it("should skip types which have sub-types (like MappingExpression)", done => { let code = `contract Foo { mapping(uint => string) users; mapping(uint => bytes32) users; mapping(bytes32 => uint) users; mapping(address => bool) users; }`; let errors = Solium.lint(code, userConfig); errors.should.be.Array(); errors.length.should.equal(0); done(); }); }); describe("[RULE] no-fixed: Rejections", function() { it("should reject contracts using fixed point declarations", function(done) { let code = toContract(` fixed x; ufixed y; function foo () { fixed a; ufixed b; } `), errors = Solium.lint(code, userConfig); errors.constructor.name.should.equal("Array"); errors.length.should.equal(4); code = toContract(` fixed128x8 x; ufixed128x8 x; mapping(ufixed128x8 => string) users; mapping(uint => fixed128x8) users; mapping(fixed128x8 => uint) users; mapping(address => ufixed128x8) users; struct Bubble { fixed128x8 abc; string name; ufixed128x8 bcd; address foo; } function foo () { fixed128x8 x; ufixed128x8 x; } `); errors = Solium.lint(code, userConfig); errors.should.be.Array(); errors.should.have.size(10); // eslint-disable-next-line no-unused-vars const codeExhaustive = toContract(` ${fixedDeclarations} ${ufixedDeclarations} function foo () { ${fixedDeclarations} ${ufixedDeclarations} } `); // TODO: Uncomment below test once we move to a fast (antlr) parser. // Since we're generating too many statements, below test will take a lot of time. // Also remove the eslint disable directive above /* errors = Solium.lint(codeExhaustive, userConfig); errors.should.be.Array(); errors.should.have.size(2 * (fixedWithMNSuffix.length + ufixedWithMNSuffix.length)); */ Solium.reset(); done(); }); it("should reject contracts using fixed point assignments", function(done) { let code = toContract(` fixed x = 100.89; ufixed y = 1.2; fixed128x8 x = 0.0; ufixed128x8 y = 0.0; uint z = 3; uint[] a; function foo () { fixed a = 2.0; ufixed b = 90.2; fixed128x8 x = 0.0; ufixed128x8 y = 0.0; } `); let errors = Solium.lint(code, userConfig); errors.constructor.name.should.equal("Array"); errors.length.should.equal(8); Solium.reset(); done(); }); });
// Copyright 2013 the V8 project authors. All rights reserved. // Redistribution and use 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // 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. // Flags: --allow-natives-syntax --smi-only-arrays --expose-gc // Flags: --track-allocation-sites --noalways-opt // Test element kind of objects. // Since --smi-only-arrays affects builtins, its default setting at compile // time sticks if built with snapshot. If --smi-only-arrays is deactivated // by default, only a no-snapshot build actually has smi-only arrays enabled // in this test case. Depending on whether smi-only arrays are actually // enabled, this test takes the appropriate code path to check smi-only arrays. // support_smi_only_arrays = %HasFastSmiElements(new Array(1,2,3,4,5,6,7,8)); support_smi_only_arrays = true; if (support_smi_only_arrays) { print("Tests include smi-only arrays."); } else { print("Tests do NOT include smi-only arrays."); } function isHoley(obj) { if (%HasFastHoleyElements(obj)) return true; return false; } function assertHoley(obj, name_opt) { assertEquals(true, isHoley(obj), name_opt); } function assertNotHoley(obj, name_opt) { assertEquals(false, isHoley(obj), name_opt); } if (support_smi_only_arrays) { function create_array(arg) { return new Array(arg); } obj = create_array(0); assertNotHoley(obj); create_array(0); %OptimizeFunctionOnNextCall(create_array); obj = create_array(10); assertHoley(obj); } // The code below would assert in debug or crash in release function f(length) { return new Array(length) } f(0); f(0); %OptimizeFunctionOnNextCall(f); var a = f(10); function g(a) { return a[0]; } var b = [0]; g(b); g(b); assertEquals(undefined, g(a));
/** * @fileoverview Firebase client Auth API. * Version: 3.6.10 * * Copyright 2017 Google Inc. All Rights Reserved. * * 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. * * @externs */ /** * Links the authenticated provider to the user account using a pop-up based * OAuth flow. * * If the linking is successful, the returned result will contain the user * and the provider's credential. * * <h4>Error Codes</h4> * <dl> * <dt>auth/auth-domain-config-required</dt> * <dd>Thrown if authDomain configuration is not provided when calling * firebase.initializeApp(). Check Firebase Console for instructions on * determining and passing that field.</dd> * <dt>auth/cancelled-popup-request</dt> * <dd>Thrown if successive popup operations are triggered. Only one popup * request is allowed at one time on a user or an auth instance. All the * popups would fail with this error except for the last one.</dd> * <dt>auth/credential-already-in-use</dt> * <dd>Thrown if the account corresponding to the credential already exists * among your users, or is already linked to a Firebase User. * For example, this error could be thrown if you are upgrading an anonymous * user to a Google user by linking a Google credential to it and the Google * credential used is already associated with an existing Firebase Google * user. * An <code>error.email</code> and <code>error.credential</code> * ({@link firebase.auth.AuthCredential}) fields are also provided. You can * recover from this error by signing in with that credential directly via * {@link firebase.auth.Auth#signInWithCredential}.</dd> * <dt>auth/email-already-in-use</dt> * <dd>Thrown if the email corresponding to the credential already exists * among your users. When thrown while linking a credential to an existing * user, an <code>error.email</code> and <code>error.credential</code> * ({@link firebase.auth.AuthCredential}) fields are also provided. * You have to link the credential to the existing user with that email if * you wish to continue signing in with that credential. To do so, call * {@link firebase.auth.Auth#fetchProvidersForEmail}, sign in to * <code>error.email</code> via one of the providers returned and then * {@link firebase.User#link} the original credential to that newly signed * in user.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if you have not enabled the provider in the Firebase Console. Go * to the Firebase Console for your project, in the Auth section and the * <strong>Sign in Method</strong> tab and configure the provider.</dd> * <dt>auth/popup-blocked</dt> * <dt>auth/operation-not-supported-in-this-environment</dt> * <dd>Thrown if this operation is not supported in the environment your * application is running on. "location.protocol" must be http or https. * </dd> * <dd>Thrown if the popup was blocked by the browser, typically when this * operation is triggered outside of a click handler.</dd> * <dt>auth/popup-closed-by-user</dt> * <dd>Thrown if the popup window is closed by the user without completing the * sign in to the provider.</dd> * <dt>auth/provider-already-linked</dt> * <dd>Thrown if the provider has already been linked to the user. This error is * thrown even if this is not the same provider's account that is currently * linked to the user.</dd> * <dt>auth/unauthorized-domain</dt> * <dd>Thrown if the app domain is not authorized for OAuth operations for your * Firebase project. Edit the list of authorized domains from the Firebase * console.</dd> * </dl> * * @example * // Creates the provider object. * var provider = new firebase.auth.FacebookAuthProvider(); * // You can add additional scopes to the provider: * provider.addScope('email'); * provider.addScope('user_friends'); * // Link with popup: * user.linkWithPopup(provider).then(function(result) { * // The firebase.User instance: * var user = result.user; * // The Facebook firebase.auth.AuthCredential containing the Facebook * // access token: * var credential = result.credential; * }, function(error) { * // An error happened. * }); * * @param {!firebase.auth.AuthProvider} provider The provider to authenticate. * The provider has to be an OAuth provider. Non-OAuth providers like {@link * firebase.auth.EmailAuthProvider} will throw an error. * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.User.prototype.linkWithPopup = function(provider) {}; /** * Links the authenticated provider to the user account using a full-page * redirect flow. * * <h4>Error Codes</h4> * <dl> * <dt>auth/auth-domain-config-required</dt> * <dd>Thrown if authDomain configuration is not provided when calling * firebase.initializeApp(). Check Firebase Console for instructions on * determining and passing that field.</dd> * <dt>auth/operation-not-supported-in-this-environment</dt> * <dd>Thrown if this operation is not supported in the environment your * application is running on. "location.protocol" must be http or https. * </dd> * <dt>auth/provider-already-linked</dt> * <dd>Thrown if the provider has already been linked to the user. This error is * thrown even if this is not the same provider's account that is currently * linked to the user.</dd> * <dt>auth/unauthorized-domain</dt> * <dd>Thrown if the app domain is not authorized for OAuth operations for your * Firebase project. Edit the list of authorized domains from the Firebase * console.</dd> * </dl> * * @param {!firebase.auth.AuthProvider} provider The provider to authenticate. * The provider has to be an OAuth provider. Non-OAuth providers like {@link * firebase.auth.EmailAuthProvider} will throw an error. * @return {!firebase.Promise<void>} */ firebase.User.prototype.linkWithRedirect = function(provider) {}; /** * Authenticates a Firebase client using a popup-based OAuth authentication * flow. * * If succeeds, returns the signed in user along with the provider's credential. * If sign in was unsuccessful, returns an error object containing additional * information about the error. * * <h4>Error Codes</h4> * <dl> * <dt>auth/account-exists-with-different-credential</dt> * <dd>Thrown if there already exists an account with the email address * asserted by the credential. Resolve this by calling * {@link firebase.auth.Auth#fetchProvidersForEmail} with the error.email * and then asking the user to sign in using one of the returned providers. * Once the user is signed in, the original credential retrieved from the * error.credential can be linked to the user with * {@link firebase.User#link} to prevent the user from signing in again * to the original provider via popup or redirect. If you are using * redirects for sign in, save the credential in session storage and then * retrieve on redirect and repopulate the credential using for example * {@link firebase.auth.GoogleAuthProvider#credential} depending on the * credential provider id and complete the link.</dd> * <dt>auth/auth-domain-config-required</dt> * <dd>Thrown if authDomain configuration is not provided when calling * firebase.initializeApp(). Check Firebase Console for instructions on * determining and passing that field.</dd> * <dt>auth/cancelled-popup-request</dt> * <dd>Thrown if successive popup operations are triggered. Only one popup * request is allowed at one time. All the popups would fail with this error * except for the last one.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if the type of account corresponding to the credential * is not enabled. Enable the account type in the Firebase Console, under * the Auth tab.</dd> * <dt>auth/operation-not-supported-in-this-environment</dt> * <dd>Thrown if this operation is not supported in the environment your * application is running on. "location.protocol" must be http or https. * </dd> * <dt>auth/popup-blocked</dt> * <dd>Thrown if the popup was blocked by the browser, typically when this * operation is triggered outside of a click handler.</dd> * <dt>auth/popup-closed-by-user</dt> * <dd>Thrown if the popup window is closed by the user without completing the * sign in to the provider.</dd> * <dt>auth/unauthorized-domain</dt> * <dd>Thrown if the app domain is not authorized for OAuth operations for your * Firebase project. Edit the list of authorized domains from the Firebase * console.</dd> * </dl> * * @example * // Creates the provider object. * var provider = new firebase.auth.FacebookAuthProvider(); * // You can add additional scopes to the provider: * provider.addScope('email'); * provider.addScope('user_friends'); * // Sign in with popup: * auth.signInWithPopup(provider).then(function(result) { * // The firebase.User instance: * var user = result.user; * // The Facebook firebase.auth.AuthCredential containing the Facebook * // access token: * var credential = result.credential; * }, function(error) { * // The provider's account email, can be used in case of * // auth/account-exists-with-different-credential to fetch the providers * // linked to the email: * var email = error.email; * // The provider's credential: * var credential = error.credential; * // In case of auth/account-exists-with-different-credential error, * // you can fetch the providers using this: * if (error.code === 'auth/account-exists-with-different-credential') { * auth.fetchProvidersForEmail(email).then(function(providers) { * // The returned 'providers' is a list of the available providers * // linked to the email address. Please refer to the guide for a more * // complete explanation on how to recover from this error. * }); * } * }); * * @param {!firebase.auth.AuthProvider} provider The provider to authenticate. * The provider has to be an OAuth provider. Non-OAuth providers like {@link * firebase.auth.EmailAuthProvider} will throw an error. * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.auth.Auth.prototype.signInWithPopup = function(provider) {}; /** * Authenticates a Firebase client using a full-page redirect flow. To handle * the results and errors for this operation, refer to {@link * firebase.auth.Auth#getRedirectResult}. * * <h4>Error Codes</h4> * <dl> * <dt>auth/auth-domain-config-required</dt> * <dd>Thrown if authDomain configuration is not provided when calling * firebase.initializeApp(). Check Firebase Console for instructions on * determining and passing that field.</dd> * <dt>auth/operation-not-supported-in-this-environment</dt> * <dd>Thrown if this operation is not supported in the environment your * application is running on. "location.protocol" must be http or https. * </dd> * <dt>auth/unauthorized-domain</dt> * <dd>Thrown if the app domain is not authorized for OAuth operations for your * Firebase project. Edit the list of authorized domains from the Firebase * console.</dd> * </dl> * * @param {!firebase.auth.AuthProvider} provider The provider to authenticate. * The provider has to be an OAuth provider. Non-OAuth providers like {@link * firebase.auth.EmailAuthProvider} will throw an error. * @return {!firebase.Promise<void>} */ firebase.auth.Auth.prototype.signInWithRedirect = function(provider) {}; /** * Returns a UserCredential from the redirect-based sign-in flow. * * If sign-in succeeded, returns the signed in user. If sign-in was * unsuccessful, fails with an error. If no redirect operation was called, * returns a UserCredential with a null User. * * <h4>Error Codes</h4> * <dl> * <dt>auth/account-exists-with-different-credential</dt> * <dd>Thrown if there already exists an account with the email address * asserted by the credential. Resolve this by calling * {@link firebase.auth.Auth#fetchProvidersForEmail} with the error.email * and then asking the user to sign in using one of the returned providers. * Once the user is signed in, the original credential retrieved from the * error.credential can be linked to the user with * {@link firebase.User#link} to prevent the user from signing in again * to the original provider via popup or redirect. If you are using * redirects for sign in, save the credential in session storage and then * retrieve on redirect and repopulate the credential using for example * {@link firebase.auth.GoogleAuthProvider#credential} depending on the * credential provider id and complete the link.</dd> * <dt>auth/auth-domain-config-required</dt> * <dd>Thrown if authDomain configuration is not provided when calling * firebase.initializeApp(). Check Firebase Console for instructions on * determining and passing that field.</dd> * <dt>auth/credential-already-in-use</dt> * <dd>Thrown if the account corresponding to the credential already exists * among your users, or is already linked to a Firebase User. * For example, this error could be thrown if you are upgrading an anonymous * user to a Google user by linking a Google credential to it and the Google * credential used is already associated with an existing Firebase Google * user. * An <code>error.email</code> and <code>error.credential</code> * ({@link firebase.auth.AuthCredential}) fields are also provided. You can * recover from this error by signing in with that credential directly via * {@link firebase.auth.Auth#signInWithCredential}.</dd> * <dt>auth/email-already-in-use</dt> * <dd>Thrown if the email corresponding to the credential already exists * among your users. When thrown while linking a credential to an existing * user, an <code>error.email</code> and <code>error.credential</code> * ({@link firebase.auth.AuthCredential}) fields are also provided. * You have to link the credential to the existing user with that email if * you wish to continue signing in with that credential. To do so, call * {@link firebase.auth.Auth#fetchProvidersForEmail}, sign in to * <code>error.email</code> via one of the providers returned and then * {@link firebase.User#link} the original credential to that newly signed * in user.</dd> * <dt>auth/operation-not-allowed</dt> * <dd>Thrown if the type of account corresponding to the credential * is not enabled. Enable the account type in the Firebase Console, under * the Auth tab.</dd> * <dt>auth/operation-not-supported-in-this-environment</dt> * <dd>Thrown if this operation is not supported in the environment your * application is running on. "location.protocol" must be http or https. * </dd> * <dt>auth/timeout</dt> * <dd>Thrown typically if the app domain is not authorized for OAuth operations * for your Firebase project. Edit the list of authorized domains from the * Firebase console.</dd> * </dl> * * @example * // First, we perform the signInWithRedirect. * // Creates the provider object. * var provider = new firebase.auth.FacebookAuthProvider(); * // You can add additional scopes to the provider: * provider.addScope('email'); * provider.addScope('user_friends'); * // Sign in with redirect: * auth.signInWithRedirect(provider) * //////////////////////////////////////////////////////////// * // The user is redirected to the provider's sign in flow... * //////////////////////////////////////////////////////////// * // Then redirected back to the app, where we check the redirect result: * auth.getRedirectResult().then(function(result) { * // The firebase.User instance: * var user = result.user; * // The Facebook firebase.auth.AuthCredential containing the Facebook * // access token: * var credential = result.credential; * }, function(error) { * // The provider's account email, can be used in case of * // auth/account-exists-with-different-credential to fetch the providers * // linked to the email: * var email = error.email; * // The provider's credential: * var credential = error.credential; * // In case of auth/account-exists-with-different-credential error, * // you can fetch the providers using this: * if (error.code === 'auth/account-exists-with-different-credential') { * auth.fetchProvidersForEmail(email).then(function(providers) { * // The returned 'providers' is a list of the available providers * // linked to the email address. Please refer to the guide for a more * // complete explanation on how to recover from this error. * }); * } * }); * * @return {!firebase.Promise<!firebase.auth.UserCredential>} */ firebase.auth.Auth.prototype.getRedirectResult = function() {};
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- var G = 0; var x = new Array(); var obj = new Object(); var i = 0; obj.y = 0; x[i] = i; function foo() { G++; return x; } function bar() { G++; return obj; } foo()[i++]++; bar().y += G; if (x[0] != 1 || x.length != 1 || G != 2 || i != 1 || obj.y != 2) { WScript.Echo("FAILED"); } else { WScript.Echo("Passed"); }
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- var a= [1, 2.2, 3.3] Array.prototype[4] = 10; function Test() { WScript.Echo(a.shift()); WScript.Echo(a.unshift(100,101,103)); } Test();
/* * * (c) 2010-2019 Torstein Honsi * * License: www.highcharts.com/license */ /** * Normalized interval. * * @interface Highcharts.NormalizedIntervalObject *//** * The interval in axis values (ms). * * @name Highcharts.NormalizedIntervalObject#unitRange * @type {number} *//** * The count. * * @name Highcharts.NormalizedIntervalObject#count * @type {number} */ /** * Function of an additional date format specifier. * * @callback Highcharts.TimeFormatCallbackFunction * * @param {number} timestamp * The time to format. * * @return {string} * The formatted portion of the date. */ /** * Additonal time tick information. * * @interface Highcharts.TimeTicksInfoObject * @augments Highcharts.NormalizedIntervalObject *//** * @name Highcharts.TimeTicksInfoObject#higherRanks * @type {Array<string>} *//** * @name Highcharts.TimeTicksInfoObject#totalRange * @type {number} */ /** * Time ticks. * * @interface Highcharts.TimeTicksObject * @augments Array<number> *//** * @name Highcharts.TimeTicksObject#info * @type {Highcharts.TimeTicksInfoObject} */ 'use strict'; import Highcharts from './Globals.js'; var H = Highcharts, defined = H.defined, extend = H.extend, merge = H.merge, pick = H.pick, timeUnits = H.timeUnits, win = H.win; /** * The Time class. Time settings are applied in general for each page using * `Highcharts.setOptions`, or individually for each Chart item through the * [time](https://api.highcharts.com/highcharts/time) options set. * * The Time object is available from {@link Highcharts.Chart#time}, * which refers to `Highcharts.time` if no individual time settings are * applied. * * @example * // Apply time settings globally * Highcharts.setOptions({ * time: { * timezone: 'Europe/London' * } * }); * * // Apply time settings by instance * var chart = Highcharts.chart('container', { * time: { * timezone: 'America/New_York' * }, * series: [{ * data: [1, 4, 3, 5] * }] * }); * * // Use the Time object * console.log( * 'Current time in New York', * chart.time.dateFormat('%Y-%m-%d %H:%M:%S', Date.now()) * ); * * @class * @name Highcharts.Time * * @param {Highcharts.TimeOptions} options * Time options as defined in [chart.options.time](/highcharts/time). * * @since 6.0.5 */ Highcharts.Time = function (options) { this.update(options, false); }; Highcharts.Time.prototype = { /** * Time options that can apply globally or to individual charts. These * settings affect how `datetime` axes are laid out, how tooltips are * formatted, how series * [pointIntervalUnit](#plotOptions.series.pointIntervalUnit) works and how * the Highstock range selector handles time. * * The common use case is that all charts in the same Highcharts object * share the same time settings, in which case the global settings are set * using `setOptions`. * * ```js * // Apply time settings globally * Highcharts.setOptions({ * time: { * timezone: 'Europe/London' * } * }); * // Apply time settings by instance * var chart = Highcharts.chart('container', { * time: { * timezone: 'America/New_York' * }, * series: [{ * data: [1, 4, 3, 5] * }] * }); * * // Use the Time object * console.log( * 'Current time in New York', * chart.time.dateFormat('%Y-%m-%d %H:%M:%S', Date.now()) * ); * ``` * * Since v6.0.5, the time options were moved from the `global` obect to the * `time` object, and time options can be set on each individual chart. * * @sample {highcharts|highstock} * highcharts/time/timezone/ * Set the timezone globally * @sample {highcharts} * highcharts/time/individual/ * Set the timezone per chart instance * @sample {highstock} * stock/time/individual/ * Set the timezone per chart instance * * @since 6.0.5 * @apioption time */ /** * Whether to use UTC time for axis scaling, tickmark placement and * time display in `Highcharts.dateFormat`. Advantages of using UTC * is that the time displays equally regardless of the user agent's * time zone settings. Local time can be used when the data is loaded * in real time or when correct Daylight Saving Time transitions are * required. * * @sample {highcharts} highcharts/time/useutc-true/ * True by default * @sample {highcharts} highcharts/time/useutc-false/ * False * * @type {boolean} * @default true * @apioption time.useUTC */ /** * A custom `Date` class for advanced date handling. For example, * [JDate](https://github.com/tahajahangir/jdate) can be hooked in to * handle Jalali dates. * * @type {*} * @since 4.0.4 * @product highcharts highstock gantt * @apioption time.Date */ /** * A callback to return the time zone offset for a given datetime. It * takes the timestamp in terms of milliseconds since January 1 1970, * and returns the timezone offset in minutes. This provides a hook * for drawing time based charts in specific time zones using their * local DST crossover dates, with the help of external libraries. * * @see [global.timezoneOffset](#global.timezoneOffset) * * @sample {highcharts|highstock} highcharts/time/gettimezoneoffset/ * Use moment.js to draw Oslo time regardless of browser locale * * @type {Function} * @since 4.1.0 * @product highcharts highstock gantt * @apioption time.getTimezoneOffset */ /** * Requires [moment.js](http://momentjs.com/). If the timezone option * is specified, it creates a default * [getTimezoneOffset](#time.getTimezoneOffset) function that looks * up the specified timezone in moment.js. If moment.js is not included, * this throws a Highcharts error in the console, but does not crash the * chart. * * @see [getTimezoneOffset](#time.getTimezoneOffset) * * @sample {highcharts|highstock} highcharts/time/timezone/ * Europe/Oslo * * @type {string} * @since 5.0.7 * @product highcharts highstock gantt * @apioption time.timezone */ /** * The timezone offset in minutes. Positive values are west, negative * values are east of UTC, as in the ECMAScript * [getTimezoneOffset](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset) * method. Use this to display UTC based data in a predefined time zone. * * @see [time.getTimezoneOffset](#time.getTimezoneOffset) * * @sample {highcharts|highstock} highcharts/time/timezoneoffset/ * Timezone offset * * @type {number} * @default 0 * @since 3.0.8 * @product highcharts highstock gantt * @apioption time.timezoneOffset */ defaultOptions: {}, /** * Update the Time object with current options. It is called internally on * initializing Highcharts, after running `Highcharts.setOptions` and on * `Chart.update`. * * @private * @function Highcharts.Time#update * * @param {Highcharts.TimeOptions} options */ update: function (options) { var useUTC = pick(options && options.useUTC, true), time = this; this.options = options = merge(true, this.options || {}, options); // Allow using a different Date class this.Date = options.Date || win.Date || Date; this.useUTC = useUTC; this.timezoneOffset = useUTC && options.timezoneOffset; /** * Get the time zone offset based on the current timezone information as * set in the global options. * * @function Highcharts.Time#getTimezoneOffset * * @param {number} timestamp * The JavaScript timestamp to inspect. * * @return {number} * The timezone offset in minutes compared to UTC. */ this.getTimezoneOffset = this.timezoneOffsetFunction(); /* * The time object has options allowing for variable time zones, meaning * the axis ticks or series data needs to consider this. */ this.variableTimezone = !!( !useUTC || options.getTimezoneOffset || options.timezone ); // UTC time with timezone handling if (this.variableTimezone || this.timezoneOffset) { this.get = function (unit, date) { var realMs = date.getTime(), ms = realMs - time.getTimezoneOffset(date), ret; date.setTime(ms); // Temporary adjust to timezone ret = date['getUTC' + unit](); date.setTime(realMs); // Reset return ret; }; this.set = function (unit, date, value) { var ms, offset, newOffset; // For lower order time units, just set it directly using local // time if ( unit === 'Milliseconds' || unit === 'Seconds' || // If we're dealting with minutes, we only need to // consider timezone if we're in Indian time zones with // half-hour offsets (#8768). ( unit === 'Minutes' && date.getTimezoneOffset() % 60 === 0 ) ) { date['set' + unit](value); // Higher order time units need to take the time zone into // account } else { // Adjust by timezone offset = time.getTimezoneOffset(date); ms = date.getTime() - offset; date.setTime(ms); date['setUTC' + unit](value); newOffset = time.getTimezoneOffset(date); ms = date.getTime() + newOffset; date.setTime(ms); } }; // UTC time with no timezone handling } else if (useUTC) { this.get = function (unit, date) { return date['getUTC' + unit](); }; this.set = function (unit, date, value) { return date['setUTC' + unit](value); }; // Local time } else { this.get = function (unit, date) { return date['get' + unit](); }; this.set = function (unit, date, value) { return date['set' + unit](value); }; } }, /** * Make a time and returns milliseconds. Interprets the inputs as UTC time, * local time or a specific timezone time depending on the current time * settings. * * @function Highcharts.Time#makeTime * * @param {number} year * The year * * @param {number} month * The month. Zero-based, so January is 0. * * @param {number} [date=1] * The day of the month * * @param {number} [hours=0] * The hour of the day, 0-23. * * @param {number} [minutes=0] * The minutes * * @param {number} [seconds=0] * The seconds * * @return {number} * The time in milliseconds since January 1st 1970. */ makeTime: function (year, month, date, hours, minutes, seconds) { var d, offset, newOffset; if (this.useUTC) { d = this.Date.UTC.apply(0, arguments); offset = this.getTimezoneOffset(d); d += offset; newOffset = this.getTimezoneOffset(d); if (offset !== newOffset) { d += newOffset - offset; // A special case for transitioning from summer time to winter time. // When the clock is set back, the same time is repeated twice, i.e. // 02:30 am is repeated since the clock is set back from 3 am to // 2 am. We need to make the same time as local Date does. } else if ( offset - 36e5 === this.getTimezoneOffset(d - 36e5) && !H.isSafari ) { d -= 36e5; } } else { d = new this.Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); } return d; }, /** * Sets the getTimezoneOffset function. If the `timezone` option is set, a * default getTimezoneOffset function with that timezone is returned. If * a `getTimezoneOffset` option is defined, it is returned. If neither are * specified, the function using the `timezoneOffset` option or 0 offset is * returned. * * @private * @function Highcharts.Time#timezoneOffsetFunction * * @return {Function} * A getTimezoneOffset function */ timezoneOffsetFunction: function () { var time = this, options = this.options, moment = win.moment; if (!this.useUTC) { return function (timestamp) { return new Date(timestamp).getTimezoneOffset() * 60000; }; } if (options.timezone) { if (!moment) { // getTimezoneOffset-function stays undefined because it depends // on Moment.js H.error(25); } else { return function (timestamp) { return -moment.tz( timestamp, options.timezone ).utcOffset() * 60000; }; } } // If not timezone is set, look for the getTimezoneOffset callback if (this.useUTC && options.getTimezoneOffset) { return function (timestamp) { return options.getTimezoneOffset(timestamp) * 60000; }; } // Last, use the `timezoneOffset` option if set return function () { return (time.timezoneOffset || 0) * 60000; }; }, /** * Formats a JavaScript date timestamp (milliseconds since Jan 1st 1970) * into a human readable date string. The format is a subset of the formats * for PHP's [strftime](http://www.php.net/manual/en/function.strftime.php) * function. Additional formats can be given in the * {@link Highcharts.dateFormats} hook. * * @function Highcharts.Time#dateFormat * * @param {string} [format] * The desired format where various time representations are * prefixed with %. * * @param {number} timestamp * The JavaScript timestamp. * * @param {boolean} [capitalize=false] * Upper case first letter in the return. * * @return {string} * The formatted date. */ dateFormat: function (format, timestamp, capitalize) { if (!H.defined(timestamp) || isNaN(timestamp)) { return H.defaultOptions.lang.invalidDate || ''; } format = H.pick(format, '%Y-%m-%d %H:%M:%S'); var time = this, date = new this.Date(timestamp), // get the basic time values hours = this.get('Hours', date), day = this.get('Day', date), dayOfMonth = this.get('Date', date), month = this.get('Month', date), fullYear = this.get('FullYear', date), lang = H.defaultOptions.lang, langWeekdays = lang.weekdays, shortWeekdays = lang.shortWeekdays, pad = H.pad, // List all format keys. Custom formats can be added from the // outside. replacements = H.extend( { // Day // Short weekday, like 'Mon' 'a': shortWeekdays ? shortWeekdays[day] : langWeekdays[day].substr(0, 3), // Long weekday, like 'Monday' 'A': langWeekdays[day], // Two digit day of the month, 01 to 31 'd': pad(dayOfMonth), // Day of the month, 1 through 31 'e': pad(dayOfMonth, 2, ' '), 'w': day, // Week (none implemented) // 'W': weekNumber(), // Month // Short month, like 'Jan' 'b': lang.shortMonths[month], // Long month, like 'January' 'B': lang.months[month], // Two digit month number, 01 through 12 'm': pad(month + 1), // Month number, 1 through 12 (#8150) 'o': month + 1, // Year // Two digits year, like 09 for 2009 'y': fullYear.toString().substr(2, 2), // Four digits year, like 2009 'Y': fullYear, // Time // Two digits hours in 24h format, 00 through 23 'H': pad(hours), // Hours in 24h format, 0 through 23 'k': hours, // Two digits hours in 12h format, 00 through 11 'I': pad((hours % 12) || 12), // Hours in 12h format, 1 through 12 'l': (hours % 12) || 12, // Two digits minutes, 00 through 59 'M': pad(time.get('Minutes', date)), // Upper case AM or PM 'p': hours < 12 ? 'AM' : 'PM', // Lower case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Two digits seconds, 00 through 59 'S': pad(date.getSeconds()), // Milliseconds (naming from Ruby) 'L': pad(Math.floor(timestamp % 1000), 3) }, H.dateFormats ); // Do the replaces H.objectEach(replacements, function (val, key) { // Regex would do it in one line, but this is faster while (format.indexOf('%' + key) !== -1) { format = format.replace( '%' + key, typeof val === 'function' ? val.call(time, timestamp) : val ); } }); // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }, /** * Resolve legacy formats of dateTimeLabelFormats (strings and arrays) into * an object. * @param {String|Array|Object} f General format description * @return {Object} The object definition */ resolveDTLFormat: function (f) { if (!H.isObject(f, true)) { f = H.splat(f); return { main: f[0], from: f[1], to: f[2] }; } return f; }, /** * Return an array with time positions distributed on round time values * right and right after min and max. Used in datetime axes as well as for * grouping data on a datetime axis. * * @function Highcharts.Time#getTimeTicks * * @param {Highcharts.NormalizedIntervalObject} normalizedInterval * The interval in axis values (ms) and the count * * @param {number} [min] * The minimum in axis values * * @param {number} [max] * The maximum in axis values * * @param {number} [startOfWeek=1] * * @return {Highcharts.TimeTicksObject} */ getTimeTicks: function ( normalizedInterval, min, max, startOfWeek ) { var time = this, Date = time.Date, tickPositions = [], i, higherRanks = {}, minYear, // used in months and years as a basis for Date.UTC() // When crossing DST, use the max. Resolves #6278. minDate = new Date(min), interval = normalizedInterval.unitRange, count = normalizedInterval.count || 1, variableDayLength, minDay; startOfWeek = pick(startOfWeek, 1); if (defined(min)) { // #1300 time.set( 'Milliseconds', minDate, interval >= timeUnits.second ? 0 : // #3935 count * Math.floor( time.get('Milliseconds', minDate) / count ) ); // #3652, #3654 if (interval >= timeUnits.second) { // second time.set( 'Seconds', minDate, interval >= timeUnits.minute ? 0 : // #3935 count * Math.floor(time.get('Seconds', minDate) / count) ); } if (interval >= timeUnits.minute) { // minute time.set( 'Minutes', minDate, interval >= timeUnits.hour ? 0 : count * Math.floor(time.get('Minutes', minDate) / count) ); } if (interval >= timeUnits.hour) { // hour time.set( 'Hours', minDate, interval >= timeUnits.day ? 0 : count * Math.floor( time.get('Hours', minDate) / count ) ); } if (interval >= timeUnits.day) { // day time.set( 'Date', minDate, interval >= timeUnits.month ? 1 : Math.max( 1, count * Math.floor( time.get('Date', minDate) / count ) ) ); } if (interval >= timeUnits.month) { // month time.set( 'Month', minDate, interval >= timeUnits.year ? 0 : count * Math.floor(time.get('Month', minDate) / count) ); minYear = time.get('FullYear', minDate); } if (interval >= timeUnits.year) { // year minYear -= minYear % count; time.set('FullYear', minDate, minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits.week) { // get start of current week, independent of count minDay = time.get('Day', minDate); time.set( 'Date', minDate, ( time.get('Date', minDate) - minDay + startOfWeek + // We don't want to skip days that are before // startOfWeek (#7051) (minDay < startOfWeek ? -7 : 0) ) ); } // Get basics for variable time spans minYear = time.get('FullYear', minDate); var minMonth = time.get('Month', minDate), minDateDate = time.get('Date', minDate), minHours = time.get('Hours', minDate); // Redefine min to the floored/rounded minimum time (#7432) min = minDate.getTime(); // Handle local timezone offset if (time.variableTimezone) { // Detect whether we need to take the DST crossover into // consideration. If we're crossing over DST, the day length may // be 23h or 25h and we need to compute the exact clock time for // each tick instead of just adding hours. This comes at a cost, // so first we find out if it is needed (#4951). variableDayLength = ( // Long range, assume we're crossing over. max - min > 4 * timeUnits.month || // Short range, check if min and max are in different time // zones. time.getTimezoneOffset(min) !== time.getTimezoneOffset(max) ); } // Iterate and add tick positions at appropriate values var t = minDate.getTime(); i = 1; while (t < max) { tickPositions.push(t); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits.year) { t = time.makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits.month) { t = time.makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it // jumps one hour at the DST crossover } else if ( variableDayLength && (interval === timeUnits.day || interval === timeUnits.week) ) { t = time.makeTime( minYear, minMonth, minDateDate + i * count * (interval === timeUnits.day ? 1 : 7) ); } else if ( variableDayLength && interval === timeUnits.hour && count > 1 ) { // make sure higher ranks are preserved across DST (#6797, // #7621) t = time.makeTime( minYear, minMonth, minDateDate, minHours + i * count ); // else, the interval is fixed and we use simple addition } else { t += interval * count; } i++; } // push the last time tickPositions.push(t); // Handle higher ranks. Mark new days if the time is on midnight // (#950, #1649, #1760, #3349). Use a reasonable dropout threshold // to prevent looping over dense data grouping (#6156). if (interval <= timeUnits.hour && tickPositions.length < 10000) { tickPositions.forEach(function (t) { if ( // Speed optimization, no need to run dateFormat unless // we're on a full or half hour t % 1800000 === 0 && // Check for local or global midnight time.dateFormat('%H%M%S%L', t) === '000000000' ) { higherRanks[t] = 'day'; } }); } } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; } }; // end of Time
/*jshint node:true */ /*global describe:false, it:false */ "use strict"; var Orchestrator = require('../'); var should = require('should'); require('mocha'); describe('orchestrator', function() { describe('_resetSpecificTasks()', function() { it('should set done = false on specified done tasks', function(done) { var orchestrator, task1, task2; // Arrange task1 = { name: 'test1', fn: function() {}, done: true }; task2 = { name: 'test2', fn: function() {}, done: true }; // the thing under test orchestrator = new Orchestrator(); orchestrator.tasks = { test1: task1, test2: task2 }; // Act orchestrator._resetSpecificTasks(['test1','test2']); // Assert task1.done.should.equal(false); task2.done.should.equal(false); done(); }); it('should not set done = false if done does not exist', function(done) { var orchestrator, task1, task2; // Arrange task1 = { name: 'test1', fn: function() {} // no done }; task2 = { name: 'test2', fn: function() {} // no done }; // the thing under test orchestrator = new Orchestrator(); orchestrator.tasks = { test1: task1, test2: task2 }; // Act orchestrator._resetSpecificTasks(['test1','test2']); // Assert should.not.exist(task1.done); should.not.exist(task2.done); done(); }); it('should set done = false on done dependency', function(done) { var orchestrator, task, dep; // Arrange task = { name: 'test', dep: ['dep'], fn: function() {} // no done though irrelevant to current test }; dep = { name: 'dep', fn: function() {}, done: true }; // the thing under test orchestrator = new Orchestrator(); orchestrator.tasks = { test: task, dep: dep }; // Act orchestrator._resetSpecificTasks(['test']); // Assert dep.done.should.equal(false); done(); }); it('should not set done on irrelevant tasks', function(done) { var orchestrator, task, irrelevant; // Arrange task = { name: 'test', fn: function() {} // no done though irrelevant to current test }; irrelevant = { name: 'irrelevant', fn: function() {}, done: true }; // the thing under test orchestrator = new Orchestrator(); orchestrator.tasks = { test: task, irrelevant: irrelevant }; // Act orchestrator._resetSpecificTasks(['test']); // Assert irrelevant.done.should.equal(true); done(); }); it('should not die if dependency does not exist', function(done) { var orchestrator, task; // Arrange task = { name: 'test', dep: ['dep'], // dep doesn't exist fn: function() {} // no done though irrelevant to current test }; // the thing under test orchestrator = new Orchestrator(); orchestrator.tasks = { test: task }; // Act orchestrator._resetSpecificTasks(['test']); // Assert // we're still here so it worked done(); }); }); });
"use strict"; require("requirish")._(module); var factories = require("lib/misc/factories"); // OPC Unified Architecture, Part 4 page 106 var ApplicationInstanceCertificate_Schema = { // ApplicationInstanceCertificate with signature created by a Certificate Authority name: "ApplicationInstanceCertificate", id: factories.next_available_id(), fields: [ // An identifier for the version of the Certificate encoding. { name: "version", fieldType: "String" }, // A unique identifier for the Certificate assigned by the Issuer. { name: "serialNumber", fieldType: "ByteString" }, // The algorithm used to sign the Certificate . // The syntax of this field depends on the Certificate encoding. { name: "signatureAlgorithm", fieldType: "String" }, // The signature created by the Issuer. { name: "signature", fieldType: "ByteString" }, // A name that identifies the Issuer Certificate used to create the signature. { name: "issuer", fieldType: "String" }, // When the Certificate becomes valid. { name: "validFrom", fieldType: "UtcTime" }, // When the Certificate expires. { name: "validTo", fieldType: "UtcTime" }, // A name that identifies the application instance that the Certificate describes. // This field shall contain the productName and the name of the organization // responsible for the application instance. { name: "subject", fieldType: "String" }, // The applicationUri specified in the ApplicationDescription . // The ApplicationDescription is described in 7.1. { name: "applicationUri", fieldType: "String" }, // The name of the machine where the application instance runs. // A machine may have multiple names if is accessible via multiple networks. // The hostname may be a numeric network address or a descriptive name. // Server Certificates shall have at least one hostname defined. { name: "hostnames", isArray: true, fieldType: "String" }, // The public key associated with the Certificate . { name: "publicKey", fieldType: "ByteString" }, // Specifies how the Certificate key may be used. // ApplicationInstanceCertificates shall support Digital Signature, Non-Repudiation // Key Encryption, Data Encryption and Client/Server Authorization. // The contents of this field depend on the Certificate enco { name: "keyUsage", fieldType: "String" } ] }; exports.ApplicationInstanceCertificate_Schema = ApplicationInstanceCertificate_Schema;
'use strict'; export default { browserPort: 3000, UIPort: 3001, testPort: 3002, sourceDir: './app/', buildDir: './build/', styles: { src: 'app/styles/**/*.scss', dest: 'build/css', prodSourcemap: false, sassIncludePaths: [] }, scripts: { src: 'app/js/**/*.js', dest: 'build/js', test: 'test/**/*.js', gulp: 'gulp/**/*.js' }, images: { src: 'app/images/**/*', dest: 'build/images' }, fonts: { src: ['app/fonts/**/*'], dest: 'build/fonts' }, assetExtensions: [ 'js', 'css', 'png', 'jpe?g', 'gif', 'svg', 'eot', 'otf', 'ttc', 'ttf', 'woff2?' ], views: { index: 'app/index.html', src: 'app/views/**/*.html', dest: 'app/js' }, gzip: { src: 'build/**/*.{html,xml,json,css,js,js.map,css.map}', dest: 'build/', options: {} }, browserify: { bundleName: 'main.js', prodSourcemap: false }, test: { karma: 'test/karma.conf.js', protractor: 'test/protractor.conf.js' }, init: function() { this.views.watch = [ this.views.index, this.views.src ]; return this; } }.init();
import ejs from 'ejs' import fs from 'fs' import mkdirp from 'mkdirp' /** * @class */ export default class BaseCommand { /** * @param {String} source * @param {String} destination */ copyFile(source, destination) { fs.createReadStream(source).pipe(fs.createWriteStream(destination)); this.logEntryCreatedEvent(destination); } /** * @param {String} path */ createDirectory(path) { mkdirp.sync(path); this.logEntryCreatedEvent(path); } /** * @param {String} path */ createEmptyFile(path) { fs.closeSync(fs.openSync(path, 'w')); this.logEntryCreatedEvent(path); } /** * @param {String} data * @param {String} path */ createFile(path, data) { fs.writeFileSync(path, data); this.logEntryCreatedEvent(path); } /** * @param {String} destination * @param {Object=} parameters * @param {String} source */ createFileFromTemplate({ destination, parameters, source }) { this.createFile( destination, ejs.render( fs.readFileSync( source, { encoding: 'utf8' } ), parameters || {} ) ); } /** * @param {String} path */ logEntryCreatedEvent(path) { console.log(`Created ${path}`); } }
'use strict'; var fs = require('fs'); var visitors = require('react-tools/vendor/fbtransform/visitors'); var jstransform = require('jstransform'); var visitorList = visitors.getAllVisitors(); var getJsName = function(filename) { var dot = filename.lastIndexOf("."); var baseName = filename.substring(0, dot); return baseName + ".js"; } // perform es6 / jsx tranforms on all files and simultaneously copy them to the // top level. var files = fs.readdirSync('js'); for (var i = 0; i < files.length; i++) { var src = 'js/' + files[i]; var dest = getJsName(files[i]); var js = fs.readFileSync(src, {encoding: 'utf8'}); var transformed = jstransform.transform(visitorList, js).code; transformed = transformed.replace('.jsx', '.js'); fs.writeFileSync(dest, transformed); }
DataExplorer.TableHelpers = (function () { var tables, infoTemplate = document.create('i', { className: 'icon-info button table-data', title: 'show the contents of this table' }), closeTemplate = document.create('i', { className: 'icon-remove button table-data-close', title: 'hide the contents of this table' }), dataTemplate = document.create('div', { className: 'table-data-panel hidden' }); dataTemplate.appendChild(document.create('span', { className: 'schema-table' })); dataTemplate.appendChild((function () { var wrapper = document.create('div', { className: 'table-data-wrapper' }), table = document.createElement('table'), tableHead = document.createElement('thead'), tableBody = document.createElement('tbody'); wrapper.appendChild(table); table.appendChild(tableHead); table.appendChild(tableBody); tableHead.appendChild(document.createElement('tr')); tableBody.appendChild(document.createElement('tr')); return wrapper; })()); function init(tableData) { var schema = document.getElementById('schema'); tables = tableData; $('ul .schema-table', schema).each(function () { var tableName = this[_textContent], data = tables[tableName.toCamelCase()]; if (data) { var infoIcon = infoTemplate.cloneNode(true), closeIcon = closeTemplate.cloneNode(true), panel = dataTemplate.cloneNode(true), $panel = $(panel); this.appendChild(infoIcon); panel.children[0][_textContent] = tableName; panel.children[0].appendChild(closeIcon); $(closeIcon).click(function () { $panel.hide(); }); var table = panel.getElementsByTagName('table')[0], tableBody = table.children[1], header = table.children[0].children[0], record = tableBody.children[0]; tableBody.removeChild(record); for (var i = 0; i < data.columns.length; ++i) { header.appendChild(document.create('th', { text: data.columns[i].name })); record.appendChild(document.create('td', { className: data.columns[i].type.toLowerCase() })); } for (var i = 0; i < data.rows.length; ++i) { var row = record.cloneNode(true); for (var c = 0; c < data.columns.length; ++c) { row.children[c][_textContent] = data.rows[i][c]; } tableBody.appendChild(row); } schema.insertBefore(panel, schema.children[0]); $(infoIcon).click(function () { $panel.show(); return false; }); } }); } // This is terrible, because it requires the outside code to // account for the header height...will fix later function resize(height) { // Could store references directly to the wrapper, too... $('#schema .table-data-wrapper').css({ height: height + 'px' }); } return { 'init': init, 'resize': resize }; })();
import Ember from 'ember'; const { Route } = Ember; export default Route.extend({ breadCrumb: { title: 'I am Bar Index' } });
version https://git-lfs.github.com/spec/v1 oid sha256:38067ac6e74cbe55f1203dde50a9f85f7f90b6bfe09e94ea11ccf8a3d31fe6a2 size 713
/** * The Studio: Artist of the Day plugin * This is a daily activity where users nominate the featured artist for the day, which is selected randomly once voting has ended. * Only works in a room with the id 'thestudio' */ 'use strict'; function toArrayOfArrays(map) { let ret = []; map.forEach(function (value, key) { ret.push([value, key]); }); return ret; } function toArtistId(artist) { // toId would return '' for foreign/sadistic artists return artist.toLowerCase().replace(/\s/g, '').replace(/\b&\b/g, ''); } let artistOfTheDay = { pendingNominations: false, nominations: new Map(), removedNominators: [], }; let theStudio = Rooms.get('thestudio'); if (theStudio && !theStudio.plugin) { theStudio.plugin = artistOfTheDay; } let commands = { start: function (target, room, user) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!room.chatRoomData || !this.can('mute', null, room)) return false; if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are already in progress."); let nominations = artistOfTheDay.nominations; let prenominations = room.chatRoomData.prenominations; if (prenominations && prenominations.length) { for (let i = 0; i < prenominations.length; i++) { let prenomination = prenominations[i]; nominations.set(Users.get(prenomination[0].userid) || prenomination[0], prenomination[1]); } } artistOfTheDay.pendingNominations = true; room.chatRoomData.prenominations = []; Rooms.global.writeChatRoomData(); room.addRaw( "<div class=\"broadcast-blue\"><strong>Nominations for the Artist of the Day have begun!</strong><br />" + "Use /aotd nom to nominate an artist.</div>" ); this.privateModCommand("(" + user.name + " began nominations for the Artist of the Day.)"); }, starthelp: ["/aotd start - Start nominations for the Artist of the Day. Requires: % @ # & ~"], end: function (target, room, user) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!room.chatRoomData || !this.can('mute', null, room)) return false; if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are not in progress."); if (!artistOfTheDay.nominations.size) return this.sendReply("No nominations have been submitted yet."); let nominations = toArrayOfArrays(artistOfTheDay.nominations); let artist = nominations[~~(Math.random() * nominations.length)][0]; artistOfTheDay.pendingNominations = false; artistOfTheDay.nominations.clear(); artistOfTheDay.removedNominators = []; room.chatRoomData.artistOfTheDay = artist; Rooms.global.writeChatRoomData(); room.addRaw( "<div class=\"broadcast-blue\"><strong>Nominations for the Artist of the Day have ended!</strong><br />" + "Randomly selected artist: " + Tools.escapeHTML(artist) + "</div>" ); this.privateModCommand("(" + user.name + " ended nominations for the Artist of the Day.)"); }, endhelp: ["/aotd end - End nominations for the Artist of the Day and set it to a randomly selected artist. Requires: % @ # & ~"], prenom: function (target, room, user) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!target) this.parse('/help aotd prenom'); if (!room.chatRoomData || !target) return false; if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are in progress."); if (!room.chatRoomData.prenominations) room.chatRoomData.prenominations = []; let userid = user.userid; let prenominationId = toArtistId(target); if (!prenominationId) return this.sendReply("" + target + " is not a valid artist name."); if (room.chatRoomData.artistOfTheDay && toArtistId(room.chatRoomData.artistOfTheDay) === prenominationId) return this.sendReply("" + target + " is already the current Artist of the Day."); let prenominations = room.chatRoomData.prenominations; let prenominationIndex = -1; let latestIp = user.latestIp; for (let i = 0; i < prenominations.length; i++) { if (toArtistId(prenominations[i][1]) === prenominationId) return this.sendReply("" + target + " has already been prenominated."); if (prenominationIndex < 0) { let prenominator = prenominations[i][0]; if (prenominator.userid === userid || prenominator.ips[latestIp]) { prenominationIndex = i; break; } } } if (prenominationIndex >= 0) { prenominations[prenominationIndex][1] = target; Rooms.global.writeChatRoomData(); return this.sendReply("Your prenomination was changed to " + target + "."); } prenominations.push([{name: user.name, userid: userid, ips: user.ips}, target]); Rooms.global.writeChatRoomData(); this.sendReply("" + target + " was submitted for the next nomination period for the Artist of the Day."); }, prenomhelp: ["/aotd prenom [artist] - Nominate an artist for the Artist of the Day between nomination periods."], nom: function (target, room, user) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!target) this.parse('/help aotd nom'); if (!room.chatRoomData || !target) return false; if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are not in progress."); let removedNominators = artistOfTheDay.removedNominators; if (removedNominators.indexOf(user) >= 0) return this.sendReply("Since your nomination has been removed, you cannot submit another artist until the next round."); let alts = user.getAlts(); for (let i = 0; i < removedNominators.length; i++) { if (alts.indexOf(removedNominators[i].name) >= 0) return this.sendReply("Since your nomination has been removed, you cannot submit another artist until the next round."); } let nominationId = toArtistId(target); if (room.chatRoomData.artistOfTheDay && toArtistId(room.chatRoomData.artistOfTheDay) === nominationId) return this.sendReply("" + target + " was the last Artist of the Day."); let userid = user.userid; let latestIp = user.latestIp; for (let data, nominationsIterator = artistOfTheDay.nominations.entries(); !!(data = nominationsIterator.next().value);) { // replace with for-of loop once available let nominator = data[0]; if (nominator.ips[latestIp] && nominator.userid !== userid || alts.indexOf(nominator.name) >= 0) return this.sendReply("You have already submitted a nomination for the Artist of the Day under the name " + nominator.name + "."); if (toArtistId(data[1]) === nominationId) return this.sendReply("" + target + " has already been nominated."); } let response = "" + user.name + (artistOfTheDay.nominations.has(user) ? " changed their nomination from " + artistOfTheDay.nominations.get(user) + " to " + target + "." : " nominated " + target + " for the Artist of the Day."); artistOfTheDay.nominations.set(user, target); room.add(response); }, nomhelp: ["/aotd nom [artist] - Nominate an artist for the Artist of the Day."], viewnoms: function (target, room, user) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!room.chatRoomData) return false; let buffer = ""; if (!artistOfTheDay.pendingNominations) { if (!user.can('mute', null, room)) return false; let prenominations = room.chatRoomData.prenominations; if (!prenominations || !prenominations.length) return this.sendReplyBox("No prenominations have been submitted yet."); prenominations = prenominations.sort(function (a, b) { if (a[1] > b[1]) return 1; if (a[1] < b[1]) return -1; return 0; }); buffer += "Current prenominations: (" + prenominations.length + ")"; for (let i = 0; i < prenominations.length; i++) { buffer += "<br />" + "- " + Tools.escapeHTML(prenominations[i][1]) + " (submitted by " + Tools.escapeHTML(prenominations[i][0].name) + ")"; } return this.sendReplyBox(buffer); } if (!this.canBroadcast()) return false; if (!artistOfTheDay.nominations.size) return this.sendReplyBox("No nominations have been submitted yet."); let nominations = toArrayOfArrays(artistOfTheDay.nominations).sort(function (a, b) {return a[0].localeCompare(b[0]);}); buffer += "Current nominations (" + nominations.length + "):"; for (let i = 0; i < nominations.length; i++) { buffer += "<br />" + "- " + Tools.escapeHTML(nominations[i][0]) + " (submitted by " + Tools.escapeHTML(nominations[i][1].name) + ")"; } this.sendReplyBox(buffer); }, viewnomshelp: ["/aotd viewnoms - View the current nominations for the Artist of the Day. Requires: % @ # & ~"], removenom: function (target, room, user) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!target) this.parse('/help aotd removenom'); if (!room.chatRoomData || !target || !this.can('mute', null, room)) return false; if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk."); if (!artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are not in progress."); if (!artistOfTheDay.nominations.size) return this.sendReply("No nominations have been submitted yet."); target = this.splitTarget(target); let name = this.targetUsername; let userid = toId(name); if (!userid) return this.errorReply("'" + name + "' is not a valid username."); for (let nominator, nominatorsIterator = artistOfTheDay.nominations.keys(); !!(nominator = nominatorsIterator.next().value);) { // replace with for-of loop once available if (nominator.userid === userid) { artistOfTheDay.nominations.delete(nominator); artistOfTheDay.removedNominators.push(nominator); return this.privateModCommand("(" + user.name + " removed " + nominator.name + "'s nomination for the Artist of the Day.)"); } } this.sendReply("User '" + name + "' has no nomination for the Artist of the Day."); }, removenomhelp: ["/aotd removenom [username] - Remove a user\'s nomination for the Artist of the Day and prevent them from voting again until the next round. Requires: % @ # & ~"], set: function (target, room, user) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!target) this.parse('/help aotd set'); if (!room.chatRoomData || !this.can('mute', null, room)) return false; if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.errorReply("You cannot do this while unable to talk."); if (!toId(target)) return this.errorReply("No valid artist was specified."); if (artistOfTheDay.pendingNominations) return this.sendReply("The Artist of the Day cannot be set while nominations are in progress."); room.chatRoomData.artistOfTheDay = target; Rooms.global.writeChatRoomData(); this.privateModCommand("(" + user.name + " set the Artist of the Day to " + target + ".)"); }, sethelp: ["/aotd set [artist] - Set the Artist of the Day. Requires: % @ # & ~"], quote: function (target, room, user) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!room.chatRoomData) return false; if (!target) { if (!this.canBroadcast()) return; if (!room.chatRoomData.artistQuoteOfTheDay) return this.sendReplyBox("The Artist Quote of the Day has not been set."); return this.sendReplyBox( "The current <strong>Artist Quote of the Day</strong> is:<br />" + "\"" + room.chatRoomData.artistQuoteOfTheDay + "\"" ); } if (!this.can('ban', null, room)) return false; if (target === 'off' || target === 'disable' || target === 'reset') { if (!room.chatRoomData.artistQuoteOfTheDay) return this.sendReply("The Artist Quote of the Day has already been reset."); delete room.chatRoomData.artistQuoteOfTheDay; this.sendReply("The Artist Quote of the Day was reset by " + Tools.escapeHTML(user.name) + "."); this.logModCommand(user.name + " reset the Artist Quote of the Day."); Rooms.global.writeChatRoomData(); return; } room.chatRoomData.artistQuoteOfTheDay = Tools.escapeHTML(target); Rooms.global.writeChatRoomData(); room.addRaw( "<div class=\"broadcast-blue\"><strong>The Artist Quote of the Day has been updated by " + Tools.escapeHTML(user.name) + ".</strong><br />" + "Quote: " + room.chatRoomData.artistQuoteOfTheDay + "</div>" ); this.logModCommand(Tools.escapeHTML(user.name) + " updated the artist quote of the day to \"" + room.chatRoomData.artistQuoteOfTheDay + "\"."); }, quotehelp: [ "/aotd quote - View the current Artist Quote of the Day.", "/aotd quote [quote] - Set the Artist Quote of the Day. Requires: # & ~", ], '': function (target, room) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!room.chatRoomData || !this.canBroadcast()) return false; this.sendReplyBox("The Artist of the Day " + (room.chatRoomData.artistOfTheDay ? "is " + room.chatRoomData.artistOfTheDay + "." : "has not been set yet.")); }, help: function (target, room) { if (room.id !== 'thestudio') return this.errorReply('This command can only be used in The Studio.'); if (!room.chatRoomData || !this.canBroadcast()) return false; this.sendReply("Use /help aotd to view help for all commands, or /help aotd [command] for help on a specific command."); }, }; exports.commands = { aotd: commands, aotdhelp: [ "The Studio: Artist of the Day plugin commands:", "- /aotd - View the Artist of the Day.", "- /aotd start - Start nominations for the Artist of the Day. Requires: % @ # & ~", "- /aotd nom [artist] - Nominate an artist for the Artist of the Day.", "- /aotd viewnoms - View the current nominations for the Artist of the Day. Requires: % @ # & ~", "- /aotd removenom [username] - Remove a user's nomination for the Artist of the Day and prevent them from voting again until the next round. Requires: % @ # & ~", "- /aotd end - End nominations for the Artist of the Day and set it to a randomly selected artist. Requires: % @ # & ~", "- /aotd prenom [artist] - Nominate an artist for the Artist of the Day between nomination periods.", "- /aotd set [artist] - Set the Artist of the Day. Requires: % @ # & ~", "- /aotd quote - View the current Artist Quote of the Day.", "- /aotd quote [quote] - Set the Artist Quote of the Day. Requires: # & ~", ], };
version https://git-lfs.github.com/spec/v1 oid sha256:63544f1ce0b192b27c8946c878c716ba60158e9fb1adf9375a57279a2fc15a1a size 2271
import Raphael from 'raphael/raphael'; Raphael.prototype.commitTooltip = function commitTooltip(x, y, commit) { const boxWidth = 300; const icon = this.image(gon.relative_url_root + commit.author.icon, x, y, 20, 20); const nameText = this.text(x + 25, y + 10, commit.author.name); const idText = this.text(x, y + 35, commit.id); const messageText = this.text(x, y + 50, commit.message.replace(/\r?\n/g, ' \n ')); const textSet = this.set(icon, nameText, idText, messageText).attr({ 'text-anchor': 'start', font: '12px Monaco, monospace', }); nameText.attr({ font: '14px Arial', 'font-weight': 'bold', }); idText.attr({ fill: '#AAA', }); messageText.node.style['white-space'] = 'pre'; this.textWrap(messageText, boxWidth - 50); const rect = this.rect(x - 10, y - 10, boxWidth, 100, 4).attr({ fill: '#FFF', stroke: '#000', 'stroke-linecap': 'round', 'stroke-width': 2, }); const tooltip = this.set(rect, textSet); rect.attr({ height: tooltip.getBBox().height + 10, width: tooltip.getBBox().width + 10, }); tooltip.transform(['t', 20, 20]); return tooltip; }; Raphael.prototype.textWrap = function testWrap(t, width) { const content = t.attr('text'); const abc = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; t.attr({ text: abc, }); const letterWidth = t.getBBox().width / abc.length; t.attr({ text: content, }); const words = content.split(' '); let x = 0; const s = []; for (let j = 0, len = words.length; j < len; j += 1) { const word = words[j]; if (x + word.length * letterWidth > width) { s.push('\n'); x = 0; } if (word === '\n') { s.push('\n'); x = 0; } else { s.push(`${word} `); x += word.length * letterWidth; } } t.attr({ text: s.join('').trim(), }); const b = t.getBBox(); const h = Math.abs(b.y2) + 1; return t.attr({ y: h, }); }; export default Raphael;
'use strict'; exports.__esModule = true; exports.default = function (hexColor, lightness) { var hex = String(hexColor).replace(/[^0-9a-f]/gi, ''); if (hex.length < 6) { hex = hex.replace(/(.)/g, '$1$1'); } var lum = lightness || 0; var rgb = '#'; var c = undefined; for (var i = 0; i < 3; ++i) { c = parseInt(hex.substr(i * 2, 2), 16); c = Math.round(Math.min(Math.max(0, c + c * lum), 255)).toString(16); rgb += ('00' + c).substr(c.length); } return rgb; };
module.exports={title:"RubyGems",slug:"rubygems",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>RubyGems</title><path d="'+this.path+'"/></svg>'},path:"M7.81 7.9l-2.97 2.95 7.19 7.18 2.96-2.95 4.22-4.23-2.96-2.96v-.01H7.8zM12 0L1.53 6v12L12 24l10.47-6V6L12 0zm8.47 16.85L12 21.73l-8.47-4.88V7.12L12 2.24l8.47 4.88v9.73z",source:"https://rubygems.org/pages/about",hex:"E9573F",guidelines:void 0,license:void 0};
function accepts(language) { return require('../')({ headers: { 'accept-language': language || '' } }) } describe('accepts.languages()', function(){ describe('with no arguments', function(){ describe('when Accept-Language is populated', function(){ it('should return accepted types', function(){ var accept = accepts('en;q=0.8, es, pt'); accept.languages().should.eql(['es', 'pt', 'en']); }) }) describe('when Accept-Language is not populated', function(){ it('should return an empty array', function(){ var accept = accepts(); accept.languages().should.eql([]); }) }) }) describe('with multiple arguments', function(){ describe('when Accept-Language is populated', function(){ describe('if any types types match', function(){ it('should return the best fit', function(){ var accept = accepts('en;q=0.8, es, pt'); accept.languages('es', 'en').should.equal('es'); }) }) describe('if no types match', function(){ it('should return false', function(){ var accept = accepts('en;q=0.8, es, pt'); accept.languages('fr', 'au').should.be.false; }) }) }) describe('when Accept-Language is not populated', function(){ it('should return the first type', function(){ var accept = accepts(); accept.languages('es', 'en').should.equal('es'); }) }) }) describe('with an array', function(){ it('should return the best fit', function(){ var accept = accepts('en;q=0.8, es, pt'); accept.languages(['es', 'en']).should.equal('es'); }) }) })
/* mustache.js — Logic-less templates in JavaScript See http://mustache.github.com/ for more info. */ var Mustache = function() { var Renderer = function() {}; Renderer.prototype = { otag: "{{", ctag: "}}", pragmas: {}, buffer: [], pragmas_implemented: { "IMPLICIT-ITERATOR": true }, render: function(template, context, partials, in_recursion) { // fail fast if(template.indexOf(this.otag) == -1) { if(in_recursion) { return template; } else { this.send(template); return; } } if(!in_recursion) { this.buffer = []; } template = this.render_pragmas(template); var html = this.render_section(template, context, partials); if(in_recursion) { return this.render_tags(html, context, partials, in_recursion); } this.render_tags(html, context, partials, in_recursion); }, /* Sends parsed lines */ send: function(line) { if(line != "") { this.buffer.push(line); } }, /* Looks for %PRAGMAS */ render_pragmas: function(template) { // no pragmas if(template.indexOf(this.otag + "%") == -1) { return template; } var that = this; var regex = new RegExp(this.otag + "%([\\w_-]+) ?([\\w]+=[\\w]+)?" + this.ctag); return template.replace(regex, function(match, pragma, options) { if(!that.pragmas_implemented[pragma]) { throw({message: "This implementation of mustache doesn't understand the '" + pragma + "' pragma"}); } that.pragmas[pragma] = {}; if(options) { var opts = options.split("="); that.pragmas[pragma][opts[0]] = opts[1]; } return ""; // ignore unknown pragmas silently }); }, /* Tries to find a partial in the global scope and render it */ render_partial: function(name, context, partials) { if(!partials || !partials[name]) { throw({message: "unknown_partial '" + name + "'"}); } if(typeof(context[name]) != "object") { return partials[name]; } return this.render(partials[name], context[name], partials, true); }, /* Renders boolean and enumerable sections */ render_section: function(template, context, partials) { if(template.indexOf(this.otag + "#") == -1) { return template; } var that = this; // CSW - Added "+?" so it finds the tighest bound, not the widest var regex = new RegExp(this.otag + "\\#(.+)" + this.ctag + "\\s*([\\s\\S]+?)" + this.otag + "\\/\\1" + this.ctag + "\\s*", "mg"); // for each {{#foo}}{{/foo}} section do... return template.replace(regex, function(match, name, content) { var value = that.find(name, context); if(that.is_array(value)) { // Enumerable, Let's loop! return that.map(value, function(row) { return that.render(content, that.merge(context, that.create_context(row)), partials, true); }).join(""); } else if(value) { // boolean section return that.render(content, context, partials, true); } else { return ""; } }); }, /* Replace {{foo}} and friends with values from our view */ render_tags: function(template, context, partials, in_recursion) { // tit for tat var that = this; var new_regex = function() { return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\/#]+?)\\1?" + that.ctag + "+", "g"); }; var regex = new_regex(); var lines = template.split("\n"); for (var i=0; i < lines.length; i++) { lines[i] = lines[i].replace(regex, function(match, operator, name) { switch(operator) { case "!": // ignore comments return match; case "=": // set new delimiters, rebuild the replace regexp that.set_delimiters(name); regex = new_regex(); return ""; case ">": // render partial return that.render_partial(name, context, partials); case "{": // the triple mustache is unescaped return that.find(name, context); default: // escape the value return that.escape(that.find(name, context)); } }, this); if(!in_recursion) { this.send(lines[i]); } } if(in_recursion) { return lines.join("\n"); } }, set_delimiters: function(delimiters) { var dels = delimiters.split(" "); this.otag = this.escape_regex(dels[0]); this.ctag = this.escape_regex(dels[1]); }, escape_regex: function(text) { // thank you Simon Willison if(!arguments.callee.sRE) { var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; arguments.callee.sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' ); } return text.replace(arguments.callee.sRE, '\\$1'); }, /* find `name` in current `context`. That is find me a value from the view object */ find: function(name, context) { name = this.trim(name); if(typeof context[name] === "function") { return context[name].apply(context); } if(context[name] !== undefined) { return context[name]; } // silently ignore unkown variables return ""; }, // Utility methods /* Does away with nasty characters */ escape: function(s) { return ((s == null) ? "" : s).toString().replace(/[&"<>\\]/g, function(s) { switch(s) { case "&": return "&amp;"; case "\\": return "\\\\";; case '"': return '\"';; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); }, /* Merges all properties of object `b` into object `a`. `b.property` overwrites a.property` */ merge: function(a, b) { var _new = {}; for(var name in a) { if(a.hasOwnProperty(name)) { _new[name] = a[name]; } }; for(var name in b) { if(b.hasOwnProperty(name)) { _new[name] = b[name]; } }; return _new; }, // by @langalex, support for arrays of strings create_context: function(_context) { if(this.is_object(_context)) { return _context; } else if(this.pragmas["IMPLICIT-ITERATOR"]) { var iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator || "."; var ctx = {}; ctx[iterator] = _context; return ctx; } }, is_object: function(a) { return a && typeof a == "object"; }, is_array: function(a) { return Object.prototype.toString.call(a) === '[object Array]'; }, /* Gets rid of leading and trailing whitespace */ trim: function(s) { return s.replace(/^\s*|\s*$/g, ""); }, /* Why, why, why? Because IE. Cry, cry cry. */ map: function(array, fn) { if (typeof array.map == "function") { return array.map(fn); } else { var r = []; var l = array.length; for(var i=0;i<l;i++) { r.push(fn(array[i])); } return r; } } }; return({ name: "mustache.js", version: "0.2.3", /* Turns a template and view into HTML */ to_html: function(template, view, partials, send_fun) { var renderer = new Renderer(); if(send_fun) { renderer.send = send_fun; } renderer.render(template, view, partials); if(!send_fun) { return renderer.buffer.join("\n"); } } }); }();
import {localeModule, test} from '../qunit'; import moment from '../../moment'; localeModule('de'); test('parse', function (assert) { var tests = 'Januar Jan._Februar Feb._März März_April Apr._Mai Mai_Juni Juni_Juli Juli_August Aug._September Sep._Oktober Okt._November Nov._Dezember Dez.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'Sonntag, 14. Februar 2010, 3:25:50 pm'], ['ddd, hA', 'So., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 Februar Feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. Sonntag So. So'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14. Februar 2010'], ['LLL', '14. Februar 2010 15:25'], ['LLLL', 'Sonntag, 14. Februar 2010 15:25'], ['l', '14.2.2010'], ['ll', '14. Feb. 2010'], ['lll', '14. Feb. 2010 15:25'], ['llll', 'So., 14. Feb. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'Januar Jan._Februar Feb._März März_April Apr._Mai Mai_Juni Juni_Juli Juli_August Aug._September Sep._Oktober Okt._November Nov._Dezember Dez.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sonntag So. So_Montag Mo. Mo_Dienstag Di. Di_Mittwoch Mi. Mi_Donnerstag Do. Do_Freitag Fr. Fr_Samstag Sa. Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'ein paar Sekunden', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'eine Minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'eine Minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 Minuten', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 Minuten', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'eine Stunde', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'eine Stunde', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 Stunden', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 Stunden', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 Stunden', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ein Tag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ein Tag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 Tage', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ein Tag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 Tage', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 Tage', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ein Monat', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ein Monat', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ein Monat', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 Monate', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 Monate', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 Monate', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ein Monat', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 Monate', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ein Jahr', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 Jahre', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ein Jahr', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 Jahre', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in ein paar Sekunden', 'prefix'); assert.equal(moment(0).from(30000), 'vor ein paar Sekunden', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in ein paar Sekunden', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'in 5 Tagen', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'heute um 12:00 Uhr', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'heute um 12:25 Uhr', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'heute um 13:00 Uhr', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'morgen um 12:00 Uhr', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'heute um 11:00 Uhr', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'gestern um 12:00 Uhr', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [um] LT [Uhr]'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [um] LT [Uhr]'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [um] LT [Uhr]'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[letzten] dddd [um] LT [Uhr]'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[letzten] dddd [um] LT [Uhr]'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[letzten] dddd [um] LT [Uhr]'), 'Today + ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); });
/** * @param {string} value * @returns {RegExp} * */ /** * @param {RegExp | string } re * @returns {string} */ function source(re) { if (!re) return null; if (typeof re === "string") return re; return re.source; } /** * @param {...(RegExp | string) } args * @returns {string} */ function concat(...args) { const joined = args.map((x) => source(x)).join(""); return joined; } /** * Any of the passed expresssions may match * * Creates a huge this | this | that | that match * @param {(RegExp | string)[] } args * @returns {string} */ function either(...args) { const joined = '(' + args.map((x) => source(x)).join("|") + ")"; return joined; } /* Language: Apache Access Log Author: Oleg Efimov <efimovov@gmail.com> Description: Apache/Nginx Access Logs Website: https://httpd.apache.org/docs/2.4/logs.html#accesslog Audit: 2020 */ /** @type LanguageFn */ function accesslog(_hljs) { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods const HTTP_VERBS = [ "GET", "POST", "HEAD", "PUT", "DELETE", "CONNECT", "OPTIONS", "PATCH", "TRACE" ]; return { name: 'Apache Access Log', contains: [ // IP { className: 'number', begin: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?\b/, relevance: 5 }, // Other numbers { className: 'number', begin: /\b\d+\b/, relevance: 0 }, // Requests { className: 'string', begin: concat(/"/, either(...HTTP_VERBS)), end: /"/, keywords: HTTP_VERBS, illegal: /\n/, relevance: 5, contains: [ { begin: /HTTP\/[12]\.\d'/, relevance: 5 } ] }, // Dates { className: 'string', // dates must have a certain length, this prevents matching // simple array accesses a[123] and [] and other common patterns // found in other languages begin: /\[\d[^\]\n]{8,}\]/, illegal: /\n/, relevance: 1 }, { className: 'string', begin: /\[/, end: /\]/, illegal: /\n/, relevance: 0 }, // User agent / relevance boost { className: 'string', begin: /"Mozilla\/\d\.\d \(/, end: /"/, illegal: /\n/, relevance: 3 }, // Strings { className: 'string', begin: /"/, end: /"/, illegal: /\n/, relevance: 0 } ] }; } module.exports = accesslog;
/* Inspire Tree * @version 6.0.0-alpha.1 * https://github.com/helion3/inspire-tree * @copyright Copyright 2015 Helion3, and other contributors * @license Licensed under MIT * see https://github.com/helion3/inspire-tree/blob/master/LICENSE */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('lodash')) : typeof define === 'function' && define.amd ? define(['lodash'], factory) : (global.InspireTree = factory(global._)); }(this, (function (_) { 'use strict'; 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; } var rngBrowser = createCommonjsModule(function (module) { // Unique ID creation requires a high quality random # generator. In the // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via // feature-detection // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) || (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto)); if (getRandomValues) { // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef module.exports = function whatwgRNG() { getRandomValues(rnds8); return rnds8; }; } else { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var rnds = new Array(16); module.exports = function mathRNG() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return rnds; }; } }); /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; } var bytesToUuid_1 = bytesToUuid; function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rngBrowser)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid_1(rnds); } var v4_1 = v4; /** * Reset a node's state to the tree default. * * @private * @param {TreeNode} node Node object. * @returns {TreeNode} Node object. */ function resetState(node) { _.each(node._tree.defaultState, function (val, prop) { node.state(prop, val); }); return node; } /** * Stores repetitive state change logic for most state methods. * * @private * @param {string} prop State property name. * @param {boolean} value New state value. * @param {string} verb Verb used for events. * @param {TreeNode} node Node object. * @param {string} deep Optional name of state method to call recursively. * @return {TreeNode} Node object. */ function baseStateChange(prop, value, verb, node, deep) { if (node.state(prop) !== value) { node.context().batch(); if (node._tree.config.nodes.resetStateOnRestore && verb === 'restored') { resetState(node); } // indeterminate may never be true if checked is if (value && prop === 'checked') { node.state('indeterminate', false); } node.state(prop, value); node._tree.emit('node.' + verb, node, false); if (deep && node.hasChildren()) { node.children.recurseDown(function (child) { baseStateChange(prop, value, verb, child); }); } // This node's "renderability" has changed, so we should // trigger a re-cache in the parent context. if (prop === 'hidden' || prop === 'removed') { node.context().indicesDirty = true; node.context().calculateRenderablePositions(); } node.markDirty(); node.context().end(); } return node; } 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 v4.2.2+97478eb6 */ (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 = void 0; 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 = void 0; var customSchedulerFn = void 0; 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 process.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 = void 0; // 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 parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { 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 = void 0, callback = void 0, 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 = void 0, error = void 0, succeeded = void 0, failed = void 0; 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 validationError() { return new Error('Array Methods must be provided an Array'); } function validationError() { return new Error('Array Methods must be provided an Array'); } var Enumerator = function () { function Enumerator(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()); } } Enumerator.prototype._enumerate = function _enumerate(input) { for (var i = 0; this._state === PENDING && i < input.length; i++) { this._eachEntry(input[i], i); } }; Enumerator.prototype._eachEntry = function _eachEntry(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$1) { 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.prototype._settledAt = function _settledAt(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.prototype._willSettleAt = function _willSettleAt(promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; return Enumerator; }(); /** `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(entries) { return new Enumerator(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(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_$$1, 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 */ var Promise$1 = function () { function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } /** 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} */ /** `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} */ Promise.prototype.catch = function _catch(onRejection) { return this.then(null, onRejection); }; /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves Synchronous example: ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuther(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuther(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @return {Promise} */ Promise.prototype.finally = function _finally(callback) { var promise = this; var constructor = promise.constructor; return promise.then(function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { throw reason; }); }); }; return Promise; }(); Promise$1.prototype.then = then; Promise$1.all = all; Promise$1.race = race; Promise$1.resolve = resolve$1; Promise$1.reject = reject$1; Promise$1._setScheduler = setScheduler; Promise$1._setAsap = setAsap; Promise$1._asap = asap; /*global self*/ function polyfill() { var local = void 0; 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$1; } // Strange compat.. Promise$1.polyfill = polyfill; Promise$1.Promise = Promise$1; return Promise$1; }))); }); var es6Promise_1 = es6Promise.Promise; 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 get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; 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 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 toArray = function (arr) { return Array.isArray(arr) ? arr : Array.from(arr); }; function _extendableBuiltin(cls) { function ExtendableBuiltin() { cls.apply(this, arguments); } ExtendableBuiltin.prototype = Object.create(cls.prototype, { constructor: { value: cls, enumerable: false, writable: true, configurable: true } }); if (Object.setPrototypeOf) { Object.setPrototypeOf(ExtendableBuiltin, cls); } else { ExtendableBuiltin.__proto__ = cls; } return ExtendableBuiltin; } /** * Base function to filter nodes by state value. * * @private * @param {string} state State property * @param {boolean} full Return a non-flat hierarchy * @return {TreeNodes} Array of matching nodes. */ function baseStatePredicate(state, full) { if (full) { return this.extract(state); } // Cache a state predicate function var fn = getPredicateFunction(state); return this.flatten(function (node) { // Never include removed nodes unless specifically requested if (state !== 'removed' && node.removed()) { return false; } return fn(node); }); } /** * Base function to invoke given method(s) on tree nodes. * * @private * @param {TreeNode} nodes Array of node objects. * @param {string|array} methods Method names. * @param {array|Arguments} args Array of arguments to proxy. * @param {boolean} deep Invoke deeply. * @return {TreeNodes} Array of node objects. */ function baseInvoke(nodes, methods, args, deep) { methods = _.castArray(methods); nodes._tree.batch(); nodes[deep ? 'recurseDown' : 'each'](function (node) { _.each(methods, function (method) { if (_.isFunction(node[method])) { node[method].apply(node, args); } }); }); nodes._tree.end(); return nodes; } /** * Creates a predicate function. * * @private * @param {string|function} predicate Property name or custom function. * @return {function} Predicate function. */ function getPredicateFunction(predicate) { var fn = predicate; if (_.isString(predicate)) { fn = function fn(node) { return _.isFunction(node[predicate]) ? node[predicate]() : node[predicate]; }; } return fn; } /** * An Array-like collection of TreeNodes. * * Note: Due to issue in many javascript environments, * native objects are problematic to extend correctly * so we mimic it, not actually extend it. * * @param {InspireTree} tree Context tree. * @param {array} array Array of TreeNode objects. * @param {object} opts Configuration object. * @return {TreeNodes} Collection of TreeNode */ var TreeNodes = function (_extendableBuiltin2) { inherits(TreeNodes, _extendableBuiltin2); function TreeNodes(tree, array, opts) { classCallCheck(this, TreeNodes); var _this = possibleConstructorReturn(this, (TreeNodes.__proto__ || Object.getPrototypeOf(TreeNodes)).call(this)); if (_.isFunction(_.get(tree, 'isTree')) && !tree.isTree(tree)) { throw new TypeError('Invalid tree instance.'); } _this._tree = tree; _this.length = 0; _this.batching = 0; // A custom dirty flag to indicate when an index-altering // change has occured. Avoids re-caching when unnecessary. _this.indicesDirty = false; _this.config = _.defaultsDeep({}, opts, { calculateRenderablePositions: false }); // Init pagination _this._pagination = { limit: tree.config.pagination.limit, total: 0 }; if (_.isArray(array) || array instanceof TreeNodes) { _.each(array, function (node) { if (node instanceof TreeNode) { _this.push(node.clone()); } else { _this.addNode(node); } }); } return _this; } /** * Adds a new node. If a sort method is configured, * the node will be added in the appropriate order. * * @param {object} object Node * @return {TreeNode} Node object. */ createClass(TreeNodes, [{ key: 'addNode', value: function addNode(object) { // Base insertion index var index = this.length; // If tree is sorted, insert in correct position if (this._tree.config.sort) { index = _.sortedIndexBy(this, object, this._tree.config.sort); } return this.insertAt(index, object); } /** * Release pending data changes to any listeners. * * Will skip rendering as long as any calls * to `batch` have yet to be resolved, * * @private * @return {void} */ }, { key: 'applyChanges', value: function applyChanges() { if (this.batching === 0) { this.calculateRenderablePositions(); this._tree.emit('changes.applied', this.context()); } } /** * Batch multiple changes for listeners (i.e. DOM) * * @private * @return {void} */ }, { key: 'batch', value: function batch() { if (this.batching < 0) { this.batching = 0; } this.batching++; } /** * Query for all available nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'available', value: function available(full) { return baseStatePredicate.call(this, 'available', full); } /** * Blur nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'blur', value: function blur() { return this.invoke('blur'); } /** * Blur (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'blurDeep', value: function blurDeep() { return this.invokeDeep('blur'); } /** * Calculate and cache the first/last renderable nodes. * * Primarily useful for rendering engines, since hidden DOM * nodes may still be present and CSS :first/:last selectors * would fail. * * @private * @return {void} */ }, { key: 'calculateRenderablePositions', value: function calculateRenderablePositions() { if (!this.indicesDirty || this.batching > 0 || !this.config.calculateRenderablePositions) { return; } var first = void 0, last = void 0; this.each(function (node) { if (node.renderable()) { // Cache first node if none yet first = first || node; // Always update last node on match last = node; } }); if (this.firstRenderableNode && this.firstRenderableNode !== first) { this.firstRenderableNode.markDirty(); } if (first && first !== this.firstRenderableNode) { first.markDirty(); } if (this.lastRenderableNode && this.lastRenderableNode !== last) { this.lastRenderableNode.markDirty(); } if (last && last !== this.lastRenderableNode) { last.markDirty(); } this.firstRenderableNode = first; this.lastRenderableNode = last; this.indicesDirty = false; } /** * Query for all checked nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'checked', value: function checked(full) { return baseStatePredicate.call(this, 'checked', full); } /** * Clean nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'clean', value: function clean() { return this.invoke('clean'); } /** * Clones (deeply) the array of nodes. * * Note: Cloning will *not* clone the context pointer. * * @return {TreeNodes} Array of cloned nodes. */ }, { key: 'clone', value: function clone() { return new TreeNodes(this._tree, this); } /** * Collapse nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'collapse', value: function collapse() { return this.invoke('collapse'); } /** * Query for all collapsed nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'collapsed', value: function collapsed(full) { return baseStatePredicate.call(this, 'collapsed', full); } /** * Collapse (deeply) all children. * * @return {TreeNodes} Array of node objects. */ }, { key: 'collapseDeep', value: function collapseDeep() { return this.invokeDeep('collapse'); } /** * Concat multiple TreeNodes arrays. * * @param {TreeNodes} nodes Array of nodes. * @return {TreeNodes} Resulting node array. */ }, { key: 'concat', value: function concat(nodes) { var newNodes = new TreeNodes(this._tree); newNodes._context = this._context; var pusher = function pusher(node) { if (node instanceof TreeNode) { newNodes.push(node); } }; _.each(this, pusher); _.each(nodes, pusher); // Copy pagination limit newNodes._pagination.limit = this._pagination.limit; return newNodes; } /** * Get the context of this collection. If a collection * of children, context is the parent node. Otherwise * the context is the tree itself. * * @return {TreeNode|object} Node object or tree instance. */ }, { key: 'context', value: function context() { return this._context || this._tree; } /** * Copy nodes to another tree instance. * * @param {object} dest Destination Inspire Tree. * @param {boolean} hierarchy Include necessary ancestors to match hierarchy. * @return {object} Methods to perform action on copied nodes. */ }, { key: 'copy', value: function copy(dest, hierarchy) { var newNodes = new TreeNodes(this._tree); _.each(this, function (node) { newNodes.push(node.copy(dest, hierarchy)); }); return newNodes; } /** * Return deepest nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'deepest', value: function deepest() { var matches = new TreeNodes(this._tree); this.recurseDown(function (node) { if (!node.children) { matches.push(node); } }); return matches; } /** * Deselect nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'deselect', value: function deselect() { return this.invoke('deselect'); } /** * Deselect (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'deselectDeep', value: function deselectDeep() { return this.invokeDeep('deselect'); } /** * Iterate each TreeNode. * * @param {function} iteratee Iteratee invoke for each node. * @return {TreeNodes} Array of node objects. */ }, { key: 'each', value: function each(iteratee) { _.each(this, iteratee); return this; } /** * Query for all editable nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'editable', value: function editable(full) { return baseStatePredicate.call(this, 'editable', full); } /** * Query for all nodes in editing mode. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'editing', value: function editing(full) { return baseStatePredicate.call(this, 'editing', full); } /** * Release the current batch. * * @private * @return {void} */ }, { key: 'end', value: function end() { this.batching--; if (this.batching === 0) { this.applyChanges(); } } /** * Expand nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'expand', value: function expand() { return this.invoke('expand'); } /** * Query for all expanded nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'expanded', value: function expanded(full) { return baseStatePredicate.call(this, 'expanded', full); } /** * Expand (deeply) all nodes. * * @return {Promise<TreeNodes>} Promise resolved when all children have loaded and expanded. */ }, { key: 'expandDeep', value: function expandDeep() { var _this2 = this; return new es6Promise_1(function (resolve) { var waitCount = 0; var done = function done() { if (--waitCount === 0) { resolve(_this2); } }; _this2.recurseDown(function (node) { waitCount++; // Ignore nodes without children if (node.children) { node.expand().catch(done).then(function () { // Manually trigger expansion on newly loaded children node.children.expandDeep().catch(done).then(done); }); } else { done(); } }); }); } /** * Expand parents. * * @return {TreeNodes} Array of node objects. */ }, { key: 'expandParents', value: function expandParents() { return this.invoke('expandParents'); } /** * Clone a hierarchy of all nodes matching a predicate. * * Because it filters deeply, we must clone all nodes so that we * don't affect the actual node array. * * @param {string|function} predicate State flag or custom function. * @return {TreeNodes} Array of node objects. */ }, { key: 'extract', value: function extract(predicate) { var flat = this.flatten(predicate); var matches = new TreeNodes(this._tree); _.each(flat, function (node) { return matches.addNode(node.copyHierarchy()); }); return matches; } /** * Filter all nodes matching the given predicate. * * @param {string|function} predicate State flag or custom function. * @return {TreeNodes} Array of node objects. */ }, { key: 'filterBy', value: function filterBy(predicate) { var fn = getPredicateFunction(predicate); var matches = new TreeNodes(this._tree); _.each(this, function (node) { if (fn(node)) { matches.push(node); } }); return matches; } /** * Returns the first node matching predicate. * * @param {function} predicate Predicate function, accepts a single node and returns a boolean. * @return {TreeNode} First matching TreeNode, or undefined. */ }, { key: 'find', value: function find(predicate) { var match = void 0; this.recurseDown(function (node) { if (predicate(node)) { match = node; return false; } }); return match; } /** * Returns the first shallow node matching predicate. * * @param {function} predicate Predicate function, accepts a single node and returns a boolean. * @return {TreeNode} First matching TreeNode, or undefined. */ }, { key: 'first', value: function first(predicate) { for (var i = 0, l = this.length; i < l; i++) { if (predicate(this[i])) { return this[i]; } } } /** * Flatten and get only node(s) matching the expected state or predicate function. * * @param {string|function} predicate State property or custom function. * @return {TreeNodes} Flat array of matching nodes. */ }, { key: 'flatten', value: function flatten(predicate) { var flat = new TreeNodes(this._tree); var fn = getPredicateFunction(predicate); this.recurseDown(function (node) { if (fn(node)) { flat.push(node); } }); return flat; } /** * Query for all focused nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'focused', value: function focused(full) { return baseStatePredicate.call(this, 'focused', full); } /** * Iterate each TreeNode. * * @param {function} iteratee Iteratee invoke for each node. * @return {TreeNodes} Array of node objects. */ }, { key: 'forEach', value: function forEach(iteratee) { return this.each(iteratee); } /** * Get a specific node by its index, or undefined if it doesn't exist. * * @param {int} index Numeric index of requested node. * @return {TreeNode} Node object. Undefined if invalid index. */ }, { key: 'get', value: function get$$1(index) { return this[index]; } /** * Query for all hidden nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'hidden', value: function hidden(full) { return baseStatePredicate.call(this, 'hidden', full); } /** * Hide nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'hide', value: function hide() { return this.invoke('hide'); } /** * Hide (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'hideDeep', value: function hideDeep() { return this.invokeDeep('hide'); } /** * Query for all indeterminate nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'indeterminate', value: function indeterminate(full) { return baseStatePredicate.call(this, 'indeterminate', full); } /** * Insert a new node at a given position. * * @param {integer} index Index at which to insert the node. * @param {object} object Raw node object or TreeNode. * @return {TreeNode} Node object. */ }, { key: 'insertAt', value: function insertAt(index, object) { // If node has a pre-existing ID if (object.id) { // Is it already in the tree? var existingNode = this.node(object.id); if (existingNode) { existingNode.restore().show(); // Merge children if (_.isArrayLike(object.children)) { // Setup existing node's children property if needed if (!_.isArrayLike(existingNode.children)) { existingNode.children = new TreeNodes(this._tree); existingNode.children._context = existingNode; } // Copy each child (using addNode, which uses insertAt) _.each(object.children, function (child) { existingNode.children.addNode(child); }); } // Merge truthy children else if (object.children && _.isBoolean(existingNode.children)) { existingNode.children = object.children; } existingNode.markDirty(); this.applyChanges(); // Node merged, return it. return existingNode; } } // Node is new, insert at given location. var node = this._tree.constructor.isTreeNode(object) ? object : objectToNode(this._tree, object); // Grab remaining nodes this.splice(index, 0, node); // Refresh parent state and mark dirty if (this._context) { node.itree.parent = this._context; this._context.refreshIndeterminateState().markDirty(); } // Event this._tree.emit('node.added', node); // Always mark this node as dirty node.markDirty(); // If pushing this node anywhere but the end, other nodes may change. if (this.length - 1 !== index) { this.invoke('markDirty'); } this.applyChanges(); return node; } /** * Invoke method(s) on each node. * * @param {string|array} methods Method name(s). * @param {array|Arguments} args Array of arguments to proxy. * @return {TreeNodes} Array of node objects. */ }, { key: 'invoke', value: function invoke(methods, args) { return baseInvoke(this, methods, args); } /** * Invoke method(s) deeply. * * @param {string|array} methods Method name(s). * @param {array|Arguments} args Array of arguments to proxy. * @return {TreeNodes} Array of node objects. */ }, { key: 'invokeDeep', value: function invokeDeep(methods, args) { if (!_.isArrayLikeObject(args) || arguments.length > 2) { args = _.tail(arguments); } return baseInvoke(this, methods, args, true); } /** * Returns the last shallow node matching predicate. * * @param {function} predicate Predicate function, accepts a single node and returns a boolean. * @return {TreeNode} Last matching shallow TreeNode, or undefined. */ }, { key: 'last', value: function last(predicate) { for (var i = this.length - 1; i >= 0; i--) { if (predicate(this[i])) { return this[i]; } } } /** * Query for all nodes currently loading children. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'loading', value: function loading(full) { return baseStatePredicate.call(this, 'loading', full); } /** * Loads additional nodes for this context. * * @param {Event} event Click or scroll event if DOM interaction triggered this call. * @return {Promise<TreeNodes>} Resolves with request results. */ }, { key: 'loadMore', value: function loadMore(event) { var _this3 = this; // Never refire if node is loading if (this._loading) { return es6Promise_1.reject(new Error('Pending loadMore call must complete before being invoked again.')); } var promise = void 0; // If no records remain, immediately resolve if (this._pagination.limit === this._pagination.total) { return es6Promise_1.resolve(); } // Set loading flag, prevents repeat requests this._loading = true; this.batch(); // Mark this context as dirty since we'll update text/tree nodes _.invoke(this._context, 'markDirty'); // Increment the pagination this._pagination.limit += this._tree.config.pagination.limit; // Emit an event this._tree.emit('node.paginated', this._context || this._tree, this.pagination, event); if (this._tree.config.deferredLoading) { if (this._context) { promise = this._context.loadChildren(); } else { promise = this._tree.load(this._tree.config.data); } } else { this._loading = false; promise = es6Promise_1.resolve(); } this.end(); // Clear the loading flag if (this._tree.config.deferredLoading) { promise.then(function () { _this3._loading = false; _this3.applyChanges(); }).catch(function () { _this3._loading = false; _this3.applyChanges(); }); } return promise; } /** * Query for all nodes matched in the last search. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'matched', value: function matched(full) { return baseStatePredicate.call(this, 'matched', full); } /** * Move node at a given index to a new index. * * @param {int} index Current index. * @param {int} newIndex New index. * @param {TreeNodes} target Target TreeNodes array. Defaults to this. * @return {TreeNode} Node object. */ }, { key: 'move', value: function move(index, newIndex) { var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this; var oldNode = this[index].remove(); var node = target.insertAt(newIndex, oldNode); this._tree.emit('node.moved', node, this, index, target, newIndex); return node; } /** * Get a node. * * @param {string|number} id ID of node. * @return {TreeNode} Node object. */ }, { key: 'node', value: function node(id) { var match = void 0; this.recurseDown(function (node) { if (node.id === id) { match = node; return false; } }); return match; } /** * Get all nodes in a tree, or nodes for an array of IDs. * * @param {array} refs Array of ID references. * @return {TreeNodes} Array of node objects. * @example * * let all = tree.nodes() * let some = tree.nodes([1, 2, 3]) */ }, { key: 'nodes', value: function nodes(refs) { var results = void 0; if (_.isArray(refs)) { results = new TreeNodes(this._tree); this.recurseDown(function (node) { if (refs.indexOf(node.id) > -1) { results.push(node); } }); } return _.isArray(refs) ? results : this; } /** * Get the pagination. * * @return {object} Pagination configuration object. */ }, { key: 'pagination', value: function pagination() { return this._pagination; } /** * Removes the last node. * * @return {TreeNode} Last tree node. */ }, { key: 'pop', value: function pop() { var result = get(TreeNodes.prototype.__proto__ || Object.getPrototypeOf(TreeNodes.prototype), 'pop', this).call(this); this.indicesDirty = true; this.calculateRenderablePositions(); return result; } /** * Push a new TreeNode onto the collection. * * @param {TreeNode} node Node objext. * @returns {number} The new length. */ }, { key: 'push', value: function push(node) { var result = get(TreeNodes.prototype.__proto__ || Object.getPrototypeOf(TreeNodes.prototype), 'push', this).call(this, node); this.indicesDirty = true; this.calculateRenderablePositions(); return result; } /** * Iterate down all nodes and any children. * * Return false to stop execution. * * @param {function} iteratee Iteratee function. * @return {TreeNodes} Resulting nodes. */ }, { key: 'recurseDown', value: function recurseDown$$1(iteratee) { recurseDown(this, iteratee); return this; } /** * Remove a node. * * @param {TreeNode} node Node object. * @return {TreeNodes} Resulting nodes. */ }, { key: 'remove', value: function remove(node) { _.remove(this, { id: node.id }); _.invoke(this._context, 'markDirty'); this.indicesDirty = true; this.applyChanges(); return this; } /** * Query for all soft-removed nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'removed', value: function removed(full) { return baseStatePredicate.call(this, 'removed', full); } /** * Restore nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'restore', value: function restore() { return this.invoke('restore'); } /** * Restore (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'restoreDeep', value: function restoreDeep() { return this.invokeDeep('restore'); } /** * Select nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'select', value: function select() { return this.invoke('select'); } /** * Query for all selectable nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'selectable', value: function selectable(full) { return baseStatePredicate.call(this, 'selectable', full); } /** * Select (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'selectDeep', value: function selectDeep() { return this.invokeDeep('select'); } /** * Query for all selected nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'selected', value: function selected(full) { return baseStatePredicate.call(this, 'selected', full); } /** * Removes the first node. * * @param {TreeNode} node Node object. * @return {TreeNode} Node object. */ }, { key: 'shift', value: function shift(node) { var result = get(TreeNodes.prototype.__proto__ || Object.getPrototypeOf(TreeNodes.prototype), 'shift', this).call(this, node); this.indicesDirty = true; this.calculateRenderablePositions(); return result; } /** * Show nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'show', value: function show() { return this.invoke('show'); } /** * Show (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'showDeep', value: function showDeep() { return this.invokeDeep('show'); } /** * Soft-remove nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'softRemove', value: function softRemove() { return this.invoke('softRemove'); } /** * Sorts all TreeNode objects in this collection. * * If no custom sorter given, the configured "sort" value will be used. * * @param {string|function} sorter Sort function or property name. * @return {TreeNodes} Array of node objects. */ }, { key: 'sortBy', value: function sortBy(sorter) { var _this4 = this; sorter = sorter || this._tree.config.sort; // Only apply sort if one provided if (sorter) { this.batch(); var sorted = _.sortBy(this, sorter); this.length = 0; _.each(sorted, function (node) { _this4.push(node); }); this.indicesDirty = true; this.end(); } return this; } /** * Sorts (deeply) all nodes in this collection. * * @param {function} comparator [description] * @return {TreeNodes} Array of node objects. */ }, { key: 'sortDeep', value: function sortDeep(comparator) { this.sort(comparator); this.each(function (node) { if (node.hasChildren()) { node.children.sortDeep(comparator); } }); return this; } /** * Changes array contents by removing existing nodes and/or adding new nodes. * * @param {number} start Start index. * @param {number} deleteCount Number of nodes to delete. * @param {TreeNode} ...nodes One or more nodes. * @return {array} Array of deleted elements. */ }, { key: 'splice', value: function splice() { var result = get(TreeNodes.prototype.__proto__ || Object.getPrototypeOf(TreeNodes.prototype), 'splice', this).apply(this, arguments); this.indicesDirty = true; this.calculateRenderablePositions(); return result; } /** * Set nodes' state values. * * @param {string} name Property name. * @param {boolean} newVal New value, if setting. * @return {TreeNodes} Array of node objects. */ }, { key: 'state', value: function state() { return this.invoke('state', arguments); } /** * Set (deeply) nodes' state values. * * @param {string} name Property name. * @param {boolean} newVal New value, if setting. * @return {TreeNodes} Array of node objects. */ }, { key: 'stateDeep', value: function stateDeep() { return this.invokeDeep('state', arguments); } /** * Swaps two node positions. * * @param {TreeNode} node1 Node 1. * @param {TreeNode} node2 Node 2. * @return {TreeNodes} Array of node objects. */ }, { key: 'swap', value: function swap(node1, node2) { this._tree.batch(); var n1Context = node1.context(); var n2Context = node2.context(); // Cache. Note: n2Index is only usable once var n1Index = n1Context.indexOf(node1); var n2Index = n2Context.indexOf(node2); // If contexts match, we can simply re-assign them if (n1Context === n2Context) { this[n1Index] = node2; this[n2Index] = node1; // Emit move events for each node this._tree.emit('node.moved', node1, n1Context, n1Index, n2Context, n2Index); this._tree.emit('node.moved', node2, n2Context, n2Index, n1Context, n1Index); } else { // Otherwise, we have to move between contexts // Move node 1 to node 2's index n1Context.move(n1Index, n2Context.indexOf(node2), n2Context); // Move node 2 to node 1s original index n2Context.move(n2Context.indexOf(node2), n1Index, n1Context); } this.indicesDirty = true; this._tree.end(); this._tree.emit('node.swapped', node1, n1Context, n1Index, node2, n2Context, n2Index); return this; } /** * Get the tree instance. * * @return {InspireTree} Tree instance. */ }, { key: 'tree', value: function tree() { return this._tree; } /** * Get a native node Array. * * @return {array} Array of node objects. */ }, { key: 'toArray', value: function toArray$$1() { var array = []; _.each(this, function (node) { array.push(node.toObject()); }); return array; } /** * Adds a node to beginning of the collection. * * @param {TreeNode} node Node object. * @return {number} New length of collection. */ }, { key: 'unshift', value: function unshift(node) { var result = get(TreeNodes.prototype.__proto__ || Object.getPrototypeOf(TreeNodes.prototype), 'unshift', this).call(this, node); this.indicesDirty = true; this.calculateRenderablePositions(); return result; } /** * Query for all visible nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'visible', value: function visible(full) { return baseStatePredicate.call(this, 'visible', full); } }]); return TreeNodes; }(_extendableBuiltin(Array)); /** * Base recursion function for a collection or node. * * Returns false if execution should cease. * * @private * @param {TreeNode|TreeNodes} obj Node or collection. * @param {function} iteratee Iteratee function * @return {boolean} Cease iteration. */ function recurseDown(obj, iteratee) { var res = void 0; if (obj instanceof TreeNodes) { _.each(obj, function (node) { res = recurseDown(node, iteratee); return res; }); } else if (obj instanceof TreeNode) { res = iteratee(obj); // Recurse children if (res !== false && obj.hasChildren()) { res = recurseDown(obj.children, iteratee); } } return res; } /** * Resolve promise-like objects consistently. * * @private * @param {object} promise Promise-like object. * @returns {Promise} Promise */ function standardizePromise(promise) { return new es6Promise_1(function (resolve, reject) { if (!_.isObject(promise)) { return reject(new Error('Invalid Promise')); } if (_.isFunction(promise.then)) { promise.then(resolve); } // jQuery promises use "error" if (_.isFunction(promise.error)) { promise.error(reject); } else if (_.isFunction(promise.catch)) { promise.catch(reject); } }); } // Libs /** * Helper method to clone an ITree config object. * * Rejects non-clonable properties like ref. * * @private * @param {object} itree ITree configuration object * @param {array} excludeKeys Keys to exclude, if any * @return {object} Cloned ITree. */ function cloneItree(itree, excludeKeys) { var clone = {}; excludeKeys = _.castArray(excludeKeys); excludeKeys.push('ref'); _.each(itree, function (v, k) { if (!_.includes(excludeKeys, k)) { clone[k] = _.cloneDeep(v); } }); return clone; } /** * Get or set a state value. * * This is a base method and will not invoke related changes, for example * setting selected=false will not trigger any deselection logic. * * @private * @param {TreeNode} node Tree node. * @param {string} property Property name. * @param {boolean} val New value, if setting. * @return {boolean} Current value on read, old value on set. */ function baseState(node, property, val) { var currentVal = node.itree.state[property]; if (typeof val !== 'undefined' && currentVal !== val) { // Update values node.itree.state[property] = val; if (property !== 'rendered') { node.markDirty(); } // Emit an event node._tree.emit('node.state.changed', node, property, currentVal, val); } return currentVal; } /** * Represents a singe node object within the tree. * * @param {TreeNode} source TreeNode to copy. * @return {TreeNode} Tree node object. */ var TreeNode = function () { function TreeNode(tree, source, excludeKeys) { var _this = this; classCallCheck(this, TreeNode); this._tree = tree; if (source instanceof TreeNode) { excludeKeys = _.castArray(excludeKeys); excludeKeys.push('_tree'); // Iterate manually for better perf _.each(source, function (value, key) { // Skip properties if (!_.includes(excludeKeys, key)) { if (_.isObject(value)) { if (value instanceof TreeNodes) { _this[key] = value.clone(); } else if (key === 'itree') { _this[key] = cloneItree(value); } else { _this[key] = _.cloneDeep(value); } } else { // Copy primitives _this[key] = value; } } }); } } /** * Add a child to this node. * * @param {object} child Node object. * @return {TreeNode} Node object. */ createClass(TreeNode, [{ key: 'addChild', value: function addChild(child) { if (_.isArray(this.children) || !_.isArrayLike(this.children)) { this.children = new TreeNodes(this._tree); this.children._context = this; } return this.children.addNode(child); } /** * Add multiple children to this node. * * @param {object} children Array of nodes. * @return {TreeNodes} Array of node objects. */ }, { key: 'addChildren', value: function addChildren(children) { var _this2 = this; var nodes = new TreeNodes(this._tree); if (_.isArray(this.children) || !_.isArrayLike(this.children)) { this.children = new TreeNodes(this._tree); this.children._context = this; } this.children.batch(); _.each(children, function (child) { nodes.push(_this2.addChild(child)); }); this.children.end(); return nodes; } /** * Ensure this node allows dynamic children. * * @private * @return {boolean} True if tree/node allows dynamic children. */ }, { key: 'allowDynamicLoad', value: function allowDynamicLoad() { return this._tree.isDynamic && (_.isArrayLike(this.children) || this.children === true); } /** * Assign source object(s) to this node. * * @param {object} source Source object(s) * @return {TreeNode} Node object. */ }, { key: 'assign', value: function assign() { _.assign.apply(_, [this].concat(Array.prototype.slice.call(arguments))); this.markDirty(); this.context().applyChanges(); return this; } /** * Check if node available. * * @return {boolean} True if available. */ }, { key: 'available', value: function available() { return !this.hidden() && !this.removed(); } /** * Blur focus from this node. * * @return {TreeNode} Node object. */ }, { key: 'blur', value: function blur() { this.state('editing', false); return baseStateChange('focused', false, 'blurred', this); } }, { key: 'check', /** * Mark node as checked. * * @param {boolean} shallow Skip auto-checking children. * @return {TreeNode} Node object. */ value: function check(shallow) { this._tree.batch(); // Will we automatically apply state changes to our children var deep = !shallow && this._tree.config.checkbox.autoCheckChildren; baseStateChange('checked', true, 'checked', this, deep); // Refresh parent if (this.hasParent()) { this.getParent().refreshIndeterminateState(); } this._tree.end(); return this; } }, { key: 'checked', /** * Get whether this node is checked. * * @return {boolean} True if node checked. */ value: function checked() { return this.state('checked'); } /** * Hide parents without any visible children. * * @return {TreeNode} Node object. */ }, { key: 'clean', value: function clean() { this.recurseUp(function (node) { if (node.hasParent()) { var parent = node.getParent(); if (!parent.hasVisibleChildren()) { parent.hide(); } } }); return this; } /** * Clone this node. * * @param {array} excludeKeys Keys to exclude from the clone. * @return {TreeNode} New node object. */ }, { key: 'clone', value: function clone(excludeKeys) { return new TreeNode(this._tree, this, excludeKeys); } /** * Collapse this node. * * @return {TreeNode} Node object. */ }, { key: 'collapse', value: function collapse() { return baseStateChange('collapsed', true, 'collapsed', this); } /** * Get whether this node is collapsed. * * @return {boolean} True if node collapsed. */ }, { key: 'collapsed', value: function collapsed() { return this.state('collapsed'); } /** * Get the containing context. If no parent present, the root context is returned. * * @return {TreeNodes} Node array object. */ }, { key: 'context', value: function context() { return this.hasParent() ? this.getParent().children : this._tree.model; } /** * Copy node to another tree instance. * * @param {object} dest Destination Inspire Tree. * @param {boolean} hierarchy Include necessary ancestors to match hierarchy. * @return {object} Property "to" for defining destination. */ }, { key: 'copy', value: function copy(dest, hierarchy) { if (!dest || !_.isFunction(dest.addNode)) { throw new Error('Destination must be an Inspire Tree instance.'); } var node = this; if (hierarchy) { node = node.copyHierarchy(); } return dest.addNode(node.toObject()); } /** * Copy all parents of a node. * * @param {boolean} excludeNode Exclude given node from hierarchy. * @return {TreeNode} Root node object with hierarchy. */ }, { key: 'copyHierarchy', value: function copyHierarchy(excludeNode) { var nodes = []; var parents = this.getParents(); // Remove old hierarchy data _.each(parents, function (node) { nodes.push(node.toObject(excludeNode)); }); parents = nodes.reverse(); if (!excludeNode) { var clone = this.toObject(true); // Filter out hidden children if (this.hasChildren()) { clone.children = this.children.filterBy(function (n) { return !n.state('hidden'); }).toArray(); clone.children._context = clone; } nodes.push(clone); } var hierarchy = nodes[0]; var pointer = hierarchy; var l = nodes.length; _.each(nodes, function (parent, key) { var children = []; if (key + 1 < l) { children.push(nodes[key + 1]); pointer.children = children; pointer = pointer.children[0]; } }); return objectToNode(this._tree, hierarchy); } }, { key: 'deselect', /** * Deselect this node. * * If selection.require is true and this is the last selected * node, the node will remain in a selected state. * * @param {boolean} shallow Skip auto-deselecting children. * @return {TreeNode} Node object. */ value: function deselect(shallow) { if (this.selected() && (!this._tree.config.selection.require || this._tree.selected().length > 1)) { this.context().batch(); // Will we apply this state change to our children? var deep = !shallow && this._tree.config.selection.autoSelectChildren; baseStateChange('selected', false, 'deselected', this, deep); this.context().end(); } return this; } /** * Get weather node editable. Required editing.edit to be enable via config. * * @return {boolean} True if node editable. */ }, { key: 'editable', value: function editable() { return this._tree.config.editable && this._tree.config.editing.edit && this.state('editable'); } /** * Get weather node is currently in edit mode. * * @return {boolean} True if node in edit mode. */ }, { key: 'editing', value: function editing() { return this.state('editing'); } /** * Expand this node. * * @return {Promise<TreeNode>} Promise resolved on successful load and expand of children. */ }, { key: 'expand', value: function expand() { var node = this; return new es6Promise_1(function (resolve, reject) { var allow = node.hasChildren() || node._tree.isDynamic && node.children === true; if (allow && (node.collapsed() || node.hidden())) { node.state('collapsed', false); node.state('hidden', false); node._tree.emit('node.expanded', node); if (node._tree.isDynamic && node.children === true) { node.loadChildren().then(resolve).catch(reject); } else { node.context().applyChanges(); resolve(node); } } else { // Resolve immediately resolve(node); } }); } /** * Get weather node expanded. * * @return {boolean} True if expanded. */ }, { key: 'expanded', value: function expanded() { return !this.collapsed(); } /** * Expand parent nodes. * * @return {TreeNode} Node object. */ }, { key: 'expandParents', value: function expandParents() { if (this.hasParent()) { this.getParent().recurseUp(function (node) { node.expand(); }); } return this; } /** * Focus a node without changing its selection. * * @return {TreeNode} Node object. */ }, { key: 'focus', value: function focus() { if (!this.focused()) { // Batch selection changes this._tree.batch(); this._tree.blurDeep(); this.state('focused', true); // Emit this event this._tree.emit('node.focused', this); // Mark hierarchy dirty and apply this.markDirty(); this._tree.end(); } return this; } /** * Get weather this node is focused. * * @return {boolean} True if node focused. */ }, { key: 'focused', value: function focused() { return this.state('focused'); } /** * Get children for this node. If no children exist, an empty TreeNodes * collection is returned for safe chaining. * * @return {TreeNodes} Array of node objects. */ }, { key: 'getChildren', value: function getChildren() { return this.hasChildren() ? this.children : new TreeNodes(this._tree); } /** * Get the immediate parent, if any. * * @return {TreeNode} Node object. */ }, { key: 'getParent', value: function getParent() { return this.itree.parent; } /** * Get parent nodes. Excludes any siblings. * * @return {TreeNodes} Node objects. */ }, { key: 'getParents', value: function getParents() { var parents = new TreeNodes(this._tree); if (this.hasParent()) { this.getParent().recurseUp(function (node) { parents.push(node); }); } return parents; } /** * Get a textual hierarchy for a given node. An array * of text from this node's root ancestor to the given node. * * @return {array} Array of node texts. */ }, { key: 'getTextualHierarchy', value: function getTextualHierarchy() { var paths = []; this.recurseUp(function (node) { paths.unshift(node.text); }); return paths; } /** * Get weather the given node is an ancestor of this node. * * @param {TreeNode} node Node object. * @return {boolean} True if node is an ancestor or the given node */ }, { key: 'hasAncestor', value: function hasAncestor(node) { var hasAncestor = false; this.recurseUp(function (n) { return !(hasAncestor = n.id === node.id); }); return hasAncestor; } /** * Get weather node has any children. * * @return {boolean} True if has loaded children. */ }, { key: 'hasChildren', value: function hasChildren() { return _.isArrayLike(this.children) && this.children.length > 0; } /** * Get weather children have been loaded. Will always be true for non-dynamic nodes. * * @return {boolean} True if we've attempted to load children. */ }, { key: 'hasLoadedChildren', value: function hasLoadedChildren() { return _.isArrayLike(this.children); } /** * Get weather node has any children, or allows dynamic loading. * * @return {boolean} True if node has, or will have children. */ }, { key: 'hasOrWillHaveChildren', value: function hasOrWillHaveChildren() { return _.isArrayLike(this.children) ? Boolean(this.children.length) : this.allowDynamicLoad(); } /** * Get weather node has a parent. * * @return {boolean} True if has a parent. */ }, { key: 'hasParent', value: function hasParent() { return Boolean(this.itree.parent); } /** * Get weather node has any visible children. * * @return {boolean} True if children are visible. */ }, { key: 'hasVisibleChildren', value: function hasVisibleChildren() { var hasVisibleChildren = false; if (this.hasChildren()) { hasVisibleChildren = this.children.filterBy('available').length > 0; } return hasVisibleChildren; } /** * Hide this node. * * @return {TreeNode} Node object. */ }, { key: 'hide', value: function hide() { var node = baseStateChange('hidden', true, 'hidden', this); // Update children if (node.hasChildren()) { node.children.hide(); } return node; } /** * Get weather this node is hidden. * * @return {boolean} True if node hidden. */ }, { key: 'hidden', value: function hidden() { return this.state('hidden'); } /** * Get a "path" of indices, values which map this node's location within all parent contexts. * * @return {string} Index path */ }, { key: 'indexPath', value: function indexPath() { var indices = []; this.recurseUp(function (node) { indices.push(_.indexOf(node.context(), node)); }); return indices.reverse().join('.'); } /** * Get weather this node is indeterminate. * * @return {boolean} True if node indeterminate. */ }, { key: 'indeterminate', value: function indeterminate() { return this.state('indeterminate'); } /** * Get whether this node is the first renderable in its context. * * @return {boolean} True if node is first renderable */ }, { key: 'isFirstRenderable', value: function isFirstRenderable() { return this === this.context().firstRenderableNode; } /** * Get whether this node is the last renderable in its context. * * @return {boolean} True if node is last renderable */ }, { key: 'isLastRenderable', value: function isLastRenderable() { return this === this.context().lastRenderableNode; } /** * Get whether this node is the only renderable in its context. * * @return {boolean} True if node is only renderable */ }, { key: 'isOnlyRenderable', value: function isOnlyRenderable() { return this.isFirstRenderable() && this.isLastRenderable(); } /** * Find the last + deepest visible child of the previous sibling. * * @return {TreeNode} Node object. */ }, { key: 'lastDeepestVisibleChild', value: function lastDeepestVisibleChild() { var found = void 0; if (this.hasChildren() && !this.collapsed()) { found = _.findLast(this.children, function (node) { return node.visible(); }); var res = found.lastDeepestVisibleChild(); if (res) { found = res; } } return found; } /** * Initiate a dynamic load of children for a given node. * * This requires `tree.config.data` to be a function which accepts * three arguments: node, resolve, reject. * * Use the `node` to filter results. * * On load success, pass the result array to `resolve`. * On error, pass the Error to `reject`. * * @return {Promise<TreeNodes>} Promise resolving children nodes. */ }, { key: 'loadChildren', value: function loadChildren() { var _this3 = this; return new es6Promise_1(function (resolve, reject) { if (!_this3.allowDynamicLoad()) { return reject(new Error('Node does not have or support dynamic children.')); } _this3.state('loading', true); _this3.markDirty(); _this3.context().applyChanges(); var complete = function complete(nodes, totalNodes) { // A little type-safety for silly situations if (!_.isArrayLike(nodes)) { return reject(new TypeError('Loader requires an array-like `nodes` parameter.')); } _this3.context().batch(); _this3.state('loading', false); var model = collectionToModel(_this3._tree, nodes, _this3); if (_.isArrayLike(_this3.children)) { _this3.children = _this3.children.concat(model); } else { _this3.children = model; } if (_.parseInt(totalNodes) > nodes.length) { _this3.children._pagination.total = _.parseInt(totalNodes); } // If using checkbox mode, share selection with newly loaded children if (_this3._tree.config.selection.mode === 'checkbox' && _this3.selected()) { _this3.children.select(); } _this3.markDirty(); _this3.context().end(); resolve(_this3.children); _this3._tree.emit('children.loaded', _this3); }; var error = function error(err) { _this3.state('loading', false); _this3.children = new TreeNodes(_this3._tree); _this3.children._context = _this3; _this3.markDirty(); _this3.context().applyChanges(); reject(err); _this3._tree.emit('tree.loaderror', err); }; var pagination = _this3._tree.constructor.isTreeNodes(_this3.children) ? _this3.children.pagination() : null; var loader = _this3._tree.config.data(_this3, complete, error, pagination); // Data loader is likely a promise if (_.isObject(loader)) { standardizePromise(loader).then(complete).catch(error); } }); } /** * Get weather this node is loading child data. * * @return {boolean} True if node's children are loading. */ }, { key: 'loading', value: function loading() { return this.state('loading'); } /** * Load additional children. * * @param {Event} event Click or scroll event if DOM interaction triggered this call. * @return {Promise<TreeNodes>} Resolves with request results. */ }, { key: 'loadMore', value: function loadMore() { if (!this.children || this.children === true) { return es6Promise_1.reject(new Error('Children have not yet been loaded.')); } return this.children.loadMore(); } /** * Mark node as dirty. For some systems this assists with rendering tracking. * * @return {TreeNode} Node object. */ }, { key: 'markDirty', value: function markDirty() { if (!this.itree.dirty) { this.itree.dirty = true; if (this.hasParent()) { this.getParent().markDirty(); } } return this; } /** * Get whether this node was matched during the last search. * * @return {boolean} True if node matched. */ }, { key: 'matched', value: function matched() { return this.state('matched'); } /** * Find the next visible sibling of our ancestor. Continues * seeking up the tree until a valid node is found or we * reach the root node. * * @return {TreeNode} Node object. */ }, { key: 'nextVisibleAncestralSiblingNode', value: function nextVisibleAncestralSiblingNode() { var next = void 0; if (this.hasParent()) { var parent = this.getParent(); next = parent.nextVisibleSiblingNode(); if (!next) { next = parent.nextVisibleAncestralSiblingNode(); } } return next; } /** * Find next visible child node. * * @return {TreeNode} Node object, if any. */ }, { key: 'nextVisibleChildNode', value: function nextVisibleChildNode() { var next = void 0; if (this.hasChildren()) { next = _.find(this.children, function (child) { return child.visible(); }); } return next; } /** * Get the next visible node. * * @return {TreeNode} Node object if any. */ }, { key: 'nextVisibleNode', value: function nextVisibleNode() { var next = void 0; // 1. Any visible children next = this.nextVisibleChildNode(); // 2. Any Siblings if (!next) { next = this.nextVisibleSiblingNode(); } // 3. Find sibling of ancestor(s) if (!next) { next = this.nextVisibleAncestralSiblingNode(); } return next; } /** * Find the next visible sibling node. * * @return {TreeNode} Node object, if any. */ }, { key: 'nextVisibleSiblingNode', value: function nextVisibleSiblingNode() { var context = this.hasParent() ? this.getParent().children : this._tree.nodes(); var i = _.findIndex(context, { id: this.id }); return _.find(_.slice(context, i + 1), function (node) { return node.visible(); }); } /** * Get pagination object for this tree node. * * @return {object} Pagination configuration object. */ }, { key: 'pagination', value: function pagination() { return _.get(this, 'children._pagination'); } /** * Find the previous visible node. * * @return {TreeNode} Node object, if any. */ }, { key: 'previousVisibleNode', value: function previousVisibleNode() { var prev = void 0; // 1. Any Siblings prev = this.previousVisibleSiblingNode(); // 2. If that sibling has children though, go there if (prev && prev.hasChildren() && !prev.collapsed()) { prev = prev.lastDeepestVisibleChild(); } // 3. Parent if (!prev && this.hasParent()) { prev = this.getParent(); } return prev; } /** * Find the previous visible sibling node. * * @return {TreeNode} Node object, if any. */ }, { key: 'previousVisibleSiblingNode', value: function previousVisibleSiblingNode() { var context = this.hasParent() ? this.getParent().children : this._tree.nodes(); var i = _.findIndex(context, { id: this.id }); return _.findLast(_.slice(context, 0, i), function (node) { return node.visible(); }); } /** * Iterate down node and any children. * * @param {function} iteratee Iteratee function. * @return {TreeNode} Node object. */ }, { key: 'recurseDown', value: function recurseDown$$1(iteratee) { recurseDown(this, iteratee); return this; } /** * Iterate up a node and its parents. * * @param {function} iteratee Iteratee function. * @return {TreeNode} Node object. */ }, { key: 'recurseUp', value: function recurseUp(iteratee) { var result = iteratee(this); if (result !== false && this.hasParent()) { this.getParent().recurseUp(iteratee); } return this; } /** * Update the indeterminate state of this node by scanning states of children. * * True if some, but not all children are checked. * False if no children are checked. * * @return {TreeNode} Node object. */ }, { key: 'refreshIndeterminateState', value: function refreshIndeterminateState() { var oldValue = this.indeterminate(); this.state('indeterminate', false); if (this.hasChildren()) { var childrenCount = this.children.length; var indeterminate = 0; var checked = 0; this.children.each(function (n) { if (n.checked()) { checked++; } if (n.indeterminate()) { indeterminate++; } }); // Set selected if all children are if (checked === childrenCount) { baseStateChange('checked', true, 'checked', this); } else { baseStateChange('checked', false, 'unchecked', this); } // Set indeterminate if any children are, or some children are selected if (!this.checked()) { this.state('indeterminate', indeterminate > 0 || childrenCount > 0 && checked > 0 && checked < childrenCount); } } if (this.hasParent()) { this.getParent().refreshIndeterminateState(); } if (oldValue !== this.state('indeterminate')) { this.markDirty(); } return this; } /** * Remove all current children and re-execute a loadChildren call. * * @return {Promise<TreeNodes>} Promise resolved on load. */ }, { key: 'reload', value: function reload() { var _this4 = this; return new es6Promise_1(function (resolve, reject) { if (!_this4.allowDynamicLoad()) { return reject(new Error('Node or tree does not support dynamic children.')); } // Reset children _this4.children = true; // Collapse _this4.collapse(); // Load and the proxy the promise _this4.loadChildren().then(resolve).catch(reject); }); } /** * Remove a node from the tree. * * @param {boolean} includeState Include itree.state object. * @return {object} Removed tree node object. */ }, { key: 'remove', value: function remove() { var includeState = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; // Cache parent before we remove the node var parent = this.getParent(); // Remove self this.context().remove(this); // Refresh parent states if (parent) { parent.refreshIndeterminateState(); parent.markDirty(); } var pagination = parent ? parent.pagination() : this._tree.pagination(); pagination.total--; // Export/event var exported = this.toObject(false, includeState); this._tree.emit('node.removed', exported, parent); this.context().applyChanges(); return exported; } /** * Get whether this node is soft-removed. * * @return {boolean} True if node soft-removed. */ }, { key: 'removed', value: function removed() { return this.state('removed'); } /** * Get whether this node can be "rendered" when the context is. * Hidden and removed nodes may still be included in the DOM, * but not "rendered" in a sense they'll be visible. * * @return {boolean} If not hidden or removed */ }, { key: 'renderable', value: function renderable() { return !this.hidden() && !this.removed(); } /** * Get whether this node has been rendered. * * Will be false if deferred rendering is enable and the node has * not yet been loaded, or if a custom DOM renderer is used. * * @return {boolean} True if node rendered. */ }, { key: 'rendered', value: function rendered() { return this.state('rendered'); } /** * Restore state if soft-removed. * * @return {TreeNode} Node object. */ }, { key: 'restore', value: function restore() { return baseStateChange('removed', false, 'restored', this); } /** * Select this node. * * @param {boolean} shallow Skip auto-selecting children. * @return {TreeNode} Node object. */ }, { key: 'select', value: function select(shallow) { if (!this.selected() && this.selectable()) { // Batch selection changes this._tree.batch(); if (this._tree.canAutoDeselect()) { var oldVal = this._tree.config.selection.require; this._tree.config.selection.require = false; this._tree.deselectDeep(); this._tree.config.selection.require = oldVal; } // Will we apply this state change to our children? var deep = !shallow && this._tree.config.selection.autoSelectChildren; baseStateChange('selected', true, 'selected', this, deep); // Cache as the last selected node this._tree._lastSelectedNode = this; // Mark hierarchy dirty and apply this.markDirty(); this._tree.end(); } return this; } /** * Get weather node selectable. * * @return {boolean} True if node selectable. */ }, { key: 'selectable', value: function selectable() { var allow = this._tree.config.selection.allow(this); return typeof allow === 'boolean' ? allow : this.state('selectable'); } /** * Get whether this node is selected. * * @return {boolean} True if node selected. */ }, { key: 'selected', value: function selected() { return this.state('selected'); } /** * Set a root property on this node. * * @param {string|number} property Property name. * @param {*} value New value. * @return {TreeNode} Node object. */ }, { key: 'set', value: function set$$1(property, value) { this[property] = value; this.markDirty(); this.context().applyChanges(); return this; } /** * Show this node. * * @return {TreeNode} Node object. */ }, { key: 'show', value: function show() { return baseStateChange('hidden', false, 'shown', this); } /** * Mark this node as "removed" without actually removing it. * * Expand/show methods will never reveal this node until restored. * * @return {TreeNode} Node object. */ }, { key: 'softRemove', value: function softRemove() { return baseStateChange('removed', true, 'softremoved', this, 'softRemove'); } /** * Get or set a state value. * * This is a base method and will not invoke related changes, for example * setting selected=false will not trigger any deselection logic. * * @param {string|object} obj Property name or Key/Value state object. * @param {boolean} val New value, if setting. * @return {boolean|object} Old state object, or old value if property name used. */ }, { key: 'state', value: function state(obj, val) { var _this5 = this; if (_.isString(obj)) { return baseState(this, obj, val); } this.context().batch(); var oldState = {}; _.each(obj, function (value, prop) { oldState[prop] = baseState(_this5, prop, value); }); this.context().end(); return oldState; } /** * Get or set multiple state values to a single value. * * @param {Array} names Property names. * @param {boolean} newVal New value, if setting. * @return {Array} Array of state booleans */ }, { key: 'states', value: function states(names, newVal) { var _this6 = this; var results = []; this.context().batch(); _.each(names, function (name) { results.push(_this6.state(name, newVal)); }); this.context().end(); return results; } /** * Swap position with the given node. * * @param {TreeNode} node Node. * @return {TreeNode} Node objects. */ }, { key: 'swap', value: function swap(node) { this.context().swap(this, node); return this; } /** * Toggle checked state. * * @return {TreeNode} Node object. */ }, { key: 'toggleCheck', value: function toggleCheck() { return this.checked() ? this.uncheck() : this.check(); } /** * Toggle collapsed state. * * @return {TreeNode} Node object. */ }, { key: 'toggleCollapse', value: function toggleCollapse() { return this.collapsed() ? this.expand() : this.collapse(); } /** * Toggle editing state. * * @return {TreeNode} Node object. */ }, { key: 'toggleEditing', value: function toggleEditing() { this.state('editing', !this.state('editing')); this.markDirty(); this.context().applyChanges(); return this; } /** * Toggle selected state. * * @return {TreeNode} Node object. */ }, { key: 'toggleSelect', value: function toggleSelect() { return this.selected() ? this.deselect() : this.select(); } /** * Export this node as a native Object. * * @param {boolean} excludeChildren Exclude children. * @param {boolean} includeState Include itree.state object. * @return {object} Node object. */ }, { key: 'toObject', value: function toObject() { var _this7 = this; var excludeChildren = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var includeState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var exported = {}; var keys = _.pull(Object.keys(this), '_tree', 'children', 'itree'); // Map keys _.each(keys, function (keyName) { exported[keyName] = _this7[keyName]; }); // Copy over whitelisted itree data // Excludes internal-use junk like parent, dirty, ref var itree = exported.itree = {}; itree.a = this.itree.a; itree.icon = this.itree.icon; itree.li = this.itree.li; if (includeState) { itree.state = this.itree.state; } // If including children, export them if (!excludeChildren && this.hasChildren() && _.isFunction(this.children.toArray)) { exported.children = this.children.toArray(); } return exported; } /** * Get the text content of this tree node. * * @return {string} Text content. */ }, { key: 'toString', value: function toString() { return this.text; } /** * Get the tree this node ultimately belongs to. * * @return {InspireTree} Tree instance. */ }, { key: 'tree', value: function tree() { return this.context().tree(); } /** * Uncheck this node. * * @param {boolean} shallow Skip auto-unchecking children. * @return {TreeNode} Node object. */ }, { key: 'uncheck', value: function uncheck(shallow) { this._tree.batch(); // Will we apply this state change to our children? var deep = !shallow && this._tree.config.checkbox.autoCheckChildren; baseStateChange('checked', false, 'unchecked', this, deep); // Reset indeterminate state this.state('indeterminate', false); // Refresh our parent if (this.hasParent()) { this.getParent().refreshIndeterminateState(); } this._tree.end(); return this; } }, { key: 'visible', /** * Get whether node is visible to a user. Returns false * if it's hidden, or if any ancestor is hidden or collapsed. * * @return {boolean} Whether visible. */ value: function visible() { var isVisible = true; if (this.hidden() || this.removed() || this._tree.usesNativeDOM && !this.rendered()) { isVisible = false; } else if (this.hasParent()) { if (this.getParent().collapsed()) { isVisible = false; } else { isVisible = this.getParent().visible(); } } else { isVisible = true; } return isVisible; } }]); return TreeNode; }(); /** * Parse a raw object into a TreeNode used within a tree. * * Note: Uses native js over lodash where performance * benefits most, since this handles every node. * * @private * @param {object} tree Tree instance. * @param {object} object Source object * @param {object} parent Pointer to parent object. * @return {object} Final object */ function objectToNode(tree, object, parent) { // Create or type-ensure ID object.id = object.id || v4_1(); if (typeof object.id !== 'string' && typeof object.id !== 'number') { object.id = object.id.toString(); } // High-performance default assignments var itree = object.itree = object.itree || {}; itree.icon = itree.icon || false; itree.dirty = false; var li = itree.li = itree.li || {}; li.attributes = li.attributes || {}; var a = itree.a = itree.a || {}; a.attributes = a.attributes || {}; var state = itree.state = itree.state || {}; // Enabled by default state.collapsed = typeof state.collapsed === 'boolean' ? state.collapsed : tree.defaultState.collapsed; state.selectable = typeof state.selectable === 'boolean' ? state.selectable : tree.defaultState.selectable; state.draggable = typeof state.draggable === 'boolean' ? state.draggable : tree.defaultState.draggable; state['drop-target'] = typeof state['drop-target'] === 'boolean' ? state['drop-target'] : tree.defaultState['drop-target']; // Disabled by default state.checked = typeof state.checked === 'boolean' ? state.checked : false; state.editable = typeof state.editable === 'boolean' ? state.editable : tree.defaultState.editable; state.editing = typeof state.editing === 'boolean' ? state.editing : tree.defaultState.editing; state.focused = state.focused || tree.defaultState.focused; state.hidden = state.hidden || tree.defaultState.hidden; state.indeterminate = state.indeterminate || tree.defaultState.indeterminate; state.loading = state.loading || tree.defaultState.loading; state.removed = state.removed || tree.defaultState.removed; state.rendered = state.rendered || tree.defaultState.rendered; state.selected = state.selected || tree.defaultState.selected; // Save parent, if any. object.itree.parent = parent; // Wrap object = _.assign(new TreeNode(tree), object); if (_.isArrayLike(object.children)) { object.children = collectionToModel(tree, object.children, object); } // Fire events for pre-set states, if enabled if (tree.allowsLoadEvents) { _.each(tree.config.allowLoadEvents, function (eventName) { if (state[eventName]) { tree.emit('node.' + eventName, object, true); } }); } return object; } /** * Parses a raw collection of objects into a model used * within a tree. Adds state and other internal properties. * * @private * @param {object} tree Tree instance. * @param {array} array Array of nodes * @param {object} parent Pointer to parent object * @return {array|object} Object model. */ function collectionToModel(tree, array, parent) { var collection = new TreeNodes(tree, null, { calculateRenderablePositions: true }); collection.batch(); // Sort if (tree.config.sort) { array = _.sortBy(array, tree.config.sort); } _.each(array, function (node) { collection.push(objectToNode(tree, node, parent)); }); collection._context = parent; collection.end(); return collection; } var eventemitter2 = createCommonjsModule(function (module, exports) { !function(undefined) { var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; var defaultMaxListeners = 10; function init() { this._events = {}; if (this._conf) { configure.call(this, this._conf); } } function configure(conf) { if (conf) { this._conf = conf; conf.delimiter && (this.delimiter = conf.delimiter); this._maxListeners = conf.maxListeners !== undefined ? conf.maxListeners : defaultMaxListeners; conf.wildcard && (this.wildcard = conf.wildcard); conf.newListener && (this._newListener = conf.newListener); conf.removeListener && (this._removeListener = conf.removeListener); conf.verboseMemoryLeak && (this.verboseMemoryLeak = conf.verboseMemoryLeak); if (this.wildcard) { this.listenerTree = {}; } } else { this._maxListeners = defaultMaxListeners; } } function logPossibleMemoryLeak(count, eventName) { var errorMsg = '(node) warning: possible EventEmitter memory ' + 'leak detected. ' + count + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.'; if(this.verboseMemoryLeak){ errorMsg += ' Event name: ' + eventName + '.'; } if(typeof process !== 'undefined' && process.emitWarning){ var e = new Error(errorMsg); e.name = 'MaxListenersExceededWarning'; e.emitter = this; e.count = count; process.emitWarning(e); } else { console.error(errorMsg); if (console.trace){ console.trace(); } } } function EventEmitter(conf) { this._events = {}; this._newListener = false; this._removeListener = false; this.verboseMemoryLeak = false; configure.call(this, conf); } EventEmitter.EventEmitter2 = EventEmitter; // backwards compatibility for exporting EventEmitter property // // Attention, function return type now is array, always ! // It has zero elements if no any matches found and one or more // elements (leafs) if there are matches // function searchListenerTree(handlers, type, tree, i) { if (!tree) { return []; } var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, typeLength = type.length, currentType = type[i], nextType = type[i+1]; if (i === typeLength && tree._listeners) { // // If at the end of the event(s) list and the tree has listeners // invoke those listeners. // if (typeof tree._listeners === 'function') { handlers && handlers.push(tree._listeners); return [tree]; } else { for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { handlers && handlers.push(tree._listeners[leaf]); } return [tree]; } } if ((currentType === '*' || currentType === '**') || tree[currentType]) { // // If the event emitted is '*' at this part // or there is a concrete match at this patch // if (currentType === '*') { for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); } } return listeners; } else if(currentType === '**') { endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); if(endReached && tree._listeners) { // The next element has a _listeners, add it to the handlers. listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); } for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { if(branch === '*' || branch === '**') { if(tree[branch]._listeners && !endReached) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); } listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } else if(branch === nextType) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); } else { // No match on this one, shift into the tree but not in the type array. listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } } } return listeners; } listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); } xTree = tree['*']; if (xTree) { // // If the listener tree will allow any match for this part, // then recursively explore all branches of the tree // searchListenerTree(handlers, type, xTree, i+1); } xxTree = tree['**']; if(xxTree) { if(i < typeLength) { if(xxTree._listeners) { // If we have a listener on a '**', it will catch all, so add its handler. searchListenerTree(handlers, type, xxTree, typeLength); } // Build arrays of matching next branches and others. for(branch in xxTree) { if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { if(branch === nextType) { // We know the next element will match, so jump twice. searchListenerTree(handlers, type, xxTree[branch], i+2); } else if(branch === currentType) { // Current node matches, move into the tree. searchListenerTree(handlers, type, xxTree[branch], i+1); } else { isolatedBranch = {}; isolatedBranch[branch] = xxTree[branch]; searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); } } } } else if(xxTree._listeners) { // We have reached the end and still on a '**' searchListenerTree(handlers, type, xxTree, typeLength); } else if(xxTree['*'] && xxTree['*']._listeners) { searchListenerTree(handlers, type, xxTree['*'], typeLength); } } return listeners; } function growListenerTree(type, listener) { type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); // // Looks for two consecutive '**', if so, don't add the event at all. // for(var i = 0, len = type.length; i+1 < len; i++) { if(type[i] === '**' && type[i+1] === '**') { return; } } var tree = this.listenerTree; var name = type.shift(); while (name !== undefined) { if (!tree[name]) { tree[name] = {}; } tree = tree[name]; if (type.length === 0) { if (!tree._listeners) { tree._listeners = listener; } else { if (typeof tree._listeners === 'function') { tree._listeners = [tree._listeners]; } tree._listeners.push(listener); if ( !tree._listeners.warned && this._maxListeners > 0 && tree._listeners.length > this._maxListeners ) { tree._listeners.warned = true; logPossibleMemoryLeak.call(this, tree._listeners.length, name); } } return true; } name = type.shift(); } return true; } // 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. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.delimiter = '.'; EventEmitter.prototype.setMaxListeners = function(n) { if (n !== undefined) { this._maxListeners = n; if (!this._conf) this._conf = {}; this._conf.maxListeners = n; } }; EventEmitter.prototype.event = ''; EventEmitter.prototype.once = function(event, fn) { return this._once(event, fn, false); }; EventEmitter.prototype.prependOnceListener = function(event, fn) { return this._once(event, fn, true); }; EventEmitter.prototype._once = function(event, fn, prepend) { this._many(event, 1, fn, prepend); return this; }; EventEmitter.prototype.many = function(event, ttl, fn) { return this._many(event, ttl, fn, false); }; EventEmitter.prototype.prependMany = function(event, ttl, fn) { return this._many(event, ttl, fn, true); }; EventEmitter.prototype._many = function(event, ttl, fn, prepend) { var self = this; if (typeof fn !== 'function') { throw new Error('many only accepts instances of Function'); } function listener() { if (--ttl === 0) { self.off(event, listener); } return fn.apply(this, arguments); } listener._origin = fn; this._on(event, listener, prepend); return self; }; EventEmitter.prototype.emit = function() { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener' && !this._newListener) { if (!this._events.newListener) { return false; } } var al = arguments.length; var args,l,i,j; var handler; if (this._all && this._all.length) { handler = this._all.slice(); if (al > 3) { args = new Array(al); for (j = 0; j < al; j++) args[j] = arguments[j]; } for (i = 0, l = handler.length; i < l; i++) { this.event = type; switch (al) { case 1: handler[i].call(this, type); break; case 2: handler[i].call(this, type, arguments[1]); break; case 3: handler[i].call(this, type, arguments[1], arguments[2]); break; default: handler[i].apply(this, args); } } } if (this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; if (typeof handler === 'function') { this.event = type; switch (al) { case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; default: args = new Array(al - 1); for (j = 1; j < al; j++) args[j - 1] = arguments[j]; handler.apply(this, args); } return true; } else if (handler) { // need to make copy of handlers because list can change in the middle // of emit call handler = handler.slice(); } } if (handler && handler.length) { if (al > 3) { args = new Array(al - 1); for (j = 1; j < al; j++) args[j - 1] = arguments[j]; } for (i = 0, l = handler.length; i < l; i++) { this.event = type; switch (al) { case 1: handler[i].call(this); break; case 2: handler[i].call(this, arguments[1]); break; case 3: handler[i].call(this, arguments[1], arguments[2]); break; default: handler[i].apply(this, args); } } return true; } else if (!this._all && type === 'error') { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } return !!this._all; }; EventEmitter.prototype.emitAsync = function() { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener' && !this._newListener) { if (!this._events.newListener) { return Promise.resolve([false]); } } var promises= []; var al = arguments.length; var args,l,i,j; var handler; if (this._all) { if (al > 3) { args = new Array(al); for (j = 1; j < al; j++) args[j] = arguments[j]; } for (i = 0, l = this._all.length; i < l; i++) { this.event = type; switch (al) { case 1: promises.push(this._all[i].call(this, type)); break; case 2: promises.push(this._all[i].call(this, type, arguments[1])); break; case 3: promises.push(this._all[i].call(this, type, arguments[1], arguments[2])); break; default: promises.push(this._all[i].apply(this, args)); } } } if (this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; } if (typeof handler === 'function') { this.event = type; switch (al) { case 1: promises.push(handler.call(this)); break; case 2: promises.push(handler.call(this, arguments[1])); break; case 3: promises.push(handler.call(this, arguments[1], arguments[2])); break; default: args = new Array(al - 1); for (j = 1; j < al; j++) args[j - 1] = arguments[j]; promises.push(handler.apply(this, args)); } } else if (handler && handler.length) { handler = handler.slice(); if (al > 3) { args = new Array(al - 1); for (j = 1; j < al; j++) args[j - 1] = arguments[j]; } for (i = 0, l = handler.length; i < l; i++) { this.event = type; switch (al) { case 1: promises.push(handler[i].call(this)); break; case 2: promises.push(handler[i].call(this, arguments[1])); break; case 3: promises.push(handler[i].call(this, arguments[1], arguments[2])); break; default: promises.push(handler[i].apply(this, args)); } } } else if (!this._all && type === 'error') { if (arguments[1] instanceof Error) { return Promise.reject(arguments[1]); // Unhandled 'error' event } else { return Promise.reject("Uncaught, unspecified 'error' event."); } } return Promise.all(promises); }; EventEmitter.prototype.on = function(type, listener) { return this._on(type, listener, false); }; EventEmitter.prototype.prependListener = function(type, listener) { return this._on(type, listener, true); }; EventEmitter.prototype.onAny = function(fn) { return this._onAny(fn, false); }; EventEmitter.prototype.prependAny = function(fn) { return this._onAny(fn, true); }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prototype._onAny = function(fn, prepend){ if (typeof fn !== 'function') { throw new Error('onAny only accepts instances of Function'); } if (!this._all) { this._all = []; } // Add the function to the event listener collection. if(prepend){ this._all.unshift(fn); }else{ this._all.push(fn); } return this; }; EventEmitter.prototype._on = function(type, listener, prepend) { if (typeof type === 'function') { this._onAny(type, listener); return this; } if (typeof listener !== 'function') { throw new Error('on only accepts instances of Function'); } this._events || init.call(this); // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". if (this._newListener) this.emit('newListener', type, listener); if (this.wildcard) { growListenerTree.call(this, type, listener); return this; } if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else { if (typeof this._events[type] === 'function') { // Change to array. this._events[type] = [this._events[type]]; } // If we've already got an array, just add if(prepend){ this._events[type].unshift(listener); }else{ this._events[type].push(listener); } // Check for listener leak if ( !this._events[type].warned && this._maxListeners > 0 && this._events[type].length > this._maxListeners ) { this._events[type].warned = true; logPossibleMemoryLeak.call(this, this._events[type].length, type); } } return this; }; EventEmitter.prototype.off = function(type, listener) { if (typeof listener !== 'function') { throw new Error('removeListener only takes instances of Function'); } var handlers,leafs=[]; if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); } else { // does not use listeners(), so no side effect of creating _events[type] if (!this._events[type]) return this; handlers = this._events[type]; leafs.push({_listeners:handlers}); } for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; handlers = leaf._listeners; if (isArray(handlers)) { var position = -1; for (var i = 0, length = handlers.length; i < length; i++) { if (handlers[i] === listener || (handlers[i].listener && handlers[i].listener === listener) || (handlers[i]._origin && handlers[i]._origin === listener)) { position = i; break; } } if (position < 0) { continue; } if(this.wildcard) { leaf._listeners.splice(position, 1); } else { this._events[type].splice(position, 1); } if (handlers.length === 0) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } if (this._removeListener) this.emit("removeListener", type, listener); return this; } else if (handlers === listener || (handlers.listener && handlers.listener === listener) || (handlers._origin && handlers._origin === listener)) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } if (this._removeListener) this.emit("removeListener", type, listener); } } function recursivelyGarbageCollect(root) { if (root === undefined) { return; } var keys = Object.keys(root); for (var i in keys) { var key = keys[i]; var obj = root[key]; if ((obj instanceof Function) || (typeof obj !== "object") || (obj === null)) continue; if (Object.keys(obj).length > 0) { recursivelyGarbageCollect(root[key]); } if (Object.keys(obj).length === 0) { delete root[key]; } } } recursivelyGarbageCollect(this.listenerTree); return this; }; EventEmitter.prototype.offAny = function(fn) { var i = 0, l = 0, fns; if (fn && this._all && this._all.length > 0) { fns = this._all; for(i = 0, l = fns.length; i < l; i++) { if(fn === fns[i]) { fns.splice(i, 1); if (this._removeListener) this.emit("removeListenerAny", fn); return this; } } } else { fns = this._all; if (this._removeListener) { for(i = 0, l = fns.length; i < l; i++) this.emit("removeListenerAny", fns[i]); } this._all = []; } return this; }; EventEmitter.prototype.removeListener = EventEmitter.prototype.off; EventEmitter.prototype.removeAllListeners = function(type) { if (type === undefined) { !this._events || init.call(this); return this; } if (this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; leaf._listeners = null; } } else if (this._events) { this._events[type] = null; } return this; }; EventEmitter.prototype.listeners = function(type) { if (this.wildcard) { var handlers = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); return handlers; } this._events || init.call(this); if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; }; EventEmitter.prototype.eventNames = function(){ return Object.keys(this._events); }; EventEmitter.prototype.listenerCount = function(type) { return this.listeners(type).length; }; EventEmitter.prototype.listenersAny = function() { if(this._all) { return this._all; } else { return []; } }; if (typeof undefined === 'function' && undefined.amd) { // AMD. Register as an anonymous module. undefined(function() { return EventEmitter; }); } else { // CommonJS module.exports = EventEmitter; } }(); }); var eventemitter2_1 = eventemitter2.EventEmitter2; // Libs /** * Maps a method to the root TreeNodes collection. * * @private * @param {InspireTree} tree Tree instance. * @param {string} method Method name. * @param {arguments} args Proxied arguments. * @return {mixed} Proxied return value. */ function _map(tree, method, args) { return tree.model[method].apply(tree.model, args); } /** * Represents a singe tree instance. * * @return {InspireTree} Tree instance. */ var InspireTree = function (_EventEmitter) { inherits(InspireTree, _EventEmitter); function InspireTree(opts) { classCallCheck(this, InspireTree); var _this = possibleConstructorReturn(this, (InspireTree.__proto__ || Object.getPrototypeOf(InspireTree)).call(this)); var tree = _this; // Init properties tree._lastSelectedNode; tree._muted = false; tree.allowsLoadEvents = false; tree.id = v4_1(); tree.initialized = false; tree.isDynamic = false; tree.opts = opts; tree.preventDeselection = false; // Assign defaults tree.config = _.defaultsDeep({}, opts, { allowLoadEvents: [], checkbox: { autoCheckChildren: true }, contextMenu: false, data: false, editable: false, editing: { add: false, edit: false, remove: false }, nodes: { resetStateOnRestore: true }, pagination: { limit: -1 }, search: { matcher: false, matchProcessor: false }, selection: { allow: _.noop, autoDeselect: true, autoSelectChildren: false, disableDirectDeselection: false, mode: 'default', multiple: false, require: false }, showCheckboxes: false, sort: false }); // If checkbox mode, we must force auto-selecting children if (tree.config.selection.mode === 'checkbox') { tree.config.selection.autoSelectChildren = true; // In checkbox mode, checked=selected tree.on('node.checked', function (node) { if (!node.selected()) { node.select(true); } }); tree.on('node.selected', function (node) { if (!node.checked()) { node.check(true); } }); tree.on('node.unchecked', function (node) { if (node.selected()) { node.deselect(true); } }); tree.on('node.deselected', function (node) { if (node.checked()) { node.uncheck(true); } }); } // If auto-selecting children, we must force multiselect if (tree.config.selection.autoSelectChildren) { tree.config.selection.multiple = true; tree.config.selection.autoDeselect = false; } // Treat editable as full edit mode if (opts.editable && !opts.editing) { tree.config.editing.add = true; tree.config.editing.edit = true; tree.config.editing.remove = true; } // Support simple config for search if (_.isFunction(opts.search)) { tree.config.search = { matcher: opts.search, matchProcessor: false }; } // Init the default state for nodes tree.defaultState = { collapsed: true, editable: _.get(tree, 'config.editing.edit'), editing: false, draggable: true, 'drop-target': true, focused: false, hidden: false, indeterminate: false, loading: false, matched: false, removed: false, rendered: false, selectable: true, selected: false }; // Cache some configs tree.allowsLoadEvents = _.isArray(tree.config.allowLoadEvents) && tree.config.allowLoadEvents.length > 0; tree.isDynamic = _.isFunction(tree.config.data); // Override emitter so we can better control flow var emit = tree.emit; tree.emit = function (eventName) { if (!tree.isEventMuted(eventName)) { // Duck-type for a DOM event if (_.isFunction(_.get(arguments, '[1].preventDefault'))) { var event = arguments[1]; event.treeDefaultPrevented = false; event.preventTreeDefault = function () { event.treeDefaultPrevented = true; }; } emit.apply(tree, arguments); } }; // Init the model tree.model = new TreeNodes(tree); // Load initial user data if (tree.config.data) { tree.load(tree.config.data); } tree.initialized = true; return _this; } /** * Adds a new node. If a sort method is configured, * the node will be added in the appropriate order. * * @param {object} node Node * @return {TreeNode} Node object. */ createClass(InspireTree, [{ key: 'addNode', value: function addNode() { return _map(this, 'addNode', arguments); } /** * Add nodes. * * @param {array} nodes Array of node objects. * @return {TreeNodes} Added node objects. */ }, { key: 'addNodes', value: function addNodes(nodes) { var _this2 = this; this.batch(); var newNodes = new TreeNodes(this); _.each(nodes, function (node) { return newNodes.push(_this2.addNode(node)); }); this.end(); return newNodes; } /** * Release pending data changes to any listeners. * * Will skip rendering as long as any calls * to `batch` have yet to be resolved, * * @private * @return {void} */ }, { key: 'applyChanges', value: function applyChanges() { return this.model.applyChanges(); } /** * Query for all available nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'available', value: function available() { return _map(this, 'available', arguments); } /** * Batch multiple changes for listeners (i.e. DOM) * * @private * @return {void} */ }, { key: 'batch', value: function batch() { return this.model.batch(); } /** * Blur children in this collection. * * @return {TreeNodes} Array of node objects. */ }, { key: 'blur', value: function blur() { return _map(this, 'blur', arguments); } /** * Blur (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'blurDeep', value: function blurDeep() { return _map(this, 'blurDeep', arguments); } /** * Compares any number of TreeNode objects and returns * the minimum and maximum (starting/ending) nodes. * * @return {array} Array with two TreeNode objects. */ }, { key: 'boundingNodes', value: function boundingNodes() { var pathMap = _.transform(arguments, function (map, node) { map[node.indexPath().replace(/\./g, '')] = node; }, {}); var _$sortBy = _.sortBy(Object.keys(pathMap)), _$sortBy2 = toArray(_$sortBy), head = _$sortBy2[0], tail = _$sortBy2.slice(1); return [_.get(pathMap, head), _.get(pathMap, tail)]; } /** * Check if the tree will auto-deselect currently selected nodes * when a new selection is made. * * @return {boolean} If tree will auto-deselect nodes. */ }, { key: 'canAutoDeselect', value: function canAutoDeselect() { return this.config.selection.autoDeselect && !this.preventDeselection; } /** * Query for all checked nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'checked', value: function checked() { return _map(this, 'checked', arguments); } /** * Clean nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'clean', value: function clean() { return _map(this, 'clean', arguments); } /** * Clear nodes matched by previous search, restore all nodes and collapse parents. * * @return {Tree} Tree instance. */ }, { key: 'clearSearch', value: function clearSearch() { this.batch(); this.recurseDown(function (node) { // Reset search effects (show node, collapse, reset matched) node.show().collapse().state('matched', false); }); this.end(); return this; } /** * Clones (deeply) the array of nodes. * * Note: Cloning will *not* clone the context pointer. * * @return {TreeNodes} Array of cloned nodes. */ }, { key: 'clone', value: function clone() { return _map(this, 'clone', arguments); } /** * Collapse nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'collapse', value: function collapse() { return _map(this, 'collapse', arguments); } /** * Query for all collapsed nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'collapsed', value: function collapsed() { return _map(this, 'collapsed', arguments); } /** * Collapse (deeply) all children. * * @return {TreeNodes} Array of node objects. */ }, { key: 'collapseDeep', value: function collapseDeep() { return _map(this, 'collapseDeep', arguments); } /** * Concat multiple TreeNodes arrays. * * @param {TreeNodes} nodes Array of nodes. * @return {TreeNodes} Resulting node array. */ }, { key: 'concat', value: function concat() { return _map(this, 'concat', arguments); } /** * Copy nodes to another tree instance. * * @param {boolean} hierarchy Include necessary ancestors to match hierarchy. * @return {object} Methods to perform action on copied nodes. */ }, { key: 'copy', value: function copy() { return _map(this, 'copy', arguments); } /** * Creates a TreeNode without adding it. If the obj is already a TreeNode it's returned without modification. * * @param {object} obj Source node object. * @return {TreeNode} Node object. */ }, { key: 'createNode', value: function createNode(obj) { return InspireTree.isTreeNode(obj) ? obj : objectToNode(this, obj); } /** * Return deepest nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'deepest', value: function deepest() { return _map(this, 'deepest', arguments); } /** * Deselect nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'deselect', value: function deselect() { return _map(this, 'deselect', arguments); } /** * Deselect (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'deselectDeep', value: function deselectDeep() { return _map(this, 'deselectDeep', arguments); } /** * Disable auto-deselection of currently selected nodes. * * @return {Tree} Tree instance. */ }, { key: 'disableDeselection', value: function disableDeselection() { if (this.config.selection.multiple) { this.preventDeselection = true; } return this; } /** * Iterate each TreeNode. * * @param {function} iteratee Iteratee invoke for each node. * @return {TreeNodes} Array of node objects. */ }, { key: 'each', value: function each() { return _map(this, 'each', arguments); } /** * Query for all editable nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'editable', value: function editable() { return _map(this, 'editable', arguments); } /** * Query for all nodes in editing mode. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'editing', value: function editing() { return _map(this, 'editing', arguments); } /** * Enable auto-deselection of currently selected nodes. * * @return {Tree} Tree instance. */ }, { key: 'enableDeselection', value: function enableDeselection() { this.preventDeselection = false; return this; } /** * Release the current batch. * * @private * @return {void} */ }, { key: 'end', value: function end() { return this.model.end(); } /** * Check if every node passes the given test. * * @param {function} tester Test each node in this collection, * @return {boolean} True if every node passes the test. */ }, { key: 'every', value: function every() { return _map(this, 'every', arguments); } /** * Expand children. * * @return {TreeNodes} Array of node objects. */ }, { key: 'expand', value: function expand() { return _map(this, 'expand', arguments); } /** * Expand (deeply) all nodes. * * @return {Promise<TreeNodes>} Promise resolved when all children have loaded and expanded. */ }, { key: 'expandDeep', value: function expandDeep() { return _map(this, 'expandDeep', arguments); } /** * Query for all expanded nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'expanded', value: function expanded() { return _map(this, 'expanded', arguments); } /** * Clone a hierarchy of all nodes matching a predicate. * * Because it filters deeply, we must clone all nodes so that we * don't affect the actual node array. * * @param {string|function} predicate State flag or custom function. * @return {TreeNodes} Array of node objects. */ }, { key: 'extract', value: function extract() { return _map(this, 'extract', arguments); } /** * Filter all nodes matching the given predicate. * * @param {function} predicate Test function. * @return {TreeNodes} Array of node objects. */ }, { key: 'filter', value: function filter() { return _map(this, 'filter', arguments); } /** * Filter all nodes matching the given predicate. * * @param {string|function} predicate State flag or custom function. * @return {TreeNodes} Array of node objects. */ }, { key: 'filterBy', value: function filterBy() { return _map(this, 'filterBy', arguments); } /** * Returns the first node matching predicate. * * @param {function} predicate Predicate function, accepts a single node and returns a boolean. * @return {TreeNode} First matching TreeNode, or undefined. */ }, { key: 'find', value: function find() { return _map(this, 'find', arguments); } /** * Returns the first shallow node matching predicate. * * @param {function} predicate Predicate function, accepts a single node and returns a boolean. * @return {TreeNode} First matching TreeNode, or undefined. */ }, { key: 'first', value: function first() { return _map(this, 'first', arguments); } /** * Flatten and get only node(s) matching the expected state or predicate function. * * @param {string|function} predicate State property or custom function. * @return {TreeNodes} Flat array of matching nodes. */ }, { key: 'flatten', value: function flatten() { return _map(this, 'flatten', arguments); } /** * Query for all focused nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'focused', value: function focused() { return _map(this, 'focused', arguments); } /** * Iterate each TreeNode. * * @param {function} iteratee Iteratee invoke for each node. * @return {TreeNodes} Array of node objects. */ }, { key: 'forEach', value: function forEach() { return _map(this, 'each', arguments); } /** * Get a specific node by its index, or undefined if it doesn't exist. * * @param {int} index Numeric index of requested node. * @return {TreeNode} Node object. Undefined if invalid index. */ }, { key: 'get', value: function get$$1() { return _map(this, 'get', arguments); } /** * Query for all hidden nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'hidden', value: function hidden() { return _map(this, 'hidden', arguments); } /** * Hide nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'hide', value: function hide() { return _map(this, 'hide', arguments); } /** * Hide (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'hideDeep', value: function hideDeep() { return _map(this, 'hideDeep', arguments); } /** * Query for all indeterminate nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'indeterminate', value: function indeterminate() { return _map(this, 'indeterminate', arguments); } /** * Get the index of the given node. * * @param {TreeNode} node Root tree node. * @return {int} Index of the node. */ }, { key: 'indexOf', value: function indexOf() { return _map(this, 'indexOf', arguments); } /** * Insert a new node at the given position. * * @param {integer} index Index at which to insert the node. * @param {object} object Raw node object or TreeNode. * @return {TreeNode} Node object. */ }, { key: 'insertAt', value: function insertAt() { return _map(this, 'insertAt', arguments); } /** * Invoke method(s) on each node. * * @param {string|array} methods Method name(s). * @return {TreeNodes} Array of node objects. */ }, { key: 'invoke', value: function invoke() { return _map(this, 'invoke', arguments); } /** * Invoke method(s) deeply. * * @param {string|array} methods Method name(s). * @return {TreeNodes} Array of node objects. */ }, { key: 'invokeDeep', value: function invokeDeep() { return _map(this, 'invokeDeep', arguments); } /** * Check if an event is currently muted. * * @param {string} eventName Event name. * @return {boolean} If event is muted. */ }, { key: 'isEventMuted', value: function isEventMuted(eventName) { if (_.isBoolean(this.muted())) { return this.muted(); } return _.includes(this.muted(), eventName); } /** * Check if an object is a Tree. * * @param {object} object Object * @return {boolean} If object is a Tree. */ }, { key: 'isTree', value: function isTree(object) { return object instanceof InspireTree; } /** * Check if an object is a TreeNode. * * @param {object} obj Object * @return {boolean} If object is a TreeNode. */ }, { key: 'join', /** * Join nodes into a resulting string. * * @param {string} separator Separator, defaults to a comma * @return {string} Strings from root node objects. */ value: function join() { return _map(this, 'join', arguments); } /** * Returns the last shallow node matching predicate. * * @param {function} predicate Predicate function, accepts a single node and returns a boolean. * @return {TreeNode} Last matching shallow TreeNode, or undefined. */ }, { key: 'last', value: function last() { return _map(this, 'last', arguments); } /** * Get the most recently selected node, if any. * * @return {TreeNode} Last selected node, or undefined. */ }, { key: 'lastSelectedNode', value: function lastSelectedNode() { return this._lastSelectedNode; } /** * Load data. Accepts an array, function, or promise. * * @param {array|function|Promise} loader Array of nodes, function, or promise resolving an array of nodes. * @return {Promise<TreeNodes>} Promise resolved upon successful load, rejected on error. * @example * * tree.load($.getJSON('nodes.json')); */ }, { key: 'load', value: function load(loader) { var _this3 = this; var promise = new es6Promise_1(function (resolve, reject) { var complete = function complete(nodes, totalNodes) { // A little type-safety for silly situations if (!_.isArrayLike(nodes)) { return reject(new TypeError('Loader requires an array-like `nodes` parameter.')); } // Delay event for synchronous loader. Otherwise it fires // before the user has a chance to listen. if (!_this3.initialized && _.isArrayLike(nodes)) { setTimeout(function () { _this3.emit('data.loaded', nodes); }); } else { _this3.emit('data.loaded', nodes); } // Parse newly-loaded nodes var newModel = collectionToModel(_this3, nodes); // Concat only if loading is deferred if (_this3.config.deferredLoading) { _this3.model = _this3.model.concat(newModel); } else { _this3.model = newModel; } // Set pagination _this3.model._pagination.total = nodes.length; if (_.parseInt(totalNodes) > nodes.length) { _this3.model._pagination.total = _.parseInt(totalNodes); } // Set pagination totals if resolver failed to provide them if (!totalNodes) { _this3.model.recurseDown(function (node) { if (node.hasChildren()) { node.children._pagination.total = node.children.length; } }); } if (_this3.config.selection.require && !_this3.selected().length) { _this3.selectFirstAvailableNode(); } var init = function init() { _this3.emit('model.loaded', _this3.model); resolve(_this3.model); _this3.model.applyChanges(); }; // Delay event for synchronous loader if (!_this3.initialized && _.isArray(nodes)) { setTimeout(init); } else { init(); } }; // Data given already as an array if (_.isArrayLike(loader)) { complete(loader); } // Data loader requires a caller/callback else if (_.isFunction(loader)) { var resp = loader(null, complete, reject, _this3.pagination()); // Loader returned its own object if (resp) { loader = resp; } } // Data loader is likely a promise if (_.isObject(loader)) { standardizePromise(loader).then(complete).catch(reject); } else { error(new Error('Invalid data loader.')); } }); // Copy to event listeners promise.catch(function (err) { _this3.emit('data.loaderror', err); }); // Cache to allow access after tree instantiation this._loader = { promise: promise }; return promise; } /** * Query for all nodes currently loading children. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'loading', value: function loading() { return _map(this, 'loading', arguments); } /** * Load additional nodes for the root context. * * @param {Event} event Click or scroll event if DOM interaction triggered this call. * @return {Promise<TreeNodes>} Resolves with request results. */ }, { key: 'loadMore', value: function loadMore() { return _map(this, 'loadMore', arguments); } /** * Create a new collection after passing every node through iteratee. * * @param {function} iteratee Node iteratee. * @return {TreeNodes} New array of node objects. */ }, { key: 'map', value: function map() { return _map(this, 'map', arguments); } /** * Query for all nodes matched in the last search. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'matched', value: function matched() { return _map(this, 'matched', arguments); } /** * Move node at a given index to a new index. * * @param {int} index Current index. * @param {int} newIndex New index. * @param {TreeNodes} target Target TreeNodes array. Defaults to this. * @return {TreeNode} Node object. */ }, { key: 'move', value: function move() { return _map(this, 'move', arguments); } /** * Pause events. * * @param {array} events Event names to mute. * @return {Tree} Tree instance. */ }, { key: 'mute', value: function mute(events) { if (_.isString(events) || _.isArray(events)) { this._muted = _.castArray(events); } else { this._muted = true; } return this; } /** * Get current mute settings. * * @return {boolean|array} Muted events. If all, true. */ }, { key: 'muted', value: function muted() { return this._muted; } /** * Get a node. * * @param {string|number} id ID of node. * @return {TreeNode} Node object. */ }, { key: 'node', value: function node() { return _map(this, 'node', arguments); } /** * Get all nodes in a tree, or nodes for an array of IDs. * * @param {array} refs Array of ID references. * @return {TreeNodes} Array of node objects. * @example * * let all = tree.nodes() * let some = tree.nodes([1, 2, 3]) */ }, { key: 'nodes', value: function nodes() { return _map(this, 'nodes', arguments); } /** * Get the root TreeNodes pagination. * * @return {object} Pagination configuration object. */ }, { key: 'pagination', value: function pagination() { return _map(this, 'pagination', arguments); } /** * Pop node in the final index position. * * @return {TreeNode} Node object. */ }, { key: 'pop', value: function pop() { return _map(this, 'pop', arguments); } /** * Add a TreeNode to the end of the root collection. * * @param {TreeNode} node Node object. * @return {int} The new length */ }, { key: 'push', value: function push() { return _map(this, 'push', arguments); } /** * Iterate down all nodes and any children. * * Return false to stop execution. * * @private * @param {function} iteratee Iteratee function * @return {TreeNodes} Resulting nodes. */ }, { key: 'recurseDown', value: function recurseDown() { return _map(this, 'recurseDown', arguments); } /** * Reduce nodes. * * @param {function} iteratee Iteratee function * @return {any} Resulting data. */ }, { key: 'reduce', value: function reduce() { return _map(this, 'reduce', arguments); } /** * Right-reduce root nodes. * * @param {function} iteratee Iteratee function * @return {any} Resulting data. */ }, { key: 'reduceRight', value: function reduceRight() { return _map(this, 'reduceRight', arguments); } /** * Reload/re-execute the original data loader. * * @return {Promise<TreeNodes>} Load method promise. */ }, { key: 'reload', value: function reload() { this.removeAll(); return this.load(this.opts.data || this.config.data); } /** * Remove a node. * * @param {TreeNode} node Node object. * @return {TreeNodes} Array of node objects. */ }, { key: 'remove', value: function remove() { return _map(this, 'remove', arguments); } /** * Remove all nodes. * * @return {Tree} Tree instance. */ }, { key: 'removeAll', value: function removeAll() { this.model = new TreeNodes(this); this.applyChanges(); return this; } /** * Query for all soft-removed nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'removed', value: function removed() { return _map(this, 'removed', arguments); } /** * Restore nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'restore', value: function restore() { return _map(this, 'restore', arguments); } /** * Restore (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'restoreDeep', value: function restoreDeep() { return _map(this, 'restoreDeep', arguments); } /** * Reverse node order. * * @return {TreeNodes} Reversed array of node objects. */ }, { key: 'reverse', value: function reverse() { return _map(this, 'reverse', arguments); } /** * Search nodes, showing only those that match and the necessary hierarchy. * * @param {*} query Search string, RegExp, or function. * @return {Promise<TreeNodes>} Promise resolved with an array of matching node objects. */ }, { key: 'search', value: function search(query) { var _this4 = this; var _config$search = this.config.search, matcher = _config$search.matcher, matchProcessor = _config$search.matchProcessor; // Don't search if query empty if (!query || _.isString(query) && _.isEmpty(query)) { return es6Promise_1.resolve(this.clearSearch()); } this.batch(); // Reset states this.recurseDown(function (node) { node.state('hidden', true); node.state('matched', false); }); this.end(); // Query nodes for any matching the query matcher = _.isFunction(matcher) ? matcher : function (query, resolve) { var matches = new TreeNodes(_this4); // Convery the query into a usable predicate if (_.isString(query)) { query = new RegExp(query, 'i'); } var predicate = void 0; if (_.isRegExp(query)) { predicate = function predicate(node) { return query.test(node.text); }; } else { predicate = query; } // Recurse down and find all matches _this4.model.recurseDown(function (node) { if (!node.removed()) { if (predicate(node)) { // Return as a match matches.push(node); } } }); resolve(matches); }; // Process all matching nodes. matchProcessor = _.isFunction(matchProcessor) ? matchProcessor : function (matches) { matches.each(function (node) { node.show().state('matched', true); node.expandParents().collapse(); if (node.hasChildren()) { node.children.showDeep(); } }); }; // Wrap the search matcher with a promise since it could require async requests return new es6Promise_1(function (resolve, reject) { // Execute the matcher and pipe results to the processor matcher(query, function (matches) { // Convert to a TreeNodes array if we're receiving external nodes if (!InspireTree.isTreeNodes(matches)) { matches = _this4.nodes(_.map(matches, 'id')); } _this4.batch(); matchProcessor(matches); _this4.end(); resolve(matches); }, reject); }); } /** * Select nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'select', value: function select() { return _map(this, 'select', arguments); } /** * Query for all selectable nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'selectable', value: function selectable() { return _map(this, 'selectable', arguments); } /** * Select all nodes between a start and end node. * Starting node must have a higher index path so we can work down to endNode. * * @param {TreeNode} startNode Starting node * @param {TreeNode} endNode Ending node * @return {Tree} Tree instance. */ }, { key: 'selectBetween', value: function selectBetween(startNode, endNode) { this.batch(); var node = startNode.nextVisibleNode(); while (node.id !== endNode.id) { node.select(); node = node.nextVisibleNode(); } this.end(); return this; } }, { key: 'selectDeep', /** * Select (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ value: function selectDeep() { return _map(this, 'selectDeep', arguments); } /** * Query for all selected nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'selected', value: function selected() { return _map(this, 'selected', arguments); } /** * Select the first available node. * * @return {TreeNode} Selected node object. */ }, { key: 'selectFirstAvailableNode', value: function selectFirstAvailableNode() { var node = this.model.filterBy('available').get(0); if (node) { node.select(); } return node; } }, { key: 'shift', /** * Shift node in the first index position. * * @return {TreeNode} Node object. */ value: function shift() { return _map(this, 'shift', arguments); } /** * Show nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'show', value: function show() { return _map(this, 'show', arguments); } /** * Show (deeply) all nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'showDeep', value: function showDeep() { return _map(this, 'showDeep', arguments); } /** * Get a shallow copy of a portion of nodes. * * @param {int} begin Starting index. * @param {int} end End index. * @return {Array} Array of selected subset. */ }, { key: 'slice', value: function slice() { return _map(this, 'slice', arguments); } /** * Soft-remove nodes. * * @return {TreeNodes} Array of node objects. */ }, { key: 'softRemove', value: function softRemove() { return _map(this, 'softRemove', arguments); } /** * Check if at least one node passes the given test. * * @param {function} tester Test each node in this collection, * @return {boolean} True if at least one node passes the test. */ }, { key: 'some', value: function some() { return _map(this, 'some', arguments); } /** * Sort nodes using a function. * * @param {function} compareFn Comparison function. * @return {TreeNodes} Root array of node objects. */ }, { key: 'sort', value: function sort() { return _map(this, 'sort', arguments); } /** * Sort nodes using a function or key name. * * If no custom sorter given, the configured "sort" value will be used. * * @param {string|function} sorter Sort function or property name. * @return {TreeNodes} Array of node obejcts. */ }, { key: 'sortBy', value: function sortBy() { return _map(this, 'sortBy', arguments); } /** * Deeply sort nodes. * * @param {function} compareFn Comparison function. * @return {TreeNodes} Root array of node objects. */ }, { key: 'sortDeep', value: function sortDeep() { return _map(this, 'sortDeep', arguments); } /** * Remove and/or add new TreeNodes into the root collection. * * @param {int} start Starting index. * @param {int} deleteCount Count of nodes to delete. * @param {TreeNode} node Node(s) to insert. * @return {Array} Array of selected subset. */ }, { key: 'splice', value: function splice() { return _map(this, 'slice', arguments); } /** * Set nodes' state values. * * @param {string} name Property name. * @param {boolean} newVal New value, if setting. * @return {TreeNodes} Array of node objects. */ }, { key: 'state', value: function state() { return _map(this, 'state', arguments); } /** * Set (deeply) nodes' state values. * * @param {string} name Property name. * @param {boolean} newVal New value, if setting. * @return {TreeNodes} Array of node objects. */ }, { key: 'stateDeep', value: function stateDeep() { return _map(this, 'stateDeep', arguments); } /** * Swap two node positions. * * @param {TreeNode} node1 Node 1. * @param {TreeNode} node2 Node 2. * @return {TreeNodes} Array of node objects. */ }, { key: 'swap', value: function swap() { return _map(this, 'swap', arguments); } /** * Get a native node Array. * * @return {array} Array of node objects. */ }, { key: 'toArray', value: function toArray$$1() { return _map(this, 'toArray', arguments); } /** * Get a string representation of node objects. * * @return {string} Strings from root node objects. */ }, { key: 'toString', value: function toString() { return _map(this, 'toString', arguments); } /** * Resume events. * * @param {array} events Events to unmute. * @return {Tree} Tree instance. */ }, { key: 'unmute', value: function unmute(events) { // Diff array and set to false if we're now empty if (_.isString(events) || _.isArray(events)) { this._muted = _.difference(this._muted, _.castArray(events)); if (!this._muted.length) { this._muted = false; } } else { this._muted = false; } return this; } }, { key: 'unshift', /** * Add a TreeNode in the first index position. * * @return {number} The new length */ value: function unshift() { return _map(this, 'unshift', arguments); } /** * Query for all visible nodes. * * @param {boolean} full Retain full hiearchy. * @return {TreeNodes} Array of node objects. */ }, { key: 'visible', value: function visible() { return _map(this, 'visible', arguments); } }], [{ key: 'isTreeNode', value: function isTreeNode(obj) { return obj instanceof TreeNode; } /** * Check if an object is a TreeNodes array. * * @param {object} obj Object * @return {boolean} If object is a TreeNodes array. */ }, { key: 'isTreeNodes', value: function isTreeNodes(obj) { return obj instanceof TreeNodes; } }]); return InspireTree; }(eventemitter2_1); return InspireTree; })));
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.8.6_A2.1_T1; * @section: 11.8.6; * @assertion: Operator "instanceof" uses GetValue; * @description: Either Expression is not Reference or GetBase is not null; */ //CHECK#1 if (({}) instanceof Object !== true) { $ERROR('#1: ({}) instanceof Object === true'); } //CHECK#2 var object = {}; if (object instanceof Object !== true) { $ERROR('#2: var object = {}; object instanceof Object === true'); } //CHECK#3 var OBJECT = Object; if (({}) instanceof OBJECT !== true) { $ERROR('#3: var OBJECT = Object; ({}) instanceof OBJECT === true'); } //CHECK#4 var object = {}; var OBJECT = Object; if (object instanceof OBJECT !== true) { $ERROR('#4: var object = {}; var OBJECT = Object; object instanceof OBJECT === true'); }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: "CharacterEscapeSequnce :: SingleEscapeSequence" es5id: 7.8.4_A4.1_T2 description: "SingleEscapeSequence :: one of ' \" \\" ---*/ //CHECK#1 if (String.fromCharCode(0x0027) !== "\'") { $ERROR('#1: String.fromCharCode(0x0027) === "\\\'"'); } //CHECK#2 if (String.fromCharCode(0x0022) !== '\"') { $ERROR('#2: String.fromCharCode(0x0027) === \'\\\"\''); } //CHECK#3 if (String.fromCharCode(0x005C) !== "\\") { $ERROR('#3: String.fromCharCode(0x005C) === "\\\"'); } //CHECK#4 if ("\'" !== "'") { $ERROR('#4: "\'" === "\\\'"'); } //CHECK#5 if ('\"' !== '"') { $ERROR('#5: \'\"\' === \'\\\"\''); }
version https://git-lfs.github.com/spec/v1 oid sha256:8fb458d5e0e2c5d65e097235388fc06997991621e1d122e250e97b52c03fb41f size 8274
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'colorbutton', 'en-gb', { auto: 'Automatic', bgColorTitle: 'Background Colour', colors: { '000': 'Black', '800000': 'Maroon', '8B4513': 'Saddle Brown', '2F4F4F': 'Dark Slate Grey', '008080': 'Teal', '000080': 'Navy', '4B0082': 'Indigo', '696969': 'Dark Grey', B22222: 'Fire Brick', A52A2A: 'Brown', DAA520: 'Golden Rod', '006400': 'Dark Green', '40E0D0': 'Turquoise', '0000CD': 'Medium Blue', '800080': 'Purple', '808080': 'Grey', F00: 'Red', FF8C00: 'Dark Orange', FFD700: 'Gold', '008000': 'Green', '0FF': 'Cyan', '00F': 'Blue', EE82EE: 'Violet', A9A9A9: 'Dim Grey', FFA07A: 'Light Salmon', FFA500: 'Orange', FFFF00: 'Yellow', '00FF00': 'Lime', AFEEEE: 'Pale Turquoise', ADD8E6: 'Light Blue', DDA0DD: 'Plum', D3D3D3: 'Light Grey', FFF0F5: 'Lavender Blush', FAEBD7: 'Antique White', FFFFE0: 'Light Yellow', F0FFF0: 'Honeydew', F0FFFF: 'Azure', F0F8FF: 'Alice Blue', E6E6FA: 'Lavender', FFF: 'White' }, more: 'More Colours...', panelTitle: 'Colours', textColorTitle: 'Text Colour' });
context('User Groups', () => { beforeEach(() => { cy.umbracoLogin(Cypress.env('username'), Cypress.env('password')); }); it('Create member group', () => { const name = "Test Group"; cy.umbracoEnsureMemberGroupNameNotExists(name); cy.umbracoSection('member'); cy.get('li .umb-tree-root:contains("Members")').should("be.visible"); cy.umbracoTreeItem("member", ["Member Groups"]).rightclick(); cy.umbracoContextMenuAction("action-create").click(); //Type name cy.umbracoEditorHeaderName(name); // Save cy.get('.btn-success').click(); //Assert cy.umbracoSuccessNotification().should('be.visible'); //Clean up cy.umbracoEnsureMemberGroupNameNotExists(name); }); });
return "'" + this.replace('\\', '\\\\').replace("'", '\\\'') + "'"; // comment
'use strict'; const align = { right: alignRight, center: alignCenter }; const top = 0; const right = 1; const bottom = 2; const left = 3; export class UI { constructor(opts) { var _a; this.width = opts.width; this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; this.rows = []; } span(...args) { const cols = this.div(...args); cols.span = true; } resetOutput() { this.rows = []; } div(...args) { if (args.length === 0) { this.div(''); } if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { return this.applyLayoutDSL(args[0]); } const cols = args.map(arg => { if (typeof arg === 'string') { return this.colFromString(arg); } return arg; }); this.rows.push(cols); return cols; } shouldApplyLayoutDSL(...args) { return args.length === 1 && typeof args[0] === 'string' && /[\t\n]/.test(args[0]); } applyLayoutDSL(str) { const rows = str.split('\n').map(row => row.split('\t')); let leftColumnWidth = 0; // simple heuristic for layout, make sure the // second column lines up along the left-hand. // don't allow the first column to take up more // than 50% of the screen. rows.forEach(columns => { if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); } }); // generate a table: // replacing ' ' with padding calculations. // using the algorithmically generated width. rows.forEach(columns => { this.div(...columns.map((r, i) => { return { text: r.trim(), padding: this.measurePadding(r), width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined }; })); }); return this.rows[this.rows.length - 1]; } colFromString(text) { return { text, padding: this.measurePadding(text) }; } measurePadding(str) { // measure padding without ansi escape codes const noAnsi = mixin.stripAnsi(str); return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; } toString() { const lines = []; this.rows.forEach(row => { this.rowToString(row, lines); }); // don't display any lines with the // hidden flag set. return lines .filter(line => !line.hidden) .map(line => line.text) .join('\n'); } rowToString(row, lines) { this.rasterize(row).forEach((rrow, r) => { let str = ''; rrow.forEach((col, c) => { const { width } = row[c]; // the width with padding. const wrapWidth = this.negatePadding(row[c]); // the width without padding. let ts = col; // temporary string used during alignment/padding. if (wrapWidth > mixin.stringWidth(col)) { ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); } // align the string within its column. if (row[c].align && row[c].align !== 'left' && this.wrap) { const fn = align[row[c].align]; ts = fn(ts, wrapWidth); if (mixin.stringWidth(ts) < wrapWidth) { ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1); } } // apply border and padding to string. const padding = row[c].padding || [0, 0, 0, 0]; if (padding[left]) { str += ' '.repeat(padding[left]); } str += addBorder(row[c], ts, '| '); str += ts; str += addBorder(row[c], ts, ' |'); if (padding[right]) { str += ' '.repeat(padding[right]); } // if prior row is span, try to render the // current row on the prior line. if (r === 0 && lines.length > 0) { str = this.renderInline(str, lines[lines.length - 1]); } }); // remove trailing whitespace. lines.push({ text: str.replace(/ +$/, ''), span: row.span }); }); return lines; } // if the full 'source' can render in // the target line, do so. renderInline(source, previousLine) { const match = source.match(/^ */); const leadingWhitespace = match ? match[0].length : 0; const target = previousLine.text; const targetTextWidth = mixin.stringWidth(target.trimRight()); if (!previousLine.span) { return source; } // if we're not applying wrapping logic, // just always append to the span. if (!this.wrap) { previousLine.hidden = true; return target + source; } if (leadingWhitespace < targetTextWidth) { return source; } previousLine.hidden = true; return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft(); } rasterize(row) { const rrows = []; const widths = this.columnWidths(row); let wrapped; // word wrap all columns, and create // a data-structure that is easy to rasterize. row.forEach((col, c) => { // leave room for left and right padding. col.width = widths[c]; if (this.wrap) { wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); } else { wrapped = col.text.split('\n'); } if (col.border) { wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); } // add top and bottom padding. if (col.padding) { wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); } wrapped.forEach((str, r) => { if (!rrows[r]) { rrows.push([]); } const rrow = rrows[r]; for (let i = 0; i < c; i++) { if (rrow[i] === undefined) { rrow.push(''); } } rrow.push(str); }); }); return rrows; } negatePadding(col) { let wrapWidth = col.width || 0; if (col.padding) { wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); } if (col.border) { wrapWidth -= 4; } return wrapWidth; } columnWidths(row) { if (!this.wrap) { return row.map(col => { return col.width || mixin.stringWidth(col.text); }); } let unset = row.length; let remainingWidth = this.width; // column widths can be set in config. const widths = row.map(col => { if (col.width) { unset--; remainingWidth -= col.width; return col.width; } return undefined; }); // any unset widths should be calculated. const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; return widths.map((w, i) => { if (w === undefined) { return Math.max(unsetWidth, _minWidth(row[i])); } return w; }); } } function addBorder(col, ts, style) { if (col.border) { if (/[.']-+[.']/.test(ts)) { return ''; } if (ts.trim().length !== 0) { return style; } return ' '; } return ''; } // calculates the minimum width of // a column, based on padding preferences. function _minWidth(col) { const padding = col.padding || []; const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); if (col.border) { return minWidth + 4; } return minWidth; } function getWindowWidth() { /* istanbul ignore next: depends on terminal */ if (typeof process === 'object' && process.stdout && process.stdout.columns) { return process.stdout.columns; } return 80; } function alignRight(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); if (strWidth < width) { return ' '.repeat(width - strWidth) + str; } return str; } function alignCenter(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); /* istanbul ignore next */ if (strWidth >= width) { return str; } return ' '.repeat((width - strWidth) >> 1) + str; } let mixin; export function cliui(opts, _mixin) { mixin = _mixin; return new UI({ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), wrap: opts === null || opts === void 0 ? void 0 : opts.wrap }); }
/** * @fileoverview Tests for no-magic-numbers rule. * @author Vincent Lemeunier */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const rule = require("../../../lib/rules/no-magic-numbers"), RuleTester = require("../../../lib/testers/rule-tester"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const ruleTester = new RuleTester(); ruleTester.run("no-magic-numbers", rule, { valid: [ { code: "var x = parseInt(y, 10);" }, { code: "var x = parseInt(y, -10);" }, { code: "var x = Number.parseInt(y, 10);" }, { code: "const foo = 42;", env: { es6: true } }, { code: "var foo = 42;", env: { es6: true }, options: [{ enforceConst: false }] }, { code: "var foo = -42;" }, { code: "var foo = 0 + 1 - 2 + -2;", options: [{ ignore: [0, 1, 2, -2] }] }, { code: "var foo = 0 + 1 + 2 + 3 + 4;", options: [{ ignore: [0, 1, 2, 3, 4] }] }, { code: "var foo = { bar:10 }" }, { code: "setTimeout(function() {return 1;}, 0);", options: [{ ignore: [0, 1] }] }, { code: "var data = ['foo', 'bar', 'baz']; var third = data[3];", options: [{ ignoreArrayIndexes: true }] }, { code: "var a = <input maxLength={10} />;", parserOptions: { ecmaFeatures: { jsx: true } } }, { code: "var a = <div objectProp={{ test: 1}}></div>;", parserOptions: { ecmaFeatures: { jsx: true } } } ], invalid: [ { code: "var foo = 42", env: { es6: true }, options: [{ enforceConst: true }], errors: [{ message: "Number constants declarations must use 'const'." }] }, { code: "var foo = 0 + 1;", errors: [ { message: "No magic number: 0." }, { message: "No magic number: 1." } ] }, { code: "a = a + 5;", errors: [ { message: "No magic number: 5." } ] }, { code: "a += 5;", errors: [ { message: "No magic number: 5." } ] }, { code: "var foo = 0 + 1 + -2 + 2;", errors: [ { message: "No magic number: 0." }, { message: "No magic number: 1." }, { message: "No magic number: -2." }, { message: "No magic number: 2." } ] }, { code: "var foo = 0 + 1 + 2;", options: [{ ignore: [0, 1] }], errors: [ { message: "No magic number: 2." } ] }, { code: "var foo = { bar:10 }", options: [{ detectObjects: true }], errors: [ { message: "No magic number: 10." } ] }, { code: "console.log(0x1A + 0x02); console.log(071);", errors: [ { message: "No magic number: 0x1A." }, { message: "No magic number: 0x02." }, { message: "No magic number: 071." } ] }, { code: "var stats = {avg: 42};", options: [{ detectObjects: true }], errors: [ { message: "No magic number: 42." } ] }, { code: "var colors = {}; colors.RED = 2; colors.YELLOW = 3; colors.BLUE = 4 + 5;", errors: [ { message: "No magic number: 4." }, { message: "No magic number: 5." } ] }, { code: "function getSecondsInMinute() {return 60;}", errors: [ { message: "No magic number: 60." } ] }, { code: "function getNegativeSecondsInMinute() {return -60;}", errors: [ { message: "No magic number: -60." } ] }, { code: "var Promise = require('bluebird');\n" + "var MINUTE = 60;\n" + "var HOUR = 3600;\n" + "const DAY = 86400;\n" + "var configObject = {\n" + "key: 90,\n" + "another: 10 * 10,\n" + "10: 'an \"integer\" key'\n" + "};\n" + "function getSecondsInDay() {\n" + " return 24 * HOUR;\n" + "}\n" + "function getMillisecondsInDay() {\n" + "return (getSecondsInDay() *\n" + "(1000)\n" + ");\n" + "}\n" + "function callSetTimeoutZero(func) {\n" + "setTimeout(func, 0);\n" + "}\n" + "function invokeInTen(func) {\n" + "setTimeout(func, 10);\n" + "}\n", env: { es6: true }, errors: [ { message: "No magic number: 10.", line: 7 }, { message: "No magic number: 10.", line: 7 }, { message: "No magic number: 24.", line: 11 }, { message: "No magic number: 1000.", line: 15 }, { message: "No magic number: 0.", line: 19 }, { message: "No magic number: 10.", line: 22 } ] }, { code: "var data = ['foo', 'bar', 'baz']; var third = data[3];", options: [{}], errors: [{ message: "No magic number: 3.", line: 1 }] }, { code: "var a = <div arrayProp={[1,2,3]}></div>;", parserOptions: { ecmaFeatures: { jsx: true } }, errors: [ { message: "No magic number: 1.", line: 1 }, { message: "No magic number: 2.", line: 1 }, { message: "No magic number: 3.", line: 1 } ] }, { code: "var min, max, mean; min = 1; max = 10; mean = 4;", options: [{}], errors: [ { message: "No magic number: 1.", line: 1 }, { message: "No magic number: 10.", line: 1 }, { message: "No magic number: 4.", line: 1 } ] } ] });
(function($) { $.widget('pageflow.hideTextOnSwipe', { _create: function() { this.element.swipeGesture({ orientation: 'x' }); this.element.on('swipegestureleft', function() { pageflow.hideText.activate(); }); this.element.on('touchstart MSPointerDown pointerdown mousedown', function() { if (pageflow.hideText.isActive()) { pageflow.hideText.deactivate(); } }); this.element.on('scrollermove', function() { if (pageflow.hideText.isActive()) { pageflow.hideText.deactivate(); } }); } }); }(jQuery));
module.exports = function(config) { return !/^v(4|6)/.test(process.version); };
version https://git-lfs.github.com/spec/v1 oid sha256:056ea780a4642ef75cef42293c9f0a75bf57873516dae527e0b48998868dfd39 size 2091
/*globals equal,test*/ Ink.requireModules(['Ink.UI.FormValidator_1', 'Ink.Dom.Element_1', 'Ink.Dom.Selector_1', 'Ink.Util.Array_1', 'Ink.Dom.Event_1'], function (FormValidator, InkElement, Selector, InkArray, InkEvent) { 'use strict'; var body = document.getElementsByTagName('body')[0]; test('required text', function () { var txt = InkElement.create('input', { type: 'text', className: 'ink-fv-required' }); ok(!FormValidator._isValid(txt, 'ink-fv-required')); txt.value = 'some text'; ok(FormValidator._isValid(txt, 'ink-fv-required')); }); test('(regression) not required email', function () { var txt = InkElement.create('input', { type: 'text', className: 'ink-fv-email' }); txt.value = ''; ok(FormValidator._isValid(txt, 'ink-fv-email')); txt.value = 'my@email.com'; ok(FormValidator._isValid(txt, 'ink-fv-email')); }); test('required to select at least one radio button', function () { var radios = [ InkElement.create('input', { type: 'radio', className: 'ink-fv-required', name: 'radioinpt', value: '1' }), InkElement.create('input', { type: 'radio', className: 'ink-fv-required', name: 'radioinpt', value: '2' }), InkElement.create('input', { type: 'radio', className: 'ink-fv-required', name: 'radioinpt', value: '3' }) ]; var form = InkElement.create('form'); for (var i = 0, len = radios.length; i < len; i++) { form.appendChild(radios[i]); } body.appendChild(form); for (i = 0, len = radios.length; i < len; i++) { ok(!FormValidator._isValid(radios[i], 'ink-fv-required')); } radios[1].checked = true; for (i = 0, len = radios.length; i < len; i++) { ok(FormValidator._isValid(radios[i], 'ink-fv-required')); } body.removeChild(form); }); test('required to check that one checkbox', function () { var check = InkElement.create('input', { type: 'checkbox', className: 'ink-fv-required', name: 'checkinpt', value: '1' }); var form = InkElement.create('form'); form.appendChild(check); body.appendChild(form); ok(!FormValidator._isValid(check, 'ink-fv-required')); check.checked = true; ok(FormValidator._isValid(check, 'ink-fv-required')); body.removeChild(form); }); test('required to select at least one checkbox', function () { var checks = [ InkElement.create('input', { type: 'checkbox', className: 'ink-fv-required', name: 'checkinpt', value: '1' }), InkElement.create('input', { type: 'checkbox', className: 'ink-fv-required', name: 'checkinpt', value: '2' }), InkElement.create('input', { type: 'checkbox', className: 'ink-fv-required', name: 'checkinpt', value: '3' }) ]; var form = InkElement.create('form'); for (var i = 0, len = checks.length; i < len; i++) { form.appendChild(checks[i]); } body.appendChild(form); for (i = 0, len = checks.length; i < len; i++) { ok(!FormValidator._isValid(checks[i], 'ink-fv-required')); } checks[1].checked = true; for (i = 0, len = checks.length; i < len; i++) { ok(FormValidator._isValid(checks[i], 'ink-fv-required')); } body.removeChild(form); }); });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'basicstyles', 'ar', { bold: 'غامق', italic: 'مائل', strike: 'يتوسطه خط', subscript: 'منخفض', superscript: 'مرتفع', underline: 'تسطير' });
'use strict'; var React = require('react/addons'); var PureRenderMixin = React.addons.PureRenderMixin; var SvgIcon = require('../../svg-icon'); var AvPlayCircleOutline = React.createClass({ displayName: 'AvPlayCircleOutline', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M10 16.5l6-4.5-6-4.5v9zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z' }) ); } }); module.exports = AvPlayCircleOutline;
(function (factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof module === 'object' && typeof module.exports === 'object') { factory(require('jquery')); } else { factory(jQuery); } }(function (jQuery) { // Italian jQuery.timeago.settings.strings = { suffixAgo: "fa", suffixFromNow: "da ora", seconds: "meno di un minuto", minute: "circa un minuto", minutes: "%d minuti", hour: "circa un'ora", hours: "circa %d ore", day: "un giorno", days: "%d giorni", month: "circa un mese", months: "%d mesi", year: "circa un anno", years: "%d anni" }; });
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use 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 Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * 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 AJAX.ORG B.V. 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. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/less', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/less_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/css', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var LessHighlightRules = require("./less_highlight_rules").LessHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = LessHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/less_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LessHighlightRules = function() { var properties = lang.arrayToMap( (function () { var browserPrefix = ("-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-").split("|"); var prefixProperties = ("appearance|background-clip|background-inline-policy|background-origin|" + "background-size|binding|border-bottom-colors|border-left-colors|" + "border-right-colors|border-top-colors|border-end|border-end-color|" + "border-end-style|border-end-width|border-image|border-start|" + "border-start-color|border-start-style|border-start-width|box-align|" + "box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|" + "box-pack|box-sizing|column-count|column-gap|column-width|column-rule|" + "column-rule-width|column-rule-style|column-rule-color|float-edge|" + "font-feature-settings|font-language-override|force-broken-image-icon|" + "image-region|margin-end|margin-start|opacity|outline|outline-color|" + "outline-offset|outline-radius|outline-radius-bottomleft|" + "outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|" + "outline-style|outline-width|padding-end|padding-start|stack-sizing|" + "tab-size|text-blink|text-decoration-color|text-decoration-line|" + "text-decoration-style|transform|transform-origin|transition|" + "transition-delay|transition-duration|transition-property|" + "transition-timing-function|user-focus|user-input|user-modify|user-select|" + "window-shadow|border-radius").split("|"); var properties = ("azimuth|background-attachment|background-color|background-image|" + "background-position|background-repeat|background|border-bottom-color|" + "border-bottom-style|border-bottom-width|border-bottom|border-collapse|" + "border-color|border-left-color|border-left-style|border-left-width|" + "border-left|border-right-color|border-right-style|border-right-width|" + "border-right|border-spacing|border-style|border-top-color|" + "border-top-style|border-top-width|border-top|border-width|border|" + "bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" + "counter-reset|cue-after|cue-before|cue|cursor|direction|display|" + "elevation|empty-cells|float|font-family|font-size-adjust|font-size|" + "font-stretch|font-style|font-variant|font-weight|font|height|left|" + "letter-spacing|line-height|list-style-image|list-style-position|" + "list-style-type|list-style|margin-bottom|margin-left|margin-right|" + "margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" + "min-width|opacity|orphans|outline-color|" + "outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" + "padding-left|padding-right|padding-top|padding|page-break-after|" + "page-break-before|page-break-inside|page|pause-after|pause-before|" + "pause|pitch-range|pitch|play-during|position|quotes|richness|right|" + "size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" + "stress|table-layout|text-align|text-decoration|text-indent|" + "text-shadow|text-transform|top|unicode-bidi|vertical-align|" + "visibility|voice-family|volume|white-space|widows|width|word-spacing|" + "z-index").split("|"); var ret = []; for (var i=0, ln=browserPrefix.length; i<ln; i++) { Array.prototype.push.apply( ret, (( browserPrefix[i] + prefixProperties.join("|" + browserPrefix[i]) ).split("|")) ); } Array.prototype.push.apply(ret, prefixProperties); Array.prototype.push.apply(ret, properties); return ret; })() ); var functions = lang.arrayToMap( ("hsl|hsla|rgb|rgba|url|attr|counter|counters|lighten|darken|saturate|" + "desaturate|fadein|fadeout|fade|spin|mix|hue|saturation|lightness|" + "alpha|round|ceil|floor|percentage|color|iscolor|isnumber|isstring|" + "iskeyword|isurl|ispixel|ispercentage|isem").split("|") ); var constants = lang.arrayToMap( ("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" + "block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" + "char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" + "decimal-leading-zero|decimal|default|disabled|disc|" + "distribute-all-lines|distribute-letter|distribute-space|" + "distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" + "hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|" + "ideograph-alpha|ideograph-numeric|ideograph-parenthesis|" + "ideograph-space|inactive|inherit|inline-block|inline|inset|inside|" + "inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|" + "keep-all|left|lighter|line-edge|line-through|line|list-item|loose|" + "lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|" + "medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|" + "nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|" + "overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|" + "ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|" + "solid|square|static|strict|super|sw-resize|table-footer-group|" + "table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|" + "transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|" + "vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|" + "zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var keywords = lang.arrayToMap( ("@mixin|@extend|@include|@import|@media|@debug|@warn|@if|@for|@each|" + "@while|@else|@font-face|@-webkit-keyframes|if|and|!default|module|" + "def|end|declare|when|not|and").split("|") ); var tags = lang.arrayToMap( ("a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdo|" + "big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" + "command|datalist|dd|del|details|dfn|dir|div|dl|dt|em|embed|fieldset|" + "figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|" + "header|hgroup|hr|html|i|iframe|img|input|ins|keygen|kbd|label|legend|li|" + "link|map|mark|menu|meta|meter|nav|noframes|noscript|object|ol|optgroup|" + "option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|" + "small|source|span|strike|strong|style|sub|summary|sup|table|tbody|td|" + "textarea|tfoot|th|thead|time|title|tr|tt|u|ul|var|video|wbr|xmp").split("|") ); var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, { token : "comment", // multi line comment regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : "constant.numeric", regex : numRe }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else return "variable"; }, regex : "@[a-z0-9_\\-@]*\\b" }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) return "support.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (constants.hasOwnProperty(value)) return "constant.language"; else if (functions.hasOwnProperty(value)) return "support.function"; else if (colors.hasOwnProperty(value.toLowerCase())) return "support.constant.color"; else if (tags.hasOwnProperty(value.toLowerCase())) return "variable.language"; else return "text"; }, regex : "\\-?[@a-z_][@a-z0-9_\\-]*" }, { token: "variable.language", regex: "#[a-z0-9-_]+" }, { token: "variable.language", regex: "\\.[a-z0-9-_]+" }, { token: "variable.language", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { token : "keyword.operator", regex : "<|>|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" }, { caseInsensitive: true } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ] }; }; oop.inherits(LessHighlightRules, TextHighlightRules); exports.LessHighlightRules = LessHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var autoInsertedBrackets = 0; var autoInsertedRow = -1; var autoInsertedLineEnd = ""; var maybeInsertedBrackets = 0; var maybeInsertedRow = -1; var maybeInsertedLineStart = ""; var maybeInsertedLineEnd = ""; var CstyleBehaviour = function () { CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, autoInsertedLineEnd[0])) autoInsertedBrackets = 0; autoInsertedRow = cursor.row; autoInsertedLineEnd = bracket + line.substr(cursor.column); autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) maybeInsertedBrackets = 0; maybeInsertedRow = cursor.row; maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; maybeInsertedLineEnd = line.substr(cursor.column); maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return autoInsertedBrackets > 0 && cursor.row === autoInsertedRow && bracket === autoInsertedLineEnd[0] && line.substr(cursor.column) === autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return maybeInsertedBrackets > 0 && cursor.row === maybeInsertedRow && line.substr(cursor.column) === maybeInsertedLineEnd && line.substr(0, cursor.column) == maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { autoInsertedLineEnd = autoInsertedLineEnd.substr(1); autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { maybeInsertedBrackets = 0; maybeInsertedRow = -1; }; this.add("braces", "insertion", function (state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return { text: '{' + selected + '}', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column])) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}' || closing !== "") { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column}, '}'); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, cursor.column), session.getTabString()); var next_indent = this.$getIndent(line); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return { text: '(' + selected + ')', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '[') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return { text: '[' + selected + ']', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); if (leftChar == '\\') { return null; } var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { if (!CstyleBehaviour.isSaneInsertion(editor, session)) return; return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i + match[0].length, 1); } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; }).call(FoldMode.prototype); });
/** * @format * @flow */ // nope // context -1 // context -2 // context -3 (null: empty); // Error: null ~> empty // context +1 // context +2 // context +3 // nope
version https://git-lfs.github.com/spec/v1 oid sha256:da06c3b3d37f5e97e47feddb285099005ffae0ba73c9ef7aa89f07322e13c54d size 2459
/* * /MathJax/localization/bcc/MathMenu.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ MathJax.Localization.addTranslation("bcc","MathMenu",{version:"2.7.4",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/bcc/MathMenu.js");
var Lab = require('lab'); var Code = require('code'); var Constants = require('../../../../client/pages/login/Constants'); var lab = exports.lab = Lab.script(); lab.experiment('Login Constants', function () { lab.test('it loads', function (done) { Code.expect(Constants).to.exist(); done(); }); });
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const makeSerializable = require("../util/makeSerializable"); const ModuleDependency = require("./ModuleDependency"); const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); class CommonJsRequireDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "cjs require"; } get category() { return "commonjs"; } } CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; makeSerializable( CommonJsRequireDependency, "webpack/lib/dependencies/CommonJsRequireDependency" ); module.exports = CommonJsRequireDependency;
/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/react-select */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); 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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _objectWithoutProperties(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; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactInputAutosize = require('react-input-autosize'); var _reactInputAutosize2 = _interopRequireDefault(_reactInputAutosize); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _utilsDefaultArrowRenderer = require('./utils/defaultArrowRenderer'); var _utilsDefaultArrowRenderer2 = _interopRequireDefault(_utilsDefaultArrowRenderer); var _utilsDefaultFilterOptions = require('./utils/defaultFilterOptions'); var _utilsDefaultFilterOptions2 = _interopRequireDefault(_utilsDefaultFilterOptions); var _utilsDefaultMenuRenderer = require('./utils/defaultMenuRenderer'); var _utilsDefaultMenuRenderer2 = _interopRequireDefault(_utilsDefaultMenuRenderer); var _Async = require('./Async'); var _Async2 = _interopRequireDefault(_Async); var _AsyncCreatable = require('./AsyncCreatable'); var _AsyncCreatable2 = _interopRequireDefault(_AsyncCreatable); var _Creatable = require('./Creatable'); var _Creatable2 = _interopRequireDefault(_Creatable); var _Option = require('./Option'); var _Option2 = _interopRequireDefault(_Option); var _Value = require('./Value'); var _Value2 = _interopRequireDefault(_Value); function stringifyValue(value) { var valueType = typeof value; if (valueType === 'string') { return value; } else if (valueType === 'object') { return JSON.stringify(value); } else if (valueType === 'number' || valueType === 'boolean') { return String(value); } else { return ''; } } var stringOrNode = _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.node]); var instanceId = 1; var Select = _react2['default'].createClass({ displayName: 'Select', propTypes: { addLabelText: _react2['default'].PropTypes.string, // placeholder displayed when you want to add a label on a multi-value input 'aria-label': _react2['default'].PropTypes.string, // Aria label (for assistive tech) 'aria-labelledby': _react2['default'].PropTypes.string, // HTML ID of an element that should be used as the label (for assistive tech) arrowRenderer: _react2['default'].PropTypes.func, // Create drop-down caret element autoBlur: _react2['default'].PropTypes.bool, // automatically blur the component when an option is selected autofocus: _react2['default'].PropTypes.bool, // autofocus the component on mount autosize: _react2['default'].PropTypes.bool, // whether to enable autosizing or not backspaceRemoves: _react2['default'].PropTypes.bool, // whether backspace removes an item if there is no text input backspaceToRemoveMessage: _react2['default'].PropTypes.string, // Message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label className: _react2['default'].PropTypes.string, // className for the outer element clearAllText: stringOrNode, // title for the "clear" control when multi: true clearValueText: stringOrNode, // title for the "clear" control clearable: _react2['default'].PropTypes.bool, // should it be possible to reset value delimiter: _react2['default'].PropTypes.string, // delimiter to use to join multiple values for the hidden field value disabled: _react2['default'].PropTypes.bool, // whether the Select is disabled or not escapeClearsValue: _react2['default'].PropTypes.bool, // whether escape clears the value when the menu is closed filterOption: _react2['default'].PropTypes.func, // method to filter a single option (option, filterString) filterOptions: _react2['default'].PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) ignoreAccents: _react2['default'].PropTypes.bool, // whether to strip diacritics when filtering ignoreCase: _react2['default'].PropTypes.bool, // whether to perform case-insensitive filtering inputProps: _react2['default'].PropTypes.object, // custom attributes for the Input inputRenderer: _react2['default'].PropTypes.func, // returns a custom input component instanceId: _react2['default'].PropTypes.string, // set the components instanceId isLoading: _react2['default'].PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded) joinValues: _react2['default'].PropTypes.bool, // joins multiple values into a single form field with the delimiter (legacy mode) labelKey: _react2['default'].PropTypes.string, // path of the label value in option objects matchPos: _react2['default'].PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: _react2['default'].PropTypes.string, // (any|label|value) which option property to filter on menuBuffer: _react2['default'].PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu menuContainerStyle: _react2['default'].PropTypes.object, // optional style to apply to the menu container menuRenderer: _react2['default'].PropTypes.func, // renders a custom menu with options menuStyle: _react2['default'].PropTypes.object, // optional style to apply to the menu multi: _react2['default'].PropTypes.bool, // multi-value input name: _react2['default'].PropTypes.string, // generates a hidden <input /> tag with this field name for html forms noResultsText: stringOrNode, // placeholder displayed when there are no matching search results onBlur: _react2['default'].PropTypes.func, // onBlur handler: function (event) {} onBlurResetsInput: _react2['default'].PropTypes.bool, // whether input is cleared on blur onChange: _react2['default'].PropTypes.func, // onChange handler: function (newValue) {} onClose: _react2['default'].PropTypes.func, // fires when the menu is closed onCloseResetsInput: _react2['default'].PropTypes.bool, // whether input is cleared when menu is closed through the arrow onFocus: _react2['default'].PropTypes.func, // onFocus handler: function (event) {} onInputChange: _react2['default'].PropTypes.func, // onInputChange handler: function (inputValue) {} onInputKeyDown: _react2['default'].PropTypes.func, // input keyDown handler: function (event) {} onMenuScrollToBottom: _react2['default'].PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options onOpen: _react2['default'].PropTypes.func, // fires when the menu is opened onValueClick: _react2['default'].PropTypes.func, // onClick handler for value labels: function (value, event) {} openAfterFocus: _react2['default'].PropTypes.bool, // boolean to enable opening dropdown when focused openOnFocus: _react2['default'].PropTypes.bool, // always open options menu on focus optionClassName: _react2['default'].PropTypes.string, // additional class(es) to apply to the <Option /> elements optionComponent: _react2['default'].PropTypes.func, // option component to render in dropdown optionRenderer: _react2['default'].PropTypes.func, // optionRenderer: function (option) {} options: _react2['default'].PropTypes.array, // array of options pageSize: _react2['default'].PropTypes.number, // number of entries to page when using page up/down keys placeholder: stringOrNode, // field placeholder, displayed when there's no value required: _react2['default'].PropTypes.bool, // applies HTML5 required attribute when needed resetValue: _react2['default'].PropTypes.any, // value to use when you clear the control scrollMenuIntoView: _react2['default'].PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged searchable: _react2['default'].PropTypes.bool, // whether to enable searching feature or not simpleValue: _react2['default'].PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false style: _react2['default'].PropTypes.object, // optional style to apply to the control tabIndex: _react2['default'].PropTypes.string, // optional tab index of the control tabSelectsValue: _react2['default'].PropTypes.bool, // whether to treat tabbing out while focused to be value selection value: _react2['default'].PropTypes.any, // initial field value valueComponent: _react2['default'].PropTypes.func, // value component to render valueKey: _react2['default'].PropTypes.string, // path of the label value in option objects valueRenderer: _react2['default'].PropTypes.func, // valueRenderer: function (option) {} wrapperStyle: _react2['default'].PropTypes.object }, // optional style to apply to the component wrapper statics: { Async: _Async2['default'], AsyncCreatable: _AsyncCreatable2['default'], Creatable: _Creatable2['default'] }, getDefaultProps: function getDefaultProps() { return { addLabelText: 'Add "{label}"?', arrowRenderer: _utilsDefaultArrowRenderer2['default'], autosize: true, backspaceRemoves: true, backspaceToRemoveMessage: 'Press backspace to remove {label}', clearable: true, clearAllText: 'Clear all', clearValueText: 'Clear value', delimiter: ',', disabled: false, escapeClearsValue: true, filterOptions: _utilsDefaultFilterOptions2['default'], ignoreAccents: true, ignoreCase: true, inputProps: {}, isLoading: false, joinValues: false, labelKey: 'label', matchPos: 'any', matchProp: 'any', menuBuffer: 0, menuRenderer: _utilsDefaultMenuRenderer2['default'], multi: false, noResultsText: 'No results found', onBlurResetsInput: true, onCloseResetsInput: true, openAfterFocus: false, optionComponent: _Option2['default'], pageSize: 5, placeholder: 'Select...', required: false, scrollMenuIntoView: true, searchable: true, simpleValue: false, tabSelectsValue: true, valueComponent: _Value2['default'], valueKey: 'value' }; }, getInitialState: function getInitialState() { return { inputValue: '', isFocused: false, isOpen: false, isPseudoFocused: false, required: false }; }, componentWillMount: function componentWillMount() { this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-'; var valueArray = this.getValueArray(this.props.value); if (this.props.required) { this.setState({ required: this.handleRequired(valueArray[0], this.props.multi) }); } }, componentDidMount: function componentDidMount() { if (this.props.autofocus) { this.focus(); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var valueArray = this.getValueArray(nextProps.value, nextProps); if (nextProps.required) { this.setState({ required: this.handleRequired(valueArray[0], nextProps.multi) }); } }, componentWillUpdate: function componentWillUpdate(nextProps, nextState) { if (nextState.isOpen !== this.state.isOpen) { this.toggleTouchOutsideEvent(nextState.isOpen); var handler = nextState.isOpen ? nextProps.onOpen : nextProps.onClose; handler && handler(); } }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { // focus to the selected option if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) { var focusedOptionNode = _reactDom2['default'].findDOMNode(this.focused); var menuNode = _reactDom2['default'].findDOMNode(this.menu); menuNode.scrollTop = focusedOptionNode.offsetTop; this.hasScrolledToOption = true; } else if (!this.state.isOpen) { this.hasScrolledToOption = false; } if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) { this._scrollToFocusedOptionOnUpdate = false; var focusedDOM = _reactDom2['default'].findDOMNode(this.focused); var menuDOM = _reactDom2['default'].findDOMNode(this.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom || focusedRect.top < menuRect.top) { menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight; } } if (this.props.scrollMenuIntoView && this.menuContainer) { var menuContainerRect = this.menuContainer.getBoundingClientRect(); if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) { window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight); } } if (prevProps.disabled !== this.props.disabled) { this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state this.closeMenu(); } }, componentWillUnmount: function componentWillUnmount() { document.removeEventListener('touchstart', this.handleTouchOutside); }, toggleTouchOutsideEvent: function toggleTouchOutsideEvent(enabled) { if (enabled) { document.addEventListener('touchstart', this.handleTouchOutside); } else { document.removeEventListener('touchstart', this.handleTouchOutside); } }, handleTouchOutside: function handleTouchOutside(event) { // handle touch outside on ios to dismiss menu if (this.wrapper && !this.wrapper.contains(event.target)) { this.closeMenu(); } }, focus: function focus() { if (!this.input) return; this.input.focus(); if (this.props.openAfterFocus) { this.setState({ isOpen: true }); } }, blurInput: function blurInput() { if (!this.input) return; this.input.blur(); }, handleTouchMove: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; }, handleTouchEnd: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.handleMouseDown(event); }, handleTouchEndClearValue: function handleTouchEndClearValue(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Clear the value this.clearValue(event); }, handleMouseDown: function handleMouseDown(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } if (event.target.tagName === 'INPUT') { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // for the non-searchable select, toggle the menu if (!this.props.searchable) { this.focus(); return this.setState({ isOpen: !this.state.isOpen }); } if (this.state.isFocused) { // On iOS, we can get into a state where we think the input is focused but it isn't really, // since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event. // Call focus() again here to be safe. this.focus(); var input = this.input; if (typeof input.getInput === 'function') { // Get the actual DOM input if the ref is an <AutosizeInput /> component input = input.getInput(); } // clears the value so that the cursor will be at the end of input when the component re-renders input.value = ''; // if the input is focused, ensure the menu is open this.setState({ isOpen: true, isPseudoFocused: false }); } else { // otherwise, focus the input and open the menu this._openAfterFocus = true; this.focus(); } }, handleMouseDownOnArrow: function handleMouseDownOnArrow(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } // If the menu isn't open, let the event bubble to the main handleMouseDown if (!this.state.isOpen) { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // close the menu this.closeMenu(); }, handleMouseDownOnMenu: function handleMouseDownOnMenu(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this._openAfterFocus = true; this.focus(); }, closeMenu: function closeMenu() { if (this.props.onCloseResetsInput) { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: '' }); } else { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: this.state.inputValue }); } this.hasScrolledToOption = false; }, handleInputFocus: function handleInputFocus(event) { if (this.props.disabled) return; var isOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus; if (this.props.onFocus) { this.props.onFocus(event); } this.setState({ isFocused: true, isOpen: isOpen }); this._openAfterFocus = false; }, handleInputBlur: function handleInputBlur(event) { // The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts. if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) { this.focus(); return; } if (this.props.onBlur) { this.props.onBlur(event); } var onBlurredState = { isFocused: false, isOpen: false, isPseudoFocused: false }; if (this.props.onBlurResetsInput) { onBlurredState.inputValue = ''; } this.setState(onBlurredState); }, handleInputChange: function handleInputChange(event) { var newInputValue = event.target.value; if (this.state.inputValue !== event.target.value && this.props.onInputChange) { var nextState = this.props.onInputChange(newInputValue); // Note: != used deliberately here to catch undefined and null if (nextState != null && typeof nextState !== 'object') { newInputValue = '' + nextState; } } this.setState({ isOpen: true, isPseudoFocused: false, inputValue: newInputValue }); }, handleKeyDown: function handleKeyDown(event) { if (this.props.disabled) return; if (typeof this.props.onInputKeyDown === 'function') { this.props.onInputKeyDown(event); if (event.defaultPrevented) { return; } } switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { event.preventDefault(); this.popValue(); } return; case 9: // tab if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) { return; } this.selectFocusedOption(); return; case 13: // enter if (!this.state.isOpen) return; event.stopPropagation(); this.selectFocusedOption(); break; case 27: // escape if (this.state.isOpen) { this.closeMenu(); event.stopPropagation(); } else if (this.props.clearable && this.props.escapeClearsValue) { this.clearValue(event); event.stopPropagation(); } break; case 38: // up this.focusPreviousOption(); break; case 40: // down this.focusNextOption(); break; case 33: // page up this.focusPageUpOption(); break; case 34: // page down this.focusPageDownOption(); break; case 35: // end key if (event.shiftKey) { return; } this.focusEndOption(); break; case 36: // home key if (event.shiftKey) { return; } this.focusStartOption(); break; default: return; } event.preventDefault(); }, handleValueClick: function handleValueClick(option, event) { if (!this.props.onValueClick) return; this.props.onValueClick(option, event); }, handleMenuScroll: function handleMenuScroll(event) { if (!this.props.onMenuScrollToBottom) return; var target = event.target; if (target.scrollHeight > target.offsetHeight && !(target.scrollHeight - target.offsetHeight - target.scrollTop)) { this.props.onMenuScrollToBottom(); } }, handleRequired: function handleRequired(value, multi) { if (!value) return true; return multi ? value.length === 0 : Object.keys(value).length === 0; }, getOptionLabel: function getOptionLabel(op) { return op[this.props.labelKey]; }, /** * Turns a value into an array from the given options * @param {String|Number|Array} value - the value of the select input * @param {Object} nextProps - optionally specify the nextProps so the returned array uses the latest configuration * @returns {Array} the value of the select represented in an array */ getValueArray: function getValueArray(value, nextProps) { var _this = this; /** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */ var props = typeof nextProps === 'object' ? nextProps : this.props; if (props.multi) { if (typeof value === 'string') value = value.split(props.delimiter); if (!Array.isArray(value)) { if (value === null || value === undefined) return []; value = [value]; } return value.map(function (value) { return _this.expandValue(value, props); }).filter(function (i) { return i; }); } var expandedValue = this.expandValue(value, props); return expandedValue ? [expandedValue] : []; }, /** * Retrieve a value from the given options and valueKey * @param {String|Number|Array} value - the selected value(s) * @param {Object} props - the Select component's props (or nextProps) */ expandValue: function expandValue(value, props) { var valueType = typeof value; if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value; var options = props.options; var valueKey = props.valueKey; if (!options) return; for (var i = 0; i < options.length; i++) { if (options[i][valueKey] === value) return options[i]; } }, setValue: function setValue(value) { var _this2 = this; if (this.props.autoBlur) { this.blurInput(); } if (!this.props.onChange) return; if (this.props.required) { var required = this.handleRequired(value, this.props.multi); this.setState({ required: required }); } if (this.props.simpleValue && value) { value = this.props.multi ? value.map(function (i) { return i[_this2.props.valueKey]; }).join(this.props.delimiter) : value[this.props.valueKey]; } this.props.onChange(value); }, selectValue: function selectValue(value) { var _this3 = this; //NOTE: update value in the callback to make sure the input value is empty so that there are no styling issues (Chrome had issue otherwise) this.hasScrolledToOption = false; if (this.props.multi) { this.setState({ inputValue: '', focusedIndex: null }, function () { _this3.addValue(value); }); } else { this.setState({ isOpen: false, inputValue: '', isPseudoFocused: this.state.isFocused }, function () { _this3.setValue(value); }); } }, addValue: function addValue(value) { var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.concat(value)); }, popValue: function popValue() { var valueArray = this.getValueArray(this.props.value); if (!valueArray.length) return; if (valueArray[valueArray.length - 1].clearableValue === false) return; this.setValue(valueArray.slice(0, valueArray.length - 1)); }, removeValue: function removeValue(value) { var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.filter(function (i) { return i !== value; })); this.focus(); }, clearValue: function clearValue(event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this.setValue(this.getResetValue()); this.setState({ isOpen: false, inputValue: '' }, this.focus); }, getResetValue: function getResetValue() { if (this.props.resetValue !== undefined) { return this.props.resetValue; } else if (this.props.multi) { return []; } else { return null; } }, focusOption: function focusOption(option) { this.setState({ focusedOption: option }); }, focusNextOption: function focusNextOption() { this.focusAdjacentOption('next'); }, focusPreviousOption: function focusPreviousOption() { this.focusAdjacentOption('previous'); }, focusPageUpOption: function focusPageUpOption() { this.focusAdjacentOption('page_up'); }, focusPageDownOption: function focusPageDownOption() { this.focusAdjacentOption('page_down'); }, focusStartOption: function focusStartOption() { this.focusAdjacentOption('start'); }, focusEndOption: function focusEndOption() { this.focusAdjacentOption('end'); }, focusAdjacentOption: function focusAdjacentOption(dir) { var options = this._visibleOptions.map(function (option, index) { return { option: option, index: index }; }).filter(function (option) { return !option.option.disabled; }); this._scrollToFocusedOptionOnUpdate = true; if (!this.state.isOpen) { this.setState({ isOpen: true, inputValue: '', focusedOption: this._focusedOption || options[dir === 'next' ? 0 : options.length - 1].option }); return; } if (!options.length) return; var focusedIndex = -1; for (var i = 0; i < options.length; i++) { if (this._focusedOption === options[i].option) { focusedIndex = i; break; } } if (dir === 'next' && focusedIndex !== -1) { focusedIndex = (focusedIndex + 1) % options.length; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedIndex = focusedIndex - 1; } else { focusedIndex = options.length - 1; } } else if (dir === 'start') { focusedIndex = 0; } else if (dir === 'end') { focusedIndex = options.length - 1; } else if (dir === 'page_up') { var potentialIndex = focusedIndex - this.props.pageSize; if (potentialIndex < 0) { focusedIndex = 0; } else { focusedIndex = potentialIndex; } } else if (dir === 'page_down') { var potentialIndex = focusedIndex + this.props.pageSize; if (potentialIndex > options.length - 1) { focusedIndex = options.length - 1; } else { focusedIndex = potentialIndex; } } if (focusedIndex === -1) { focusedIndex = 0; } this.setState({ focusedIndex: options[focusedIndex].index, focusedOption: options[focusedIndex].option }); }, getFocusedOption: function getFocusedOption() { return this._focusedOption; }, getInputValue: function getInputValue() { return this.state.inputValue; }, selectFocusedOption: function selectFocusedOption() { if (this._focusedOption) { return this.selectValue(this._focusedOption); } }, renderLoading: function renderLoading() { if (!this.props.isLoading) return; return _react2['default'].createElement( 'span', { className: 'Select-loading-zone', 'aria-hidden': 'true' }, _react2['default'].createElement('span', { className: 'Select-loading' }) ); }, renderValue: function renderValue(valueArray, isOpen) { var _this4 = this; var renderLabel = this.props.valueRenderer || this.getOptionLabel; var ValueComponent = this.props.valueComponent; if (!valueArray.length) { return !this.state.inputValue ? _react2['default'].createElement( 'div', { className: 'Select-placeholder' }, this.props.placeholder ) : null; } var onClick = this.props.onValueClick ? this.handleValueClick : null; if (this.props.multi) { return valueArray.map(function (value, i) { return _react2['default'].createElement( ValueComponent, { id: _this4._instancePrefix + '-value-' + i, instancePrefix: _this4._instancePrefix, disabled: _this4.props.disabled || value.clearableValue === false, key: 'value-' + i + '-' + value[_this4.props.valueKey], onClick: onClick, onRemove: _this4.removeValue, value: value }, renderLabel(value, i), _react2['default'].createElement( 'span', { className: 'Select-aria-only' }, ' ' ) ); }); } else if (!this.state.inputValue) { if (isOpen) onClick = null; return _react2['default'].createElement( ValueComponent, { id: this._instancePrefix + '-value-item', disabled: this.props.disabled, instancePrefix: this._instancePrefix, onClick: onClick, value: valueArray[0] }, renderLabel(valueArray[0]) ); } }, renderInput: function renderInput(valueArray, focusedOptionIndex) { var _this5 = this; if (this.props.inputRenderer) { return this.props.inputRenderer(); } else { var _classNames; var className = (0, _classnames2['default'])('Select-input', this.props.inputProps.className); var isOpen = !!this.state.isOpen; var ariaOwns = (0, _classnames2['default'])((_classNames = {}, _defineProperty(_classNames, this._instancePrefix + '-list', isOpen), _defineProperty(_classNames, this._instancePrefix + '-backspace-remove-message', this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue), _classNames)); // TODO: Check how this project includes Object.assign() var inputProps = _extends({}, this.props.inputProps, { role: 'combobox', 'aria-expanded': '' + isOpen, 'aria-owns': ariaOwns, 'aria-haspopup': '' + isOpen, 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-labelledby': this.props['aria-labelledby'], 'aria-label': this.props['aria-label'], className: className, tabIndex: this.props.tabIndex, onBlur: this.handleInputBlur, onChange: this.handleInputChange, onFocus: this.handleInputFocus, ref: function ref(_ref) { return _this5.input = _ref; }, required: this.state.required, value: this.state.inputValue }); if (this.props.disabled || !this.props.searchable) { var _props$inputProps = this.props.inputProps; var inputClassName = _props$inputProps.inputClassName; var divProps = _objectWithoutProperties(_props$inputProps, ['inputClassName']); return _react2['default'].createElement('div', _extends({}, divProps, { role: 'combobox', 'aria-expanded': isOpen, 'aria-owns': isOpen ? this._instancePrefix + '-list' : this._instancePrefix + '-value', 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', className: className, tabIndex: this.props.tabIndex || 0, onBlur: this.handleInputBlur, onFocus: this.handleInputFocus, ref: function (ref) { return _this5.input = ref; }, 'aria-readonly': '' + !!this.props.disabled, style: { border: 0, width: 1, display: 'inline-block' } })); } if (this.props.autosize) { return _react2['default'].createElement(_reactInputAutosize2['default'], _extends({}, inputProps, { minWidth: '5px' })); } return _react2['default'].createElement( 'div', { className: className }, _react2['default'].createElement('input', inputProps) ); } }, renderClear: function renderClear() { if (!this.props.clearable || !this.props.value || this.props.value === 0 || this.props.multi && !this.props.value.length || this.props.disabled || this.props.isLoading) return; return _react2['default'].createElement( 'span', { className: 'Select-clear-zone', title: this.props.multi ? this.props.clearAllText : this.props.clearValueText, 'aria-label': this.props.multi ? this.props.clearAllText : this.props.clearValueText, onMouseDown: this.clearValue, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEndClearValue }, _react2['default'].createElement('span', { className: 'Select-clear', dangerouslySetInnerHTML: { __html: '&times;' } }) ); }, renderArrow: function renderArrow() { var onMouseDown = this.handleMouseDownOnArrow; var arrow = this.props.arrowRenderer({ onMouseDown: onMouseDown }); return _react2['default'].createElement( 'span', { className: 'Select-arrow-zone', onMouseDown: onMouseDown }, arrow ); }, filterOptions: function filterOptions(excludeOptions) { var filterValue = this.state.inputValue; var options = this.props.options || []; if (this.props.filterOptions) { // Maintain backwards compatibility with boolean attribute var filterOptions = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : _utilsDefaultFilterOptions2['default']; return filterOptions(options, filterValue, excludeOptions, { filterOption: this.props.filterOption, ignoreAccents: this.props.ignoreAccents, ignoreCase: this.props.ignoreCase, labelKey: this.props.labelKey, matchPos: this.props.matchPos, matchProp: this.props.matchProp, valueKey: this.props.valueKey }); } else { return options; } }, onOptionRef: function onOptionRef(ref, isFocused) { if (isFocused) { this.focused = ref; } }, renderMenu: function renderMenu(options, valueArray, focusedOption) { if (options && options.length) { return this.props.menuRenderer({ focusedOption: focusedOption, focusOption: this.focusOption, instancePrefix: this._instancePrefix, labelKey: this.props.labelKey, onFocus: this.focusOption, onSelect: this.selectValue, optionClassName: this.props.optionClassName, optionComponent: this.props.optionComponent, optionRenderer: this.props.optionRenderer || this.getOptionLabel, options: options, selectValue: this.selectValue, valueArray: valueArray, valueKey: this.props.valueKey, onOptionRef: this.onOptionRef }); } else if (this.props.noResultsText) { return _react2['default'].createElement( 'div', { className: 'Select-noresults' }, this.props.noResultsText ); } else { return null; } }, renderHiddenField: function renderHiddenField(valueArray) { var _this6 = this; if (!this.props.name) return; if (this.props.joinValues) { var value = valueArray.map(function (i) { return stringifyValue(i[_this6.props.valueKey]); }).join(this.props.delimiter); return _react2['default'].createElement('input', { type: 'hidden', ref: function (ref) { return _this6.value = ref; }, name: this.props.name, value: value, disabled: this.props.disabled }); } return valueArray.map(function (item, index) { return _react2['default'].createElement('input', { key: 'hidden.' + index, type: 'hidden', ref: 'value' + index, name: _this6.props.name, value: stringifyValue(item[_this6.props.valueKey]), disabled: _this6.props.disabled }); }); }, getFocusableOptionIndex: function getFocusableOptionIndex(selectedOption) { var options = this._visibleOptions; if (!options.length) return null; var focusedOption = this.state.focusedOption || selectedOption; if (focusedOption && !focusedOption.disabled) { var focusedOptionIndex = options.indexOf(focusedOption); if (focusedOptionIndex !== -1) { return focusedOptionIndex; } } for (var i = 0; i < options.length; i++) { if (!options[i].disabled) return i; } return null; }, renderOuter: function renderOuter(options, valueArray, focusedOption) { var _this7 = this; var menu = this.renderMenu(options, valueArray, focusedOption); if (!menu) { return null; } return _react2['default'].createElement( 'div', { ref: function (ref) { return _this7.menuContainer = ref; }, className: 'Select-menu-outer', style: this.props.menuContainerStyle }, _react2['default'].createElement( 'div', { ref: function (ref) { return _this7.menu = ref; }, role: 'listbox', className: 'Select-menu', id: this._instancePrefix + '-list', style: this.props.menuStyle, onScroll: this.handleMenuScroll, onMouseDown: this.handleMouseDownOnMenu }, menu ) ); }, render: function render() { var _this8 = this; var valueArray = this.getValueArray(this.props.value); var options = this._visibleOptions = this.filterOptions(this.props.multi ? this.getValueArray(this.props.value) : null); var isOpen = this.state.isOpen; if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false; var focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]); var focusedOption = null; if (focusedOptionIndex !== null) { focusedOption = this._focusedOption = options[focusedOptionIndex]; } else { focusedOption = this._focusedOption = null; } var className = (0, _classnames2['default'])('Select', this.props.className, { 'Select--multi': this.props.multi, 'Select--single': !this.props.multi, 'is-disabled': this.props.disabled, 'is-focused': this.state.isFocused, 'is-loading': this.props.isLoading, 'is-open': isOpen, 'is-pseudo-focused': this.state.isPseudoFocused, 'is-searchable': this.props.searchable, 'has-value': valueArray.length }); var removeMessage = null; if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) { removeMessage = _react2['default'].createElement( 'span', { id: this._instancePrefix + '-backspace-remove-message', className: 'Select-aria-only', 'aria-live': 'assertive' }, this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey]) ); } return _react2['default'].createElement( 'div', { ref: function (ref) { return _this8.wrapper = ref; }, className: className, style: this.props.wrapperStyle }, this.renderHiddenField(valueArray), _react2['default'].createElement( 'div', { ref: function (ref) { return _this8.control = ref; }, className: 'Select-control', style: this.props.style, onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleTouchEnd, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove }, _react2['default'].createElement( 'span', { className: 'Select-multi-value-wrapper', id: this._instancePrefix + '-value' }, this.renderValue(valueArray, isOpen), this.renderInput(valueArray, focusedOptionIndex) ), removeMessage, this.renderLoading(), this.renderClear(), this.renderArrow() ), isOpen ? this.renderOuter(options, !this.props.multi ? valueArray : null, focusedOption) : null ); } }); exports['default'] = Select; module.exports = exports['default'];
ace.define("ace/mode/sh_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { "use strict"; var oop = acequire("../lib/oop"); var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; var reservedKeywords = exports.reservedKeywords = ( '!|{|}|case|do|done|elif|else|'+ 'esac|fi|for|if|in|then|until|while|'+ '&|;|export|local|read|typeset|unset|'+ 'elif|select|set' ); var languageConstructs = exports.languageConstructs = ( '[|]|alias|bg|bind|break|builtin|'+ 'cd|command|compgen|complete|continue|'+ 'dirs|disown|echo|enable|eval|exec|'+ 'exit|fc|fg|getopts|hash|help|history|'+ 'jobs|kill|let|logout|popd|printf|pushd|'+ 'pwd|return|set|shift|shopt|source|'+ 'suspend|test|times|trap|type|ulimit|'+ 'umask|unalias|wait' ); var ShHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "keyword": reservedKeywords, "support.function.builtin": languageConstructs, "invalid.deprecated": "debugger" }, "identifier"); var integer = "(?:(?:[1-9]\\d*)|(?:0))"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; var fileDescriptor = "(?:&" + intPart + ")"; var variableName = "[a-zA-Z_][a-zA-Z0-9_]*"; var variable = "(?:(?:\\$" + variableName + ")|(?:" + variableName + "=))"; var builtinVariable = "(?:\\$(?:SHLVL|\\$|\\!|\\?))"; var func = "(?:" + variableName + "\\s*\\(\\))"; this.$rules = { "start" : [{ token : "constant", regex : /\\./ }, { token : ["text", "comment"], regex : /(^|\s)(#.*)$/ }, { token : "string", regex : '"', push : [{ token : "constant.language.escape", regex : /\\(?:[$abeEfnrtv\\'"]|x[a-fA-F\d]{1,2}|u[a-fA-F\d]{4}([a-fA-F\d]{4})?|c.|\d{1,3})/ }, { token : "constant", regex : /\$\w+/ }, { token : "string", regex : '"', next: "pop" }, { defaultToken: "string" }] }, { regex : "<<<", token : "keyword.operator" }, { stateName: "heredoc", regex : "(<<-?)(\\s*)(['\"`]?)([\\w\\-]+)(['\"`]?)", onMatch : function(value, currentState, stack) { var next = value[2] == '-' ? "indentedHeredoc" : "heredoc"; var tokens = value.split(this.splitRegex); stack.push(next, tokens[4]); return [ {type:"constant", value: tokens[1]}, {type:"text", value: tokens[2]}, {type:"string", value: tokens[3]}, {type:"support.class", value: tokens[4]}, {type:"string", value: tokens[5]} ]; }, rules: { heredoc: [{ onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }], indentedHeredoc: [{ token: "string", regex: "^\t+" }, { onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }] } }, { regex : "$", token : "empty", next : function(currentState, stack) { if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc") return stack[0]; return currentState; } }, { token : "variable.language", regex : builtinVariable }, { token : "variable", regex : variable }, { token : "support.function", regex : func }, { token : "support.function", regex : fileDescriptor }, { token : "string", // ' string start : "'", end : "'" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : keywordMapper, regex : "[a-zA-Z_][a-zA-Z0-9_]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|~|<|>|<=|=>|=|!=" }, { token : "paren.lparen", regex : "[\\[\\(\\{]" }, { token : "paren.rparen", regex : "[\\]\\)\\}]" } ] }; this.normalizeRules(); }; oop.inherits(ShHighlightRules, TextHighlightRules); exports.ShHighlightRules = ShHighlightRules; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { "use strict"; var oop = acequire("../../lib/oop"); var Range = acequire("../../range").Range; var BaseFoldMode = acequire("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/)#(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) { "use strict"; var oop = acequire("../../lib/oop"); var Behaviour = acequire("../behaviour").Behaviour; var TokenIterator = acequire("../../token_iterator").TokenIterator; var lang = acequire("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.index; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = {rangeCount: editor.multiSelect.rangeCount}; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var getWrapped = function(selection, selected, opening, closing) { var rowDiff = selection.end.row - selection.start.row; return { text: opening + selected + closing, selection: [ 0, selection.start.column + 1, rowDiff, selection.end.column + (rowDiff ? 0 : 1) ] }; }; var CstyleBehaviour = function() { this.add("braces", "insertion", function(state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '{', '}'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function(state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '(', ')'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function(state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '[', ']'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, quote, quote); } else if (!selected) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); var rightChar = line.substring(cursor.column, cursor.column + 1); var token = session.getTokenAt(cursor.row, cursor.column); var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); if (leftChar == "\\" && token && /escape/.test(token.type)) return null; var stringBefore = token && /string/.test(token.type); var stringAfter = !rightToken || /string/.test(rightToken.type); var pair; if (rightChar == quote) { pair = stringBefore !== stringAfter; } else { if (stringBefore && !stringAfter) return null; // wrap string with different quote if (stringBefore && stringAfter) return null; // do not pair quotes inside strings var wordRe = session.$mode.tokenRe; wordRe.lastIndex = 0; var isWordBefore = wordRe.test(leftChar); wordRe.lastIndex = 0; var isWordAfter = wordRe.test(leftChar); if (isWordBefore || isWordAfter) return null; // before or after alphanumeric if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) return null; // there is rightChar and it isn't closing pair = true; } return { text: pair ? quote + quote : "", selection: [1,1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); ace.define("ace/mode/sh",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/sh_highlight_rules","ace/range","ace/mode/folding/cstyle","ace/mode/behaviour/cstyle"], function(acequire, exports, module) { "use strict"; var oop = acequire("../lib/oop"); var TextMode = acequire("./text").Mode; var ShHighlightRules = acequire("./sh_highlight_rules").ShHighlightRules; var Range = acequire("../range").Range; var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; var Mode = function() { this.HighlightRules = ShHighlightRules; this.foldingRules = new CStyleFoldMode(); this.$behaviour = new CstyleBehaviour(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "#"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; var outdents = { "pass": 1, "return": 1, "raise": 1, "break": 1, "continue": 1 }; this.checkOutdent = function(state, line, input) { if (input !== "\r\n" && input !== "\r" && input !== "\n") return false; var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens; if (!tokens) return false; do { var last = tokens.pop(); } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); if (!last) return false; return (last.type == "keyword" && outdents[last.value]); }; this.autoOutdent = function(state, doc, row) { row += 1; var indent = this.$getIndent(doc.getLine(row)); var tab = doc.getTabString(); if (indent.slice(-tab.length) == tab) doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); }; this.$id = "ace/mode/sh"; }).call(Mode.prototype); exports.Mode = Mode; });
WYMeditor.STRINGS['pt-br'] = { Strong: 'Resaltar', Emphasis: 'Enfatizar', Superscript: 'Sobre escrito', Subscript: 'Sub escrito ', Ordered_List: 'Lista ordenada', Unordered_List: 'Lista desordenada', Indent: 'Indentado', Outdent: 'Desidentar', Undo: 'Desfazer', Redo: 'Refazer', Link: 'Link', Unlink: 'Remover Link', Image: 'Imagem', Table: 'Tabela', HTML: 'HTML', Paragraph: 'Parágrafo', Heading_1: 'Título 1', Heading_2: 'Título 2', Heading_3: 'Título 3', Heading_4: 'Título 4', Heading_5: 'Título 5', Heading_6: 'Título 6', Preformatted: 'Preformatado', Blockquote: 'Citação', Table_Header: 'Título de tabela', URL: 'URL', Title: 'Título', Alternative_Text: 'Texto alternativo', Caption: 'Legenda', Summary: 'Summary', Number_Of_Rows: 'Número de linhas', Number_Of_Cols: 'Número de colunas', Submit: 'Enviar', Cancel: 'Cancelar', Choose: 'Selecionar', Preview: 'Previsualizar', Paste_From_Word: 'Copiar do Word', Tools: 'Ferramentas', Containers: 'Conteneiners', Classes: 'Classes', Status: 'Estado', Source_Code: 'Código fonte' };
/* * grunt-replace * * Copyright (c) 2014 outaTiME * Licensed under the MIT license. * https://github.com/outaTiME/grunt-replace/blob/master/LICENSE-MIT */ 'use strict'; // plugin module.exports = function (grunt) { var path = require('path'); var fs = require('fs'); var chalk = require('chalk'); var Applause = require('applause'); grunt.registerMultiTask('replace', 'Replace text patterns with applause.', function () { // took options var options = this.options({ encoding: grunt.file.defaultEncoding, mode: false, processContentExclude: [], patterns: [], excludeBuiltins: false, force: true, verbose: true }); // attach builtins var patterns = options.patterns; if (options.excludeBuiltins !== true) { patterns.push({ match: '__SOURCE_FILE__', replacement: function (match, offset, string, source, target) { return source; } }, { match: '__SOURCE_PATH__', replacement: function (match, offset, string, source, target) { return path.dirname(source); } }, { match: '__SOURCE_FILENAME__', replacement: function (match, offset, string, source, target) { return path.basename(source); } }, { match: '__TARGET_FILE__', replacement: function (match, offset, string, source, target) { return target; } }, { match: '__TARGET_PATH__', replacement: function (match, offset, string, source, target) { return path.dirname(target); } }, { match: '__TARGET_FILENAME__', replacement: function (match, offset, string, source, target) { return path.basename(target); } }); } // create applause instance var applause = Applause.create(options); // took code from copy task var dest; var isExpandedPair; this.files.forEach(function (filePair) { isExpandedPair = filePair.orig.expand || false; filePair.src.forEach(function (src) { if (detectDestType(filePair.dest) === 'directory') { dest = (isExpandedPair) ? filePair.dest : unixifyPath(path.join(filePair.dest, src)); } else { dest = filePair.dest; } if (grunt.file.isDir(src)) { grunt.file.mkdir(dest); } else { replace(src, dest, options, applause); if (options.mode !== false) { fs.chmodSync(dest, (options.mode === true) ? fs.lstatSync(src).mode : options.mode); } } }); }); }); var detectDestType = function (dest) { var lastChar = dest.slice(-1); if (lastChar === '/') { return 'directory'; } else { return 'file'; } }; var unixifyPath = function (filepath) { if (process.platform === 'win32') { return filepath.replace(/\\/g, '/'); } else { return filepath; } }; var replace = function (source, target, options, applause) { grunt.file.copy(source, target, { encoding: options.encoding, process: function (contents) { var result = applause.replace(contents, [source, target]); // force contents if (result === false && options.force === true) { result = contents; } if (result !== false && options.verbose === true) { grunt.log.writeln('Replace ' + chalk.cyan(source) + ' → ' + chalk.green(target)); } return result; }, noProcess: options.noProcess || options.processContentExclude }); }; };
//Author : @arboshiki /** * Generates random string of n length. * String contains only letters and numbers * * @param {int} n * @returns {String} */ Math.randomString = function (n) { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < n; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; }; /** * This function is for HTML element style attribute. * It converts the style attribute to css object * * @returns {object} */ String.prototype.getCss = function () { var css = {}; var style = this.valueOf().split(';'); for (var i = 0; i < style.length; i++) { style[i] = $.trim(style[i]); if (style[i]) { var s = style[i].split(':'); css[$.trim(s[0])] = $.trim(s[1]); } } return css; }; String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ""); }; String.prototype.toCamel = function () { return this.replace(/(\-[a-z])/g, function ($1) { return $1.toUpperCase().replace('-', ''); }); }; String.prototype.toDash = function () { return this.replace(/([A-Z])/g, function ($1) { return "-" + $1.toLowerCase(); }); }; String.prototype.toUnderscore = function () { return this.replace(/([A-Z])/g, function ($1) { return "_" + $1.toLowerCase(); }); }; /** * Checks if number is between two numbers * * @param {number} num1 * @param {number} num2 * @param {boolean} including "include these numbers in comparison or not" default false * @returns boolean */ Number.prototype.isBetween = function (num1, num2, including) { if (!including) { if (this.valueOf() < num2 && this.valueOf() > num1) { return true; } } else { if (this.valueOf() <= num2 && this.valueOf() >= num1) { return true; } } return false; }; /** * Inserts element at specific index in given elements children * * @param {number} i * @param {string} selector * @returns {undefined} */ $.fn.insertAt = function (i, selector) { var $object = selector; if (typeof selector === 'string') { $object = $(selector); } i = Math.min($object.children().length, i); if (i == 0) { $object.prepend(this); return this; } var oldIndex = this.data('index'); if (!i || isNaN(i)){ i = $object.children().length - 1; } this.attr('data-index', i); var $el = $object.children().eq(i - 1); if ($el.length){ $el.after(this); } else { $object.append(this); } $object.children().each(function (index, el) { var $el = $(el); if (oldIndex < i && index > oldIndex && index <= i) { $el.attr('data-index', parseInt($el.data('data-index'), 10) - 1); } else if (oldIndex >= i && index > i && index <= oldIndex) { $el.attr('data-index', parseInt($el.attr('data-index'), 10) + 1); } }); return this; }; $.fn.disableSelection = function () { return this .attr('unselectable', 'on') .css('user-select', 'none') .on('selectstart', false); }; $.fn.enableSelection = function () { return this .removeAttr('unselectable') .css('user-select', 'initial') .off('selectstart'); }; $(function () { var STORAGE_PREFIX = 'lobipanel_'; var StorageLocal = function(){ this.saveChildPositions = function(parentInnerId, positions){ if (positions !== undefined) { localStorage.setItem(STORAGE_PREFIX + 'parent_' + parentInnerId, JSON.stringify(positions)); } }; this.savePanelParams = function(innerId, storage){ localStorage.setItem(STORAGE_PREFIX + innerId, JSON.stringify(storage)); }; this.getAllPanelPositions = function(){ var parents = []; for (var i in localStorage) { if (i.indexOf(STORAGE_PREFIX + 'parent_') === 0) { var innerParentId = i.replace(STORAGE_PREFIX + 'parent_', ''); var $parent = $('.lobipanel-parent-sortable[data-inner-id=' + innerParentId + ']'); if ($parent.length) { parents[innerParentId] = JSON.parse(localStorage[i]); } } } return parents; }; this.getPanelStorage = function(innerId){ var item = localStorage.getItem(STORAGE_PREFIX + innerId); return JSON.parse(item || null) || {}; }; }; var LobiPanel = function ($el, options) { var me = this; this.hasRandomId = false; this.storage = null; this.$el = $el; if (!me.$el.data('inner-id')) { me.hasRandomId = true; me.$el.attr('data-inner-id', Math.randomString(10)); } this.innerId = me.$el.data('inner-id'); this.$options = me._processInput(options); me.$heading = this.$el.find('>.panel-heading'); me.$body = this.$el.find('>.panel-body'); me._init(); me.$el.css('display', 'none'); me._applyState(me.$options.state, me.$options.stateParams); me.$el.css('display', 'block'); // me._applyIndex(me.$options.initialIndex); }; LobiPanel.prototype = { _processInput: function (options) { var me = this; if (!options) { options = {}; } if (!me.hasRandomId) { if (!this.storageObject){ this.storageObject = new StorageLocal(); } me.storage = this.storageObject.getPanelStorage(me.innerId); } var opts = me._getOptionsFromAttributes(); // window.console.log(opts); options = $.extend({}, $.fn.lobiPanel.DEFAULTS, me.storage, options, opts); var objects = ['unpin', 'reload', 'expand', 'minimize', 'close', 'editTitle']; for (var i = 0; i < objects.length; i++) { var prop = objects[i]; if (typeof options[prop] === 'object') { options[prop] = $.extend({}, $.fn.lobiPanel.DEFAULTS[prop], options[prop], opts[prop]); } } return options; }, _init: function () { var me = this; me.$el.addClass('lobipanel'); me.$heading.append(me._generateControls()); //------------------------------------------------------------------------------ var parent = me.$el.parent(); me._appendInnerIdToParent(parent, me.innerId); me._enableSorting(); me._onToggleIconsBtnClick(); me._enableResponsiveness(); me._setBodyHeight(); if (me.$options.autoload) { me.load(); } var maxWidth = 'calc(100% - ' + me.$heading.find('.dropdown-menu').children().length * me.$heading.find('.dropdown-menu li').first().outerWidth() + "px)"; me.$heading.find('.panel-title').css('max-width', maxWidth); if (me.getParam('panelTitle')) { me.$heading.find('.panel-title').html(me.getParam('panelTitle')); } var style = me.getParam('panelStyle'); if (style) { me.applyStyle(style.bg, style.text); } // me.savepanelPositions(); me._triggerEvent("init"); }, /** * Checks if panel is initialized. Panel is initialized if it has * lobipanel class and data-inner-id="" attribute * * @returns {boolean} */ isPanelInit: function () { var me = this; return me.$el.hasClass('lobipanel') && me.$el.data('inner-id'); }, /** * Checks if panel is pinned or unpinned * * @returns {Boolean} */ isPinned: function () { var me = this; return !me.$el.hasClass('panel-unpin'); }, /** * Pin the panel * * @returns {LobiPanel} */ pin: function () { var me = this; //disable resize functionality me.disableResize(); me.disableDrag(); //remove on panel click event (which brings the panel into front) me._offPanelClick(); //remove panel-unpin class me.$el.removeClass('panel-unpin') //save current position, z-index and size to use it for later unpin .attr('old-style', me.$el.attr('style')) // .removeAttr('style') .css('position', 'relative'); var toRemoveProperties = [ 'position', 'z-index', 'left', 'top', 'width', 'height' ]; for (var i in toRemoveProperties) { me.$el.css(toRemoveProperties[i], ''); } me.$body.css({ width: '', height: '' }); me._setBodyHeight(); me._insertInParent(); me._enableSorting(); return me; }, /** * Unpin the panel * * @returns {LobiPanel} */ unpin: function () { var me = this; if (me.$el.hasClass("panel-collapsed")) { return me; } me._disableSorting(); if (me.$el.attr('old-style')) { me.$el.attr('style', me.$el.attr('old-style')); } else { var width = me.$el.width(); var height = me.$el.height(); var left = Math.max(0, (($(window).width() - me.$el.outerWidth()) / 2)); var top = Math.max(0, ($(document).scrollTop() + ($(window).height() - me.$el.outerHeight()) / 2)); me.$el.css({ left: left, top: top, width: width, height: height }); } var res = me._getMaxZIndex(); me.$el.css('z-index', res['z-index'] + 1); me._onPanelClick(); me.$el.addClass('panel-unpin'); $('body').append(me.$el); var panelWidth = me._getAvailableWidth(me.$el.width()); var panelHeight = me._getAvailableHeight(me.$el.height()); me.$el.css({ position: 'absolute', width: panelWidth, height: panelHeight }); //we give .panel-body to width and height in order .panel-body to start scroling var bHeight = me._calculateBodyHeight(panelHeight); var bWidth = me._calculateBodyWidth(panelWidth); me.$body.css({ width: bWidth, height: bHeight }); if (me.$options.draggable) { me.enableDrag(); } if (me.$options.resize !== 'none') { me.enableResize(); } return me; }, /** * Toggles (pin or unpin) the panel * * @returns {LobiPanel} */ togglePin: function () { var me = this; if (this.isPinned()) { this.unpin(); } else { this.pin(); } return me; }, /** * Checks if panel is minimized or not. It does not matter if panel is pinned or not * * @returns {Boolean} */ isMinimized: function () { var me = this; return me.$el.hasClass('panel-minimized') || me.$el.hasClass('panel-collapsed'); }, /** * Minimize the panel. If panel is pinned it is minimized on its place * if panel is unpinned it is minimized at the bottom of the page * * @returns {LobiPanel} */ minimize: function () { var me = this; me._triggerEvent("beforeMinimize"); if (me.isMinimized()) { return me; } if (me.isPinned()) { me.$body.slideUp(); me.$el.find('.panel-footer').slideUp(); me.$el.addClass('panel-collapsed'); me._saveState('collapsed'); me._changeClassOfControl(me.$heading.find('[data-func="minimize"]')); } else { me.disableTooltips(); //get footer where we need to put panel var footer = me._getFooterForMinimizedPanels(); //find other panels which are already inside footer var children = footer.find('>*'); var left, top; //get top coordinate of footer top = footer.offset().top; //if there are no other panels inside footer, this panel will be first //and its left coordinate will be footer's left coordinate if (children.length === 0) { left = footer.offset().left; } else { //if there exist panels inside footer, then this panel's left //coordinate will be last panel's (in footer) right coordinate var ch = $(children[children.length - 1]); left = ch.offset().left + ch.width(); } //if panel was not expanded and it was jus unpin we need to save //panel's style if (!me.$el.hasClass('panel-expanded')) { me.$el.attr('old-style', me.$el.attr('style')); } me.$el.animate({ left: left, top: top, width: 200, height: footer.height() }, 100, function () { //if panel was expanded on full screen before we minimize it //after minimization we remove 'panel-expanded' class and we change icon if (me.$el.hasClass('panel-expanded')) { me.$el.removeClass('panel-expanded'); me.$el.find('.panel-heading [data-func=expand] .' + LobiPanel.PRIVATE_OPTIONS.iconClass) .removeClass(me.$options.expand.icon2) .addClass(me.$options.expand.icon) ; } //we add 'panel-minimized' class me.$el.addClass('panel-minimized'); me.$el.removeAttr('style'); me.disableDrag(); me.disableResize(); me._expandOnHeaderClick(); //animation was made and panel is positioned in place we it must be //so we append panel into footer footer.append(me.$el); $('body').addClass('lobipanel-minimized'); var maxWidth = 'calc(100% - ' + me.$heading.find('.dropdown-menu li>a:visible').length * me.$heading.find('.dropdown-menu li>a:visible').first().outerWidth() + "px)"; me.$heading.find('.panel-title').css('max-width', maxWidth); me._saveState('minimized'); me._triggerEvent("onMinimize"); }); } return me; }, /** * Maximize the panel. This method works for minimized panel. * If panel is pinned it's maximized on its place. * If panel is unpinned it's maximized on position from which it was minimized * * @returns {LobiPanel} */ maximize: function () { var me = this; me._triggerEvent("beforeMaximize"); if (!me.isMinimized()) { return me; } if (me.isPinned()) { me.$body.slideDown(); me.$el.find('.panel-footer').slideDown(); me.$el.removeClass('panel-collapsed'); me._saveState('pinned'); me._changeClassOfControl(me.$heading.find('[data-func="minimize"]')); } else { me.enableTooltips(); //we get css style which was saved before minimization var css = me.$el.attr('old-style').getCss(); //we give panel these css properties, coz animation work me.$el.css({ position: css.position || 'fixed', 'z-index': css['z-index'], left: me.$el.offset().left, top: me.$el.offset().top, width: me.$el.width(), height: me.$el.height() }); //we append panel into body $('body').append(me.$el); //It is not possible to make animations to these propeties and we remove it delete css['position']; delete css['z-index']; // css['position'] = 'absolute'; //and we animate panel to its saved style me.$el.animate(css, 100, function () { //we remove position property from style, before 'panel-unpin' //class has it to absolute me.$el.css('position', ''); me.$el.removeClass('panel-minimized'); //as panel is already in its place we remove 'old-style' property me.$el.removeAttr('old-style'); if (me.$options.draggable) { me.enableDrag(); } me.enableResize(); me._removeExpandOnHeaderClick(); //If there are no other elements inside footer, remove it also var footer = me._getFooterForMinimizedPanels(); if (footer.children().length === 0) { footer.remove(); } $('body').removeClass('lobipanel-minimized') .addClass('lobipanel-minimized'); var maxWidth = 'calc(100% - ' + me.$heading.find('.dropdown-menu li').length * me.$heading.find('.dropdown-menu li').first().outerWidth() + "px)"; me.$heading.find('.panel-title').css('max-width', maxWidth); me._updateUnpinnedState(); me._triggerEvent("onMaximize"); }); } return me; }, /** * Toggles (minimize or maximize) the panel state. * * @returns {LobiPanel} */ toggleMinimize: function () { var me = this; if (me.isMinimized()) { me.maximize(); } else { me.minimize(); } return me; }, /** * Checks if panel is on full screen * * @returns {Boolean} */ isOnFullScreen: function () { var me = this; return me.$el.hasClass('panel-expanded'); }, /** * Expands the panel to full screen size * * @returns {LobiPanel} */ toFullScreen: function () { var me = this; me._triggerEvent("beforeFullScreen"); if (me.$el.hasClass("panel-collapsed")) { return me; } me.$el.attr('data-index', me.$el.index()); me._changeClassOfControl(me.$heading.find('[data-func="expand"]')); me.$el.css('position', 'fixed'); var res = me._getMaxZIndex(); //if panel is pinned or minimized, its position is not absolute and //animation will not work correctly so we change its position and //other css properties and we append panel into body if (me.isPinned() || me.isMinimized()) { me.enableTooltips(); me.$el.css({ "z-index": res["z-index"] + 1, left: me.$el.offset().left, top: me.$el.offset().top - $(window).scrollTop(), width: me.$el.width(), height: me.$el.height() }); $('body').append(me.$el); //If we are expanding panel to full screen from footer and in footer there are no more elements //remove footer also var footer = me._getFooterForMinimizedPanels(); if (footer.children().length === 0) { footer.remove(); } } else { me.$body.css({ width: '', height: '' }); me._setBodyHeight(); } //if panel is not minimized we save its style property, because when //toSmallSize() method is called panel needs to have style, it had before calling method // toFullScreen() if (!me.isMinimized()) { me.$el.attr('old-style', me.$el.attr('style')); me.disableResize(); } else { me.$el.removeClass('panel-minimized'); me._removeExpandOnHeaderClick(); } //get toolbar var toolbar = $('.' + LobiPanel.PRIVATE_OPTIONS.toolbarClass); var toolbarHeight = toolbar.outerHeight() || 0; me.$el.animate({ width: $(window).width(), height: $(window).height() - toolbarHeight, left: 0, top: 0 }, me.$options.expandAnimation, function () { me.$el.css({ width: '', height: '', right: 0, bottom: toolbarHeight }); me.$el.addClass('panel-expanded'); $('body').css('overflow', 'hidden'); me.$body.css({ width: me._calculateBodyWidth(me.$el.width()), height: me._calculateBodyHeight(me.$el.height()) }); me.disableDrag(); if (me.isPinned()) { me._disableSorting(); } me._saveState('fullscreen'); me._triggerEvent("onFullScreen"); }); return me; }, /** * Collapse the panel to small size * * @returns {LobiPanel} */ toSmallSize: function () { var me = this; me._triggerEvent("beforeSmallSize"); me._changeClassOfControl(me.$heading.find('[data-func="expand"]')); var css = me.$el.attr('old-style').getCss(); var toRemoveProperties = [ 'position', 'z-index', 'left', 'top', 'width', 'height' ]; //we get css properties from old-style (saved before expanding) //and we animate panel to this css properties me.$el.animate({ position: 'absolute', left: css.left, top: css.top, width: css.width, height: css.height, right: css.right, bottom: css.bottom }, me.$options.collapseAnimation, function () { //we remove old-style as we do not need it me.$el.removeAttr('old-style'); //if panel is pinned we also remove its style attribute and we //append panel in its parent element if (!me.$el.hasClass('panel-unpin')) { for (var i in toRemoveProperties) { me.$el.css(toRemoveProperties[i], ''); } // me.$el.removeAttr('style'); me._insertInParent(); me._enableSorting(); } else { if (me.$options.draggable) { me.enableDrag(); } me.enableResize(); } me.$el.removeClass('panel-expanded'); $('body').css('overflow', 'auto'); var bWidth = ''; var bHeight = ''; if (!me.isPinned()) { bWidth = me._calculateBodyWidth(me.getWidth()); bHeight = me._calculateBodyHeight(me.getHeight()); } else if (me.$options.bodyHeight !== 'auto') { bHeight = me.$options.bodyHeight; } if ( me.isPinned()) { me._saveState('pinned'); } else { me._updateUnpinnedState(); } me.$body.css({ width: bWidth, height: bHeight }); me._triggerEvent("onSmallSize"); }); return me; }, /** * Toggles (changes to full screen size or to small size) the panel size * * @returns {LobiPanel} */ toggleSize: function () { var me = this; if (me.isOnFullScreen()) { me.toSmallSize(); } else { me.toFullScreen(); } return me; }, /** * Closes the panel. Removes it from document * * @param {number} animationDuration * @returns {LobiPanel} */ close: function (animationDuration) { var me = this, animationDuration = animationDuration === undefined ? 100 : animationDuration; me._triggerEvent('beforeClose'); me.$el.hide(animationDuration, function () { if (me.isOnFullScreen()) { $('body').css('overflow', 'auto'); } me._triggerEvent('onClose'); me.$el.remove(); var footer = me._getFooterForMinimizedPanels(); if (footer.children().length === 0) { footer.remove(); } }); return me; }, /** * Moves unpinned panel to given position. * This method will do nothing if panel is pinned * * @param {number} left * @param {number} top * @param {number} animationDuration * @returns {LobiPanel} */ setPosition: function (left, top, animationDuration) { var me = this, animationDuration = animationDuration === undefined ? 100 : animationDuration; //this method works only if panel is not pinned if (me.isPinned()) { return me; } me.$el.animate({ 'left': left, 'top': top }, animationDuration); return me; }, /** * Set the width of the panel * * @param {number} w * @param {number} animationDuration * @returns {LobiPanel} */ setWidth: function (w, animationDuration) { var me = this, animationDuration = animationDuration === undefined ? 100 : animationDuration; if (me.isPinned()) { return me; } var bWidth = me._calculateBodyWidth(w); me.$el.animate({ width: w }, animationDuration); me.$body.animate({ width: bWidth }, animationDuration); return me; }, /** * Set the height of the panel * * @param {number} h * @param {number} animationDuration * @returns {LobiPanel} */ setHeight: function (h, animationDuration) { var me = this, animationDuration = animationDuration === undefined ? 100 : animationDuration; if (me.isPinned()) { return me; } var bHeight = me._calculateBodyHeight(h); me.$el.animate({ height: h }, animationDuration); me.$body.animate({ height: bHeight }, animationDuration); return me; }, /** * Set size (width and height) of the panel * * @param {number} w * @param {number} h * @param {number} animationDuration * @returns {LobiPanel} */ setSize: function (w, h, animationDuration) { var me = this, animationDuration = animationDuration === undefined ? 100 : animationDuration; if (me.isPinned()) { return me; } var bHeight = me._calculateBodyHeight(h); var bWidth = me._calculateBodyWidth(w); me.$el.animate({ height: h, width: w }, animationDuration); me.$body.animate({ height: bHeight, width: bWidth }, animationDuration); return me; }, /** * Get the position of the panel. * Returns object where x is left coordinate and y is top coordinate * * @returns {Object} */ getPosition: function () { var me = this; var offset = me.$el.offset(); return { x: offset.left, y: offset.top }; }, /** * Get width of the panel * * @returns {number} */ getWidth: function () { var me = this; return me.$el.width(); }, /** * Get height of the panel * * @returns {number} */ getHeight: function () { var me = this; return me.$el.height(); }, /** * If panel is overlapped by another panel this panel will be shown on front * (this panel will overlap other panels) * * @returns {LobiPanel} */ bringToFront: function () { var me = this; me._triggerEvent("beforeToFront"); var res = me._getMaxZIndex(); if (res['id'] === me.$el.data('inner-id')) { return me; } me.$el.css('z-index', res['z-index'] + 1); me._triggerEvent("onToFront"); return me; }, /** * Enable dragging of panel * * @returns {LobiPanel} */ enableDrag: function () { var me = this; me.$el.draggable({ handle: '.panel-heading', containment: me.$options.constrain, start: function () { me.$el.css('position', 'absolute'); }, stop: function () { me.$el.css('position', ''); me._updateUnpinnedState(); } }); return me; }, /** * Disable dragging of the panel * * @returns {LobiPanel} */ disableDrag: function () { var me = this; if (me.$el.hasClass('ui-draggable')) { me.$el.draggable("destroy"); } return me; }, /** * Enable resize of the panel * * @returns {LobiPanel} */ enableResize: function () { var me = this; var handles = false; if (me.$options.resize === 'vertical') { handles = 'n, s'; } else if (me.$options.resize === 'horizontal') { handles = 'e, w'; } else if (me.$options.resize === 'both') { handles = 'all'; } if (!handles) { return me; } me.$el.resizable({ minWidth: me.$options.minWidth, maxWidth: me.$options.maxWidth, minHeight: me.$options.minHeight, maxHeight: me.$options.maxHeight, handles: handles, start: function () { me.$el.disableSelection(); me._triggerEvent('resizeStart'); }, stop: function () { me.$el.enableSelection(); me._triggerEvent('resizeStop'); }, resize: function () { var bHeight = me._calculateBodyHeight(me.$el.height()); var bWidth = me._calculateBodyWidth(me.$el.width()); me.$body.css({ width: bWidth, height: bHeight }); me._updateUnpinnedState(); me._triggerEvent("onResize"); } }); return me; }, /** * Disable resize of the panel * * @returns {LobiPanel} */ disableResize: function () { var me = this; if (me.$el.hasClass('ui-resizable')) { me.$el.resizable("destroy"); } return me; }, /** * Start spinner of the panel loading * * @returns {LobiPanel} */ startLoading: function () { var me = this; var spinner = me._generateWindow8Spinner(); me.$el.append(spinner); var sp = spinner.find('.spinner'); sp.css('margin-top', 50); return me; }, /** * Stop spinner of the panel loading * * @returns {LobiPanel} */ stopLoading: function () { var me = this; me.$el.find('.spinner-wrapper').remove(); return me; }, /** * Set url. This url will be used to load data when Reload button is clicked * or user calls .load() method without url parameter * * @param {string} url * @returns {LobiPanel} */ setLoadUrl: function (url) { var me = this; me.$options.loadUrl = url; return me; }, /** * Load data into .panel-body. * params object is in format * { * url: '', //Optional: load url * data: 'PlainObject or String', //Optional: A plain object or string of parameters which is sent to the server with the request. * callback: 'function' //Optional: callback function which is called when load is finished * } * * @param {Object} params * @returns {LobiPanel} */ load: function (params) { var me = this; params = params || {}; if (typeof params === 'string') { params = {url: params}; } var url = params.url || me.$options.loadUrl, data = params.data || {}, callback = params.callback || null; if (!url) { return me; } me._triggerEvent("beforeLoad"); me.startLoading(); me.$body.load(url, data, function (result, status, xhr) { if (callback && typeof callback === 'function') { me.callback(result, status, xhr); } me.stopLoading(); me._triggerEvent("loaded", result, status, xhr); }); return me; }, /** * Destroy the LobiPanel instance * * @returns {jQuery} */ destroy: function () { var me = this; me.disableDrag(); me.disableResize(); me.$options.sortable = false; me._enableSorting(); me._removeInnerIdFromParent(me.innerId); me.$el.removeClass('lobipanel') .removeAttr('data-inner-id') .removeAttr('data-index') .removeData('lobiPanel'); me.$heading.find('.dropdown').remove(); return me.$el; }, /** * Creates input field to edit panel title * * @returns {LobiPanel} */ startTitleEditing: function () { var me = this; var title = me.$heading.find('.panel-title').text().trim(); var input = $('<input value="' + title + '"/>'); input.on('keydown', function (ev) { if (ev.which === 13) { me.finishTitleEditing(); } else if (ev.which === 27) { me.cancelTitleEditing(); } }); me.$heading.find('.panel-title') .data('old-title', title) .html("").append(input); input[0].focus(); input[0].select(); me._changeClassOfControl(me.$heading.find('[data-func="editTitle"]')); return me; }, /** * Check if panel title is being edited (if it is in edit process) * * @returns {Boolean} */ isTitleEditing: function () { var me = this; return me.$heading.find('.panel-title input').length > 0; }, /** * Cancel the panel new title and return to previous title when it is changed but not saved * * @returns {LobiPanel} */ cancelTitleEditing: function () { var me = this; var title = me.$heading.find('.panel-title'); title.html(title.data('old-title')) .find('input').remove(); me._changeClassOfControl(me.$heading.find('[data-func="editTitle"]')); return me; }, /** * Finish the panel title editing process and save new title * * @returns {LobiPanel} */ finishTitleEditing: function () { var me = this, input = me.$heading.find('input'); if (me._triggerEvent('beforeTitleChange', input.val()) === false) { return me; } me.saveParam('panelTitle', input.val()); me.$heading.find('.panel-title').html(input.val()); input.remove(); me._changeClassOfControl(me.$heading.find('[data-func="editTitle"]')); me._triggerEvent('onTitleChange', input.val()); return me; }, /** * Enable tooltips on panel controls * * @returns {LobiPanel} */ enableTooltips: function () { var me = this; if ($(window).width() < 768) { return me; } var controls = me.$heading.find('.dropdown-menu>li>a'); controls.each(function (index, el) { var $el = $(el); $el.attr('data-toggle', 'tooltip') .attr('data-title', $el.data('tooltip')) .attr('data-placement', 'bottom') ; }); controls.each(function (ind, el) { $(el).tooltip({ container: 'body', template: '<div class="tooltip lobipanel-tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' }); }); return me; }, /** * Disable tooltips on panel controls * * @returns {LobiPanel} */ disableTooltips: function () { var me = this; var $links = me.$heading.find('.dropdown-menu>li>a'); $links.each(function (ind, el) { var bsTooltip = $(el).data('bs.tooltip'); if (bsTooltip) { $(el).tooltip('destroy'); } }); // me.$heading.find('.dropdown-menu>li>a').tooltip('destroy'); return me; }, _generateControls: function () { var me = this; var dropdown = me._generateDropdown(); var menu = dropdown.find('.dropdown-menu'); if (me.$options.editTitle !== false) { menu.append(me._generateEditTitle()); } if (me.$options.unpin !== false) { menu.append(me._generateUnpin()); } if (me.$options.reload !== false) { menu.append(me._generateReload()); } if (me.$options.minimize !== false) { menu.append(me._generateMinimize()); } if (me.$options.expand !== false) { menu.append(me._generateExpand()); } if (me.$options.changeStyle !== false) { menu.append(me._generateChangeStyle()); } if (me.$options.close !== false) { menu.append(me._generateClose()); } menu.find('>li>a').on('click', function (ev) { ev.preventDefault(); ev.stopPropagation(); }); return dropdown; }, _generateDropdown: function () { var me = this; return $('<div class="dropdown"></div>') .append('<ul class="dropdown-menu dropdown-menu-right"></ul>') .append('<div class="dropdown-toggle" data-toggle="dropdown"><span class="' + LobiPanel.PRIVATE_OPTIONS.iconClass + ' ' + me.$options.toggleIcon + '"></div>'); }, _generateEditTitle: function () { var me = this; var options = me.$options.editTitle; var control = $('<a data-func="editTitle"></a>'); control.append('<i class="' + LobiPanel.PRIVATE_OPTIONS.iconClass + ' ' + options.icon + '"></i>'); if (options.tooltip && typeof options.tooltip === 'string') { control.append('<span class="control-title">' + options.tooltip + '</span>'); control.attr('data-tooltip', options.tooltip); } me._attachEditTitleClickListener(control); return $('<li></li>').append(control); }, _attachEditTitleClickListener: function (control) { var me = this; control.on('mousedown', function (ev) { ev.stopPropagation(); }); control.on('click', function (ev) { ev.stopPropagation(); me.hideTooltip(control); if (me.isTitleEditing()) { me.finishTitleEditing(); } else { me.startTitleEditing(); } }); }, hideTooltip: function ($el) { var bsTooltip = $el.data('bs.tooltip'); if (bsTooltip) { $el.tooltip('hide'); } return this; }, _generateUnpin: function () { var me = this; var options = me.$options.unpin; var control = $('<a data-func="unpin"></a>'); control.append('<i class="' + LobiPanel.PRIVATE_OPTIONS.iconClass + ' ' + options.icon + '"></i>'); if (options.tooltip && typeof options.tooltip === 'string') { control.append('<span class="control-title">' + options.tooltip + '</span>'); control.attr('data-tooltip', options.tooltip); } me._attachUnpinClickListener(control); return $('<li></li>').append(control); }, _attachUnpinClickListener: function (control) { var me = this; //hide the tooltip control.on('mousedown', function (ev) { ev.stopPropagation(); }); control.on('click', function () { me.hideTooltip(control); me.doTogglePin(); }); }, _generateReload: function () { var me = this; var options = me.$options.reload; var control = $('<a data-func="reload"></a>'); control.append('<i class="' + LobiPanel.PRIVATE_OPTIONS.iconClass + ' ' + options.icon + '"></i>'); if (options.tooltip && typeof options.tooltip === 'string') { control.append('<span class="control-title">' + options.tooltip + '</span>'); control.attr('data-tooltip', options.tooltip); } me._attachReloadClickListener(control); return $('<li></li>').append(control); }, _attachReloadClickListener: function (control) { var me = this; control.on('mousedown', function (ev) { ev.stopPropagation(); }); control.on('click', function () { me.hideTooltip(control); me.load(); }); }, _generateMinimize: function () { var me = this; var options = me.$options.minimize; var control = $('<a data-func="minimize"></a>'); control.append('<i class="' + LobiPanel.PRIVATE_OPTIONS.iconClass + ' ' + options.icon + '"></i>'); if (options.tooltip && typeof options.tooltip === 'string') { control.append('<span class="control-title">' + options.tooltip + '</span>'); control.attr('data-tooltip', options.tooltip); } me._attachMinimizeClickListener(control); return $('<li></li>').append(control); }, _attachMinimizeClickListener: function (control) { var me = this; control.on('mousedown', function (ev) { ev.stopPropagation(); }); control.on('click', function (ev) { ev.stopPropagation(); me.hideTooltip(control); me.toggleMinimize(); }); }, _generateExpand: function () { var me = this; var options = me.$options.expand; var control = $('<a data-func="expand"></a>'); control.append('<i class="' + LobiPanel.PRIVATE_OPTIONS.iconClass + ' ' + options.icon + '"></i>'); if (options.tooltip && typeof options.tooltip === 'string') { control.append('<span class="control-title">' + options.tooltip + '</span>'); control.attr('data-tooltip', options.tooltip); } me._attachExpandClickListener(control); return $('<li></li>').append(control); }, _generateChangeStyle: function () { var me = this; var options = me.$options.changeStyle; var $control = $('<a data-func="changeStyle"></a>'); $control.append('<i class="' + LobiPanel.PRIVATE_OPTIONS.iconClass + ' ' + options.icon + '"></i>'); if (options.tooltip && typeof options.tooltip === 'string') { $control.append('<span class="control-title">' + options.tooltip + '</span>'); $control.attr('data-tooltip', options.tooltip); } // me._attachExpandClickListener(control); var $dropdown = $('<li class="style-change-item"></li>').append($control); var $menu = $('<div>', { 'class': 'style-list' }).appendTo($dropdown); if (me.$options.styles) { for (var i = 0; i < me.$options.styles.length; i++) { var style = me.$options.styles[i]; $menu.append('<div class="style-item style-primary" style="background-color: ' + style.bg + '" data-bg="' + style.bg + '" data-text="' + style.text + '"></div>'); } } $menu.find('.style-item').on('click', function () { var $item = $(this); me.saveParam('panelStyle', { bg: $item.data('bg'), text: $item.data('text') }); me.applyStyle($item.data('bg'), $item.data('text')); $menu.removeClass('opened'); }); $control.on('click', function () { var $this = $(this); var $parent = $this.closest('.style-change-item'); $parent.find('.style-list').toggleClass('opened'); }); return $dropdown; }, applyStyle: function(color, text){ var me = this; me.$heading.css('background-color', color); me.$heading.css('border-color', color); me.$heading.css('color', text); me.$el.css('border-color', color); }, _createDropdownForStyleChange: function () { var me = this; var $dropdown = $('<div>', { 'class': 'dropdown' }).append( $('<button>', { 'type': 'button', 'data-toggle': 'dropdown', 'class': 'btn btn-default btn-xs', 'html': '<i class="glyphicon glyphicon-th"></i>' }) ); var $menu = $('<div>', { 'class': 'dropdown-menu dropdown-menu-right' }).appendTo($dropdown); for (var i = 0; i < 0; i++) { var st = me.$globalOptions.listStyles[i]; var st = 'primary'; $('<div class="' + st + '"></div>') .on('mousedown', function (ev) { ev.stopPropagation() }) .click(function () { var classes = me.$el[0].className.split(' '); var oldClass = null; for (var i = 0; i < classes.length; i++) { if (me.$globalOptions.listStyles.indexOf(classes[i]) > -1) { oldClass = classes[i]; } } me.$el.removeClass(me.$globalOptions.listStyles.join(" ")) .addClass(this.className); me._triggerEvent('styleChange', [me, oldClass, this.className]); }) .appendTo($menu); } return $dropdown; }, _attachExpandClickListener: function (control) { var me = this; control.on('mousedown', function (ev) { ev.stopPropagation(); }); control.on('click', function (ev) { ev.stopPropagation(); me.hideTooltip(control); me.toggleSize(); }); }, _generateClose: function () { var me = this; var options = me.$options.close; var control = $('<a data-func="close"></a>'); control.append('<i class="' + LobiPanel.PRIVATE_OPTIONS.iconClass + ' ' + options.icon + '"></i>'); if (options.tooltip && typeof options.tooltip === 'string') { control.append('<span class="control-title">' + options.tooltip + '</span>'); control.attr('data-tooltip', options.tooltip); } me._attachCloseClickListener(control); return $('<li></li>').append(control); }, _attachCloseClickListener: function (control) { var me = this; control.on('mousedown', function (ev) { ev.stopPropagation(); }); control.on('click', function (ev) { ev.stopPropagation(); me.hideTooltip(control); me.close(); }); }, _getMaxZIndex: function () { var me = this; var panels = $('.lobipanel.panel-unpin:not(.panel-minimized.panel-expanded)'), style, max, cur; if (panels.length === 0) { return { "id": "", "z-index": LobiPanel.PRIVATE_OPTIONS.initialZIndex }; } style = $(panels[0]).attr('style'); var id = $(panels[0]).data('inner-id'); if (!style) { max = LobiPanel.PRIVATE_OPTIONS.initialZIndex; } else { max = style.getCss()['z-index']; } for (var i = 1; i < panels.length; i++) { style = $(panels[i]).attr('style'); if (!style) { cur = 0; } else { cur = style.getCss()['z-index']; } if (cur > max) { id = $(panels[i]).data('inner-id'); max = cur; } } return { "id": id, "z-index": parseInt(max, 10) }; }, _onPanelClick: function () { var me = this; me.$el.on('mousedown.lobiPanel', function () { if (me.isPinned() || me.isMinimized() || me.isOnFullScreen()) { return false; } me.bringToFront(); }); }, _offPanelClick: function () { var me = this; me.$el.off('mousedown.lobiPanel'); }, _changeClassOfControl: function (el) { var me = this; el = $(el); var opts = me.$options[el.attr('data-func')]; if (!opts.icon) { return; } el.find('.' + LobiPanel.PRIVATE_OPTIONS.iconClass).toggleClass(opts.icon).toggleClass(opts.icon2); }, _getFooterForMinimizedPanels: function () { var me = this; //we grab footer where minimized panels should go var minimizedCtr = $('.' + LobiPanel.PRIVATE_OPTIONS.toolbarClass); //if panel does not exist we create it and append to body if (minimizedCtr.length === 0) { minimizedCtr = $('<div class="' + LobiPanel.PRIVATE_OPTIONS.toolbarClass + '"></div>'); $('body').append(minimizedCtr); } return minimizedCtr; }, _expandOnHeaderClick: function () { var me = this; me.$heading.on('click.lobiPanel', function () { me.maximize(); me.bringToFront(); }); }, _removeExpandOnHeaderClick: function () { var me = this; me.$heading.off('click.lobiPanel'); }, _getAvailableWidth: function (calcWidth) { var me = this; if (me.$options.maxWidth) { calcWidth = Math.min(calcWidth, me.$options.maxWidth); } if (me.$options.minWidth) { calcWidth = Math.max(calcWidth, me.$options.minWidth); } return calcWidth; }, _getAvailableHeight: function (calcHeight) { var me = this; if (me.$options.maxHeight) { calcHeight = Math.min(calcHeight, me.$options.maxHeight); } if (me.$options.minHeight) { calcHeight = Math.max(calcHeight, me.$options.minHeight); } return calcHeight; }, _calculateBodyHeight: function (h) { var me = this; return h - me.$heading.outerHeight() - me.$el.find('.panel-footer').outerHeight(); }, _calculateBodyWidth: function (w) { var me = this; return w - 2; }, _appendInnerIdToParent: function (parent, innerId) { var me = this; //If this is first lobipanel element of its parent if (parent.attr(LobiPanel.PRIVATE_OPTIONS.parentAttr) === undefined) { parent.attr(LobiPanel.PRIVATE_OPTIONS.parentAttr, innerId); } //This means that parent already has LobiPanel instance else { //if parent already has panel innerId than we do nothing if (parent.attr(LobiPanel.PRIVATE_OPTIONS.parentAttr).indexOf(innerId) > -1) { return; } var innerIds = parent.attr(LobiPanel.PRIVATE_OPTIONS.parentAttr); parent.attr(LobiPanel.PRIVATE_OPTIONS.parentAttr, innerIds + " " + innerId); } me.$el.attr('data-index', me.$el.index()); }, _insertInParent: function () { var me = this; //find its parent element var parent = $('[' + LobiPanel.PRIVATE_OPTIONS.parentAttr + '~=' + me.innerId + ']'); me.$el.insertAt(me.$el.attr('data-index'), parent); }, _generateWindow8Spinner: function () { var me = this; var template = ['<div class="spinner spinner-windows8">', '<div class="wBall">', '<div class="wInnerBall">', '</div>', '</div>', '<div class="wBall">', '<div class="wInnerBall">', '</div>', '</div>', '<div class="wBall">', '<div class="wInnerBall">', '</div>', '</div>', '<div class="wBall">', '<div class="wInnerBall">', '</div>', '</div>', '<div class="wBall">', '<div class="wInnerBall">', '</div>', '</div>', '</div>'].join(""); return $('<div class="spinner-wrapper">' + template + '</div>'); }, _enableSorting: function () { var me = this; var parent = me.$el.parent(); if (parent.hasClass('ui-sortable')) { parent.sortable("destroy"); } if (me.$options.sortable) { me.$el.addClass('lobipanel-sortable'); parent.addClass('lobipanel-parent-sortable'); } else { me.$el.removeClass('lobipanel-sortable'); } parent.sortable({ connectWith: '.lobipanel-parent-sortable', items: '.lobipanel-sortable', handle: '.panel-heading', cursor: 'move', placeholder: 'lobipanel-placeholder', forcePlaceholderSize: true, opacity: 0.7, revert: 300, update: function (event, ui) { me.savepanelPositions(); var $panel = ui.item; var innerId = $panel.data('inner-id'); me._removeInnerIdFromParent(innerId); me._appendInnerIdToParent(ui.item.parent(), innerId); me._triggerEvent('dragged'); } }); }, savepanelPositions: function () { var me = this; var $parents = $('.lobipanel-parent-sortable'); $parents.each(function (index, parent) { var $parent = $(parent); var parentInnerId = $parent.data('inner-id'); if (!parentInnerId) { console.error("Panel does not have parent id ", $parent); return; } var $childPanels = $parent.find('.lobipanel'); var positions = {}; $childPanels.each(function (index, el) { var $el = $(el); positions[$el.data('inner-id')] = index; }); me.storageObject.saveChildPositions(parentInnerId, positions); }); }, _disableSorting: function () { var me = this; var parent = me.$el.parent(); if (parent.hasClass('ui-sortable')) { parent.sortable("destroy"); } }, _removeInnerIdFromParent: function (innerId) { var me = this; var parent = $('[' + LobiPanel.PRIVATE_OPTIONS.parentAttr + '~=' + innerId + ']'); if (parent.length) { var innerIds = parent.attr(LobiPanel.PRIVATE_OPTIONS.parentAttr).replace(innerId, '').trim().replace(/\s{2,}/g, ' '); parent.attr(LobiPanel.PRIVATE_OPTIONS.parentAttr, innerIds); } }, _onToggleIconsBtnClick: function () { var me = this; me.$heading.find('.toggle-controls').on('click.lobiPanel', function () { me.$el.toggleClass("controls-expanded"); }); }, _adjustForScreenSize: function () { var me = this; me.disableTooltips(); if ($(window).width() > 768 && me.$options.tooltips) { me.enableTooltips(); } if (me.isOnFullScreen()) { me.$body.css({ width: me._calculateBodyWidth(me.$el.width()), height: me._calculateBodyHeight(me.$el.height()) }); } }, _enableResponsiveness: function () { var me = this; me._adjustForScreenSize(); $(window).on('resize.lobiPanel', function () { me._adjustForScreenSize(); }); }, _setBodyHeight: function () { var me = this; if (me.$options.bodyHeight !== 'auto') { me.$body.css({ 'height': me.$options.bodyHeight, overflow: 'auto' }); } }, _getOptionsFromAttributes: function () { var me = this; var $el = me.$el; var options = {}; for (var key in $.fn.lobiPanel.DEFAULTS) { var k = key.toDash(); var val = $el.data(k); if (val !== undefined) { if (typeof $.fn.lobiPanel.DEFAULTS[key] !== 'object') { options[key] = val; } else { options[key] = eval('(' + val + ')'); } } } return options; }, _saveState: function (state, params) { var me = this; // console.log("Save state ", state, params); if (!me.hasRandomId && me.$options.stateful) { me.storage.state = state; if (params) { me.storage.stateParams = params; } me._saveLocalStorage(me.storage); } }, getParam: function (key, value) { var me = this; // console.log("Save state ", state, params); return me.storage[key]; }, saveParam: function (key, value) { var me = this; // console.log("Save state ", state, params); me.storage[key] = value; me._saveLocalStorage(me.storage); }, _saveLocalStorage: function (storage) { var me = this; me.storageObject.savePanelParams(me.innerId, storage); }, _applyState: function (state, params) { var me = this; switch (state) { case 'pinned': var allPanelPositions = me.storageObject.getAllPanelPositions(); // console.log(allPanelPositions); for (var i in allPanelPositions) { var panelPositions = allPanelPositions[i]; var innerParentId = i; var $parent = $('.lobipanel-parent-sortable[data-inner-id=' + innerParentId + ']'); for (var j in panelPositions) { var $panel = $('[data-inner-id=' + j + ']'); me._removeInnerIdFromParent($panel.data('inner-id')); me._appendInnerIdToParent($parent, $panel.data('inner-id')); if (!$panel.hasClass('panel-unpin') && !$panel.hasClass('panel-expanded')) { $panel.insertAt(panelPositions[j], $parent); } } } // if (params && params.index !== null && params.index !== undefined) { // me._applyIndex(params.index); // } break; case 'unpinned': me.unpin(); me.setPosition(params.left, params.top, 0); me.setSize(params.width, params.height, 0); break; case 'minimized': me.unpin(); me.minimize(); break; case 'collapsed': me.minimize(); break; case 'fullscreen': me.toFullScreen(); break; default: break; } }, _applyIndex: function (index) { var me = this; if (index !== null) { me.$el.insertAt(index, me.$el.parent()); } }, _triggerEvent: function (eventType) { var me = this; var args = Array.prototype.slice.call(arguments, 1); args.unshift(me); me.$el.trigger(eventType + '.lobiPanel', args); if (me.$options[eventType] && typeof me.$options[eventType] === 'function') { return me.$options[eventType].apply(me, args); } return true; }, doPin: function () { var me = this; if (me._triggerEvent("beforePin") !== false) { me.pin(); me._saveState('pinned'); me._triggerEvent("onPin"); } return me; }, doUnpin: function () { var me = this; if (me._triggerEvent('beforeUnpin') !== false) { me.unpin(); me._updateUnpinnedState(); me._triggerEvent('onUnpin'); } return me; }, doTogglePin: function () { var me = this; if (this.isPinned()) { this.doUnpin(); } else { this.doPin(); } return me; }, _updateUnpinnedState: function () { var me = this; me._saveState('unpinned', me.getAlignment()); }, getAlignment: function () { var me = this; return { top: me.$el.css('top'), left: me.$el.css('left'), width: me.$el.css('width'), height: me.$el.css('height') }; } }; $.fn.lobiPanel = function (option) { var args = arguments, ret = null; this.each(function () { var $this = $(this); var data = $this.data('lobiPanel'); var options = typeof option === 'object' && option; if (!data) { $this.data('lobiPanel', (data = new LobiPanel($this, options))); } if (typeof option === 'string') { args = Array.prototype.slice.call(args, 1); ret = data[option].apply(data, args); } }); return ret; }; LobiPanel.PRIVATE_OPTIONS = { //We need to know what is the parent of the panel, that's why we add //this attribute to parent element and it contains space seperated inner-ids of all its child lobipanel parentAttr: 'data-lobipanel-child-inner-id', toolbarClass: 'lobipanel-minimized-toolbar', //This class is added to container which contains all minimized panels //First instance on lobiPanel will get this z-index css property. //Every next instance will get 1 + previous z-index initialZIndex: 10000, //This class is attached to every panel-control icon iconClass: 'panel-control-icon' }; $.fn.lobiPanel.DEFAULTS = { //Makes <b>unpinned</b> panel draggable //Warning!!! This requires jquery ui draggable widget to be included draggable: true, //Makes <b>pinned</b> panels sortable //Warning!!! This requires jquery ui sortable widget to be included sortable: false, //jquery ui sortable plugin option. //To avoid any problems this option must be same for all panels which are direct children of their parent connectWith: '.ui-sortable', //This parameter accepts string ['both', 'vertical', 'horizontal', 'none']. none means disable resize resize: 'both', //Minimum width <b>unpin, resizable</b> panel can have. minWidth: 200, //Minimum height <b>unpin, resizable</b> panel can have. minHeight: 100, //Maximum width <b>unpin, resizable</b> panel can have. maxWidth: 1200, //Maximum height <b>unpin, resizable</b> panel can have. maxHeight: 700, //The url which will be used to load content. If not provided reload button will do nothing loadUrl: "", //If loadUrl is provided plugin will load content as soon as plugin is initialized autoload: true, bodyHeight: 'auto', //This will enable tooltips on panel controls tooltips: true, toggleIcon: 'glyphicon glyphicon-cog', expandAnimation: 100, collapseAnimation: 100, state: 'pinned', // Initial state of the panel. Available options: pinned, unpinned, collapsed, minimized, fullscreen initialIndex: null, // Initial index of the panel among its siblings stateful: false, // If you set this to true you must specify data-inner-id. Plugin will save (in localStorage) it's states such as // pinned, unpinned, collapsed, minimized, fullscreen, position among it's siblings // and apply them when you reload the browser constrain: 'document', // 'parent', 'document', 'window' unpin: { icon: 'glyphicon glyphicon-move', //You can user glyphicons if you do not want to use font-awesome tooltip: 'Unpin' //tooltip text, If you want to disable tooltip, set it to false }, reload: { icon: 'glyphicon glyphicon-refresh', //You can user glyphicons if you do not want to use font-awesome tooltip: 'Reload' //tooltip text, If you want to disable tooltip, set it to false }, minimize: { icon: 'glyphicon glyphicon-minus', //icon is shown when panel is not minimized icon2: 'glyphicon glyphicon-plus', //icon2 is shown when panel is minimized tooltip: 'Minimize' //tooltip text, If you want to disable tooltip, set it to false }, expand: { icon: 'glyphicon glyphicon-resize-full', //icon is shown when panel is not on full screen icon2: 'glyphicon glyphicon-resize-small', //icon2 is shown when pane is on full screen state tooltip: 'Fullscreen' //tooltip text, If you want to disable tooltip, set it to false }, changeStyle: { icon: 'glyphicon glyphicon-th', //icon is shown when panel is not on full screen tooltip: 'Style' //tooltip text, If you want to disable tooltip, set it to false }, close: { icon: 'glyphicon glyphicon-remove', //You can user glyphicons if you do not want to use font-awesome tooltip: 'Close' //tooltip text, If you want to disable tooltip, set it to false }, editTitle: { icon: 'glyphicon glyphicon-pencil', icon2: 'glyphicon glyphicon-floppy-disk', tooltip: 'Edit title' }, styles: [ { bg: '#d9534f', text: '#FFF' }, { bg: '#f0ad4e', text: '#FFF' }, { bg: '#337ab7', text: '#FFF' }, { bg: '#5bc0de', text: '#FFF' }, { bg: '#4753e4', text: '#FFF' }, { bg: '#9e4aea', text: '#FFF' } ], storageObject: null, // Events /** * @event beforeTitleChange * Fires before title change happens. Returning false will prevent title change from happening. * @param {LobiPanel} The <code>LobiPanel</code> instance */ beforeTitleChange: null }; $('.lobipanel').lobiPanel(); var $parent = $('.lobipanel-parent-sortable'); if (!$parent.hasClass('ui-sortable')) { $parent.sortable({ connectWith: '.lobipanel-parent-sortable', items: '.lobipanel-sortable', handle: '.panel-heading', cursor: 'move', placeholder: 'lobipanel-placeholder', forcePlaceholderSize: true, opacity: 0.7, revert: 300, update: function (event, ui) { console.log(ui); // me.savepanelPositions(); // // // me._removeInnerIdFromParent(innerId); // // me._appendInnerIdToParent(ui.item.parent(), innerId); // me._triggerEvent('dragged'); } }); } });
/* * * * (c) 2010-2019 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from './Globals.js'; /** * @typedef {"circlepin"|"flag"|"squarepin"} Highcharts.FlagsShapeValue */ import U from './Utilities.js'; var defined = U.defined, isNumber = U.isNumber, objectEach = U.objectEach; import './Series.js'; import './SvgRenderer.js'; import onSeriesMixin from '../mixins/on-series.js'; var addEvent = H.addEvent, merge = H.merge, noop = H.noop, Renderer = H.Renderer, Series = H.Series, seriesType = H.seriesType, SVGRenderer = H.SVGRenderer, TrackerMixin = H.TrackerMixin, VMLRenderer = H.VMLRenderer, symbols = SVGRenderer.prototype.symbols; /** * The Flags series. * * @private * @class * @name Highcharts.seriesTypes.flags * * @augments Highcharts.Series */ seriesType('flags', 'column' /** * Flags are used to mark events in stock charts. They can be added on the * timeline, or attached to a specific series. * * @sample stock/demo/flags-general/ * Flags on a line series * * @extends plotOptions.column * @excluding animation, borderColor, borderRadius, borderWidth, * colorByPoint, dataGrouping, pointPadding, pointWidth, * turboThreshold * @product highstock * @optionparent plotOptions.flags */ , { /** * In case the flag is placed on a series, on what point key to place * it. Line and columns have one key, `y`. In range or OHLC-type series, * however, the flag can optionally be placed on the `open`, `high`, * `low` or `close` key. * * @sample {highstock} stock/plotoptions/flags-onkey/ * Range series, flag on high * * @type {string} * @default y * @since 4.2.2 * @product highstock * @validvalue ["y", "open", "high", "low", "close"] * @apioption plotOptions.flags.onKey */ /** * The id of the series that the flags should be drawn on. If no id * is given, the flags are drawn on the x axis. * * @sample {highstock} stock/plotoptions/flags/ * Flags on series and on x axis * * @type {string} * @product highstock * @apioption plotOptions.flags.onSeries */ pointRange: 0, /** * Whether the flags are allowed to overlap sideways. If `false`, the * flags are moved sideways using an algorithm that seeks to place every * flag as close as possible to its original position. * * @sample {highstock} stock/plotoptions/flags-allowoverlapx * Allow sideways overlap * * @since 6.0.4 */ allowOverlapX: false, /** * The shape of the marker. Can be one of "flag", "circlepin", * "squarepin", or an image of the format `url(/path-to-image.jpg)`. * Individual shapes can also be set for each point. * * @sample {highstock} stock/plotoptions/flags/ * Different shapes * * @type {Highcharts.FlagsShapeValue} * @product highstock */ shape: 'flag', /** * When multiple flags in the same series fall on the same value, this * number determines the vertical offset between them. * * @sample {highstock} stock/plotoptions/flags-stackdistance/ * A greater stack distance * * @product highstock */ stackDistance: 12, /** * Text alignment for the text inside the flag. * * @since 5.0.0 * @product highstock * @validvalue ["left", "center", "right"] */ textAlign: 'center', /** * Specific tooltip options for flag series. Flag series tooltips are * different from most other types in that a flag doesn't have a data * value, so the tooltip rather displays the `text` option for each * point. * * @extends plotOptions.series.tooltip * @excluding changeDecimals, valueDecimals, valuePrefix, valueSuffix * @product highstock */ tooltip: { pointFormat: '{point.text}<br/>' }, threshold: null, /** * The text to display on each flag. This can be defined on series * level, or individually for each point. Defaults to `"A"`. * * @type {string} * @default A * @product highstock * @apioption plotOptions.flags.title */ /** * The y position of the top left corner of the flag relative to either * the series (if onSeries is defined), or the x axis. Defaults to * `-30`. * * @product highstock */ y: -30, /** * Whether to use HTML to render the flag texts. Using HTML allows for * advanced formatting, images and reliable bi-directional text * rendering. Note that exported images won't respect the HTML, and that * HTML won't respect Z-index settings. * * @type {boolean} * @default false * @since 1.3 * @product highstock * @apioption plotOptions.flags.useHTML */ /** * Fixed width of the flag's shape. By default, width is autocalculated * according to the flag's title. * * @sample {highstock} stock/demo/flags-shapes/ * Flags with fixed width * * @type {number} * @product highstock * @apioption plotOptions.flags.width */ /** * Fixed height of the flag's shape. By default, height is * autocalculated according to the flag's title. * * @type {number} * @product highstock * @apioption plotOptions.flags.height */ /** * The fill color for the flags. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highstock */ fillColor: '#ffffff', /** * The color of the line/border of the flag. * * In styled mode, the stroke is set in the * `.highcharts-flag-series.highcharts-point` rule. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @default #000000 * @product highstock * @apioption plotOptions.flags.lineColor */ /** * The pixel width of the flag's line/border. * * @product highstock */ lineWidth: 1, states: { /** * @extends plotOptions.column.states.hover * @product highstock */ hover: { /** * The color of the line/border of the flag. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highstock */ lineColor: '#000000', /** * The fill or background color of the flag. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highstock */ fillColor: '#ccd6eb' } }, /** * The text styles of the flag. * * In styled mode, the styles are set in the * `.highcharts-flag-series .highcharts-point` rule. * * @type {Highcharts.CSSObject} * @default {"fontSize": "11px", "fontWeight": "bold"} * @product highstock */ style: { /** @ignore-option */ fontSize: '11px', /** @ignore-option */ fontWeight: 'bold' } }, /** * @lends seriesTypes.flags.prototype */ { sorted: false, noSharedTooltip: true, allowDG: false, takeOrdinalPosition: false, trackerGroups: ['markerGroup'], forceCrop: true, /* eslint-disable no-invalid-this, valid-jsdoc */ /** * Inherit the initialization from base Series. * * @private * @borrows Highcharts.Series#init as Highcharts.seriesTypes.flags#init */ init: Series.prototype.init, /** * Get presentational attributes * * @private * @function Highcharts.seriesTypes.flags#pointAttribs * * @param {Highcharts.Point} point * * @param {string} [state] * * @return {Highcharts.SVGAttributes} */ pointAttribs: function (point, state) { var options = this.options, color = (point && point.color) || this.color, lineColor = options.lineColor, lineWidth = (point && point.lineWidth), fill = (point && point.fillColor) || options.fillColor; if (state) { fill = options.states[state].fillColor; lineColor = options.states[state].lineColor; lineWidth = options.states[state].lineWidth; } return { fill: fill || color, stroke: lineColor || color, 'stroke-width': lineWidth || options.lineWidth || 0 }; }, translate: onSeriesMixin.translate, getPlotBox: onSeriesMixin.getPlotBox, /** * Draw the markers. * * @private * @function Highcharts.seriesTypes.flags#drawPoints * @return {void} */ drawPoints: function () { var series = this, points = series.points, chart = series.chart, renderer = chart.renderer, plotX, plotY, inverted = chart.inverted, options = series.options, optionsY = options.y, shape, i, point, graphic, stackIndex, anchorY, attribs, outsideRight, yAxis = series.yAxis, boxesMap = {}, boxes = [], centered; i = points.length; while (i--) { point = points[i]; outsideRight = (inverted ? point.plotY : point.plotX) > series.xAxis.len; plotX = point.plotX; stackIndex = point.stackIndex; shape = point.options.shape || options.shape; plotY = point.plotY; if (plotY !== undefined) { plotY = point.plotY + optionsY - (stackIndex !== undefined && (stackIndex * options.stackDistance)); } // skip connectors for higher level stacked points point.anchorX = stackIndex ? undefined : point.plotX; anchorY = stackIndex ? undefined : point.plotY; centered = shape !== 'flag'; graphic = point.graphic; // Only draw the point if y is defined and the flag is within // the visible area if (plotY !== undefined && plotX >= 0 && !outsideRight) { // Create the flag if (!graphic) { graphic = point.graphic = renderer.label('', null, null, shape, null, null, options.useHTML); if (!chart.styledMode) { graphic .attr(series.pointAttribs(point)) .css(merge(options.style, point.style)); } graphic.attr({ align: centered ? 'center' : 'left', width: options.width, height: options.height, 'text-align': options.textAlign }) .addClass('highcharts-point') .add(series.markerGroup); // Add reference to the point for tracker (#6303) if (point.graphic.div) { point.graphic.div.point = point; } if (!chart.styledMode) { graphic.shadow(options.shadow); } graphic.isNew = true; } if (plotX > 0) { // #3119 plotX -= graphic.strokeWidth() % 2; // #4285 } // Plant the flag attribs = { y: plotY, anchorY: anchorY }; if (options.allowOverlapX) { attribs.x = plotX; attribs.anchorX = point.anchorX; } graphic.attr({ text: point.options.title || options.title || 'A' })[graphic.isNew ? 'attr' : 'animate'](attribs); // Rig for the distribute function if (!options.allowOverlapX) { if (!boxesMap[point.plotX]) { boxesMap[point.plotX] = { align: centered ? 0.5 : 0, size: graphic.width, target: plotX, anchorX: plotX }; } else { boxesMap[point.plotX].size = Math.max(boxesMap[point.plotX].size, graphic.width); } } // Set the tooltip anchor position point.tooltipPos = [ plotX, plotY + yAxis.pos - chart.plotTop ]; // #6327 } else if (graphic) { point.graphic = graphic.destroy(); } } // Handle X-dimension overlapping if (!options.allowOverlapX) { objectEach(boxesMap, function (box) { box.plotX = box.anchorX; boxes.push(box); }); H.distribute(boxes, inverted ? yAxis.len : this.xAxis.len, 100); points.forEach(function (point) { var box = point.graphic && boxesMap[point.plotX]; if (box) { point.graphic[point.graphic.isNew ? 'attr' : 'animate']({ x: box.pos + box.align * box.size, anchorX: point.anchorX }); // Hide flag when its box position is not specified // (#8573, #9299) if (!defined(box.pos)) { point.graphic.attr({ x: -9999, anchorX: -9999 }); point.graphic.isNew = true; } else { point.graphic.isNew = false; } } }); } // Can be a mix of SVG and HTML and we need events for both (#6303) if (options.useHTML) { H.wrap(series.markerGroup, 'on', function (proceed) { return H.SVGElement.prototype.on.apply( // for HTML proceed.apply(this, [].slice.call(arguments, 1)), // and for SVG [].slice.call(arguments, 1)); }); } }, /** * Extend the column trackers with listeners to expand and contract * stacks. * * @private * @function Highcharts.seriesTypes.flags#drawTracker * @return {void} */ drawTracker: function () { var series = this, points = series.points; TrackerMixin.drawTrackerPoint.apply(this); /* * * Bring each stacked flag up on mouse over, this allows readability * of vertically stacked elements as well as tight points on the x * axis. #1924. */ points.forEach(function (point) { var graphic = point.graphic; if (graphic) { addEvent(graphic.element, 'mouseover', function () { // Raise this point if (point.stackIndex > 0 && !point.raised) { point._y = graphic.y; graphic.attr({ y: point._y - 8 }); point.raised = true; } // Revert other raised points points.forEach(function (otherPoint) { if (otherPoint !== point && otherPoint.raised && otherPoint.graphic) { otherPoint.graphic.attr({ y: otherPoint._y }); otherPoint.raised = false; } }); }); } }); }, /** * Disable animation, but keep clipping (#8546). * * @private * @function Highcharts.seriesTypes.flags#animate * @param {boolean} [init] * @return {void} */ animate: function (init) { if (init) { this.setClip(); } else { this.animate = null; } }, /** * @private * @function Highcharts.seriesTypes.flags#setClip * @return {void} */ setClip: function () { Series.prototype.setClip.apply(this, arguments); if (this.options.clip !== false && this.sharedClipKey) { this.markerGroup .clip(this.chart[this.sharedClipKey]); } }, /** * @private * @function Highcharts.seriesTypes.flags#buildKDTree */ buildKDTree: noop, /** * Don't invert the flag marker group (#4960). * * @private * @function Highcharts.seriesTypes.flags#invertGroups */ invertGroups: noop /* eslint-enable no-invalid-this, valid-jsdoc */ }, /** * @lends Highcharts.seriesTypes.flag.prototype.pointClass.prototype */ { isValid: function () { // #9233 - Prevent from treating flags as null points (even if // they have no y values defined). return isNumber(this.y) || this.y === undefined; } }); // create the flag icon with anchor symbols.flag = function (x, y, w, h, options) { var anchorX = (options && options.anchorX) || x, anchorY = (options && options.anchorY) || y; return symbols.circle(anchorX - 1, anchorY - 1, 2, 2).concat([ 'M', anchorX, anchorY, 'L', x, y + h, x, y, x + w, y, x + w, y + h, x, y + h, 'Z' ]); }; /** * Create the circlepin and squarepin icons with anchor. * @private * @param {string} shape - circle or square * @return {void} */ function createPinSymbol(shape) { symbols[shape + 'pin'] = function (x, y, w, h, options) { var anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, labelTopOrBottomY; // For single-letter flags, make sure circular flags are not taller // than their width if (shape === 'circle' && h > w) { x -= Math.round((h - w) / 2); w = h; } path = symbols[shape](x, y, w, h); if (anchorX && anchorY) { /** * If the label is below the anchor, draw the connecting line * from the top edge of the label * otherwise start drawing from the bottom edge */ labelTopOrBottomY = (y > anchorY) ? y : y + h; path.push('M', shape === 'circle' ? x + w / 2 : path[1] + path[4] / 2, labelTopOrBottomY, 'L', anchorX, anchorY); path = path.concat(symbols.circle(anchorX - 1, anchorY - 1, 2, 2)); } return path; }; } createPinSymbol('circle'); createPinSymbol('square'); /** * The symbol callbacks are generated on the SVGRenderer object in all browsers. * Even VML browsers need this in order to generate shapes in export. Now share * them with the VMLRenderer. */ if (Renderer === VMLRenderer) { ['circlepin', 'flag', 'squarepin'].forEach(function (shape) { VMLRenderer.prototype.symbols[shape] = symbols[shape]; }); } /** * A `flags` series. If the [type](#series.flags.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.flags * @excluding dataParser, dataURL * @product highstock * @apioption series.flags */ /** * An array of data points for the series. For the `flags` series type, * points can be given in the following ways: * * 1. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of * data points exceeds the series' * [turboThreshold](#series.flags.turboThreshold), this option is not * available. * ```js * data: [{ * x: 1, * title: "A", * text: "First event" * }, { * x: 1, * title: "B", * text: "Second event" * }] * ``` * * @type {Array<*>} * @extends series.line.data * @excluding dataLabels, marker, name, y * @product highstock * @apioption series.flags.data */ /** * The fill color of an individual flag. By default it inherits from * the series color. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highstock * @apioption series.flags.data.fillColor */ /** * The longer text to be shown in the flag's tooltip. * * @type {string} * @product highstock * @apioption series.flags.data.text */ /** * The short text to be shown on the flag. * * @type {string} * @product highstock * @apioption series.flags.data.title */ ''; // adds doclets above to transpiled file
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Injectable } from '@angular/core'; import { __platform_browser_private__ } from '@angular/platform-browser'; import { Observable } from 'rxjs/Observable'; import { ResponseOptions } from '../base_response_options'; import { ContentType, RequestMethod, ResponseContentType, ResponseType } from '../enums'; import { isPresent, isString } from '../facade/lang'; import { Headers } from '../headers'; import { getResponseURL, isSuccess } from '../http_utils'; import { XSRFStrategy } from '../interfaces'; import { Response } from '../static_response'; import { BrowserXhr } from './browser_xhr'; var XSSI_PREFIX = /^\)\]\}',?\n/; /** * Creates connections using `XMLHttpRequest`. Given a fully-qualified * request, an `XHRConnection` will immediately create an `XMLHttpRequest` object and send the * request. * * This class would typically not be created or interacted with directly inside applications, though * the {@link MockConnection} may be interacted with in tests. * * @experimental */ export var XHRConnection = (function () { function XHRConnection(req, browserXHR, baseResponseOptions) { var _this = this; this.request = req; this.response = new Observable(function (responseObserver) { var _xhr = browserXHR.build(); _xhr.open(RequestMethod[req.method].toUpperCase(), req.url); if (isPresent(req.withCredentials)) { _xhr.withCredentials = req.withCredentials; } // load event handler var onLoad = function () { // responseText is the old-school way of retrieving response (supported by IE8 & 9) // response/responseType properties were introduced in ResourceLoader Level2 spec (supported // by IE10) var body = _xhr.response === undefined ? _xhr.responseText : _xhr.response; // Implicitly strip a potential XSSI prefix. if (isString(body)) body = body.replace(XSSI_PREFIX, ''); var headers = Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders()); var url = getResponseURL(_xhr); // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) var status = _xhr.status === 1223 ? 204 : _xhr.status; // fix status code when it is 0 (0 status is undocumented). // Occurs when accessing file resources or on Android 4.1 stock browser // while retrieving files from application cache. if (status === 0) { status = body ? 200 : 0; } var statusText = _xhr.statusText || 'OK'; var responseOptions = new ResponseOptions({ body: body, status: status, headers: headers, statusText: statusText, url: url }); if (isPresent(baseResponseOptions)) { responseOptions = baseResponseOptions.merge(responseOptions); } var response = new Response(responseOptions); response.ok = isSuccess(status); if (response.ok) { responseObserver.next(response); // TODO(gdi2290): defer complete if array buffer until done responseObserver.complete(); return; } responseObserver.error(response); }; // error event handler var onError = function (err) { var responseOptions = new ResponseOptions({ body: err, type: ResponseType.Error, status: _xhr.status, statusText: _xhr.statusText, }); if (isPresent(baseResponseOptions)) { responseOptions = baseResponseOptions.merge(responseOptions); } responseObserver.error(new Response(responseOptions)); }; _this.setDetectedContentType(req, _xhr); if (isPresent(req.headers)) { req.headers.forEach(function (values, name) { return _xhr.setRequestHeader(name, values.join(',')); }); } // Select the correct buffer type to store the response if (isPresent(req.responseType) && isPresent(_xhr.responseType)) { switch (req.responseType) { case ResponseContentType.ArrayBuffer: _xhr.responseType = 'arraybuffer'; break; case ResponseContentType.Json: _xhr.responseType = 'json'; break; case ResponseContentType.Text: _xhr.responseType = 'text'; break; case ResponseContentType.Blob: _xhr.responseType = 'blob'; break; default: throw new Error('The selected responseType is not supported'); } } _xhr.addEventListener('load', onLoad); _xhr.addEventListener('error', onError); _xhr.send(_this.request.getBody()); return function () { _xhr.removeEventListener('load', onLoad); _xhr.removeEventListener('error', onError); _xhr.abort(); }; }); } XHRConnection.prototype.setDetectedContentType = function (req /** TODO #9100 */, _xhr /** TODO #9100 */) { // Skip if a custom Content-Type header is provided if (isPresent(req.headers) && isPresent(req.headers.get('Content-Type'))) { return; } // Set the detected content type switch (req.contentType) { case ContentType.NONE: break; case ContentType.JSON: _xhr.setRequestHeader('content-type', 'application/json'); break; case ContentType.FORM: _xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); break; case ContentType.TEXT: _xhr.setRequestHeader('content-type', 'text/plain'); break; case ContentType.BLOB: var blob = req.blob(); if (blob.type) { _xhr.setRequestHeader('content-type', blob.type); } break; } }; return XHRConnection; }()); /** * `XSRFConfiguration` sets up Cross Site Request Forgery (XSRF) protection for the application * using a cookie. See {@link https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)} * for more information on XSRF. * * Applications can configure custom cookie and header names by binding an instance of this class * with different `cookieName` and `headerName` values. See the main HTTP documentation for more * details. * * @experimental */ export var CookieXSRFStrategy = (function () { function CookieXSRFStrategy(_cookieName, _headerName) { if (_cookieName === void 0) { _cookieName = 'XSRF-TOKEN'; } if (_headerName === void 0) { _headerName = 'X-XSRF-TOKEN'; } this._cookieName = _cookieName; this._headerName = _headerName; } CookieXSRFStrategy.prototype.configureRequest = function (req) { var xsrfToken = __platform_browser_private__.getDOM().getCookie(this._cookieName); if (xsrfToken && !req.headers.has(this._headerName)) { req.headers.set(this._headerName, xsrfToken); } }; return CookieXSRFStrategy; }()); /** * Creates {@link XHRConnection} instances. * * This class would typically not be used by end users, but could be * overridden if a different backend implementation should be used, * such as in a node backend. * * ### Example * * ``` * import {Http, MyNodeBackend, HTTP_PROVIDERS, BaseRequestOptions} from '@angular/http'; * @Component({ * viewProviders: [ * HTTP_PROVIDERS, * {provide: Http, useFactory: (backend, options) => { * return new Http(backend, options); * }, deps: [MyNodeBackend, BaseRequestOptions]}] * }) * class MyComponent { * constructor(http:Http) { * http.request('people.json').subscribe(res => this.people = res.json()); * } * } * ``` * @experimental */ export var XHRBackend = (function () { function XHRBackend(_browserXHR, _baseResponseOptions, _xsrfStrategy) { this._browserXHR = _browserXHR; this._baseResponseOptions = _baseResponseOptions; this._xsrfStrategy = _xsrfStrategy; } XHRBackend.prototype.createConnection = function (request) { this._xsrfStrategy.configureRequest(request); return new XHRConnection(request, this._browserXHR, this._baseResponseOptions); }; XHRBackend.decorators = [ { type: Injectable }, ]; /** @nocollapse */ XHRBackend.ctorParameters = [ { type: BrowserXhr, }, { type: ResponseOptions, }, { type: XSRFStrategy, }, ]; return XHRBackend; }()); //# sourceMappingURL=xhr_backend.js.map
'use strict'; /** * @name $$cookieWriter * @requires $document * * @description * This is a private service for writing cookies * * @param {string} name Cookie name * @param {string=} value Cookie value (if undefined, cookie will be deleted) * @param {Object=} options Object with options that need to be stored for the cookie. */ function $$CookieWriter($document, $log, $browser) { var cookiePath = $browser.baseHref(); var rawDocument = $document[0]; function buildCookieString(name, value, options) { var path, expires; options = options || {}; expires = options.expires; path = angular.isDefined(options.path) ? options.path : cookiePath; if (angular.isUndefined(value)) { expires = 'Thu, 01 Jan 1970 00:00:00 GMT'; value = ''; } if (angular.isString(expires)) { expires = new Date(expires); } var str = encodeURIComponent(name) + '=' + encodeURIComponent(value); str += path ? ';path=' + path : ''; str += options.domain ? ';domain=' + options.domain : ''; str += expires ? ';expires=' + expires.toUTCString() : ''; str += options.secure ? ';secure' : ''; str += options.samesite ? ';samesite=' + options.samesite : ''; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie var cookieLength = str.length + 1; if (cookieLength > 4096) { $log.warn('Cookie \'' + name + '\' possibly not set or overflowed because it was too large (' + cookieLength + ' > 4096 bytes)!'); } return str; } return function(name, value, options) { rawDocument.cookie = buildCookieString(name, value, options); }; } $$CookieWriter.$inject = ['$document', '$log', '$browser']; angular.module('ngCookies').provider('$$cookieWriter', /** @this */ function $$CookieWriterProvider() { this.$get = $$CookieWriter; });
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use 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 Microsoft nor the names of its contributors may be used to /// endorse or promote products derived from this software without specific prior written permission. /// /// 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. /* The abtract operation ToPropertyDescriptor is used to package the into a property desc. Step 10 of ToPropertyDescriptor throws a TypeError if the property desc ends up having a mix of accessor and data property elements. */ ES5Harness.registerTest( { id: "15.2.3.6-3-3", path: "TestCases/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-3.js", description: "Object.defineProperty throws TypeError if desc has 'set' and 'value' present", test: function testcase() { var o = {}; // dummy setter var setter = function () { } var desc = { set: setter, value: 101}; try { Object.defineProperty(o, "foo", desc); } catch (e) { if (e instanceof TypeError && (o.hasOwnProperty("foo") === false)) { return true; } } }, precondition: function prereq() { return fnExists(Object.defineProperty); } });
// // converter.js // Mr-Data-Converter // // Created by Shan Carter on 2010-09-01. // function DataConverter(nodeId) { //--------------------------------------- // PUBLIC PROPERTIES //--------------------------------------- this.nodeId = nodeId; this.node = $("#"+nodeId); this.outputDataTypes = [ {"text":"Actionscript", "id":"as", "notes":""}, {"text":"ASP/VBScript", "id":"asp", "notes":""}, {"text":"HTML", "id":"html", "notes":""}, {"text":"JSON - Properties", "id":"json", "notes":""}, {"text":"JSON - Column Arrays", "id":"jsonArrayCols", "notes":""}, {"text":"JSON - Row Arrays", "id":"jsonArrayRows", "notes":""}, {"text":"JSON - Dictionary", "id":"jsonDict", "notes":""}, {"text":"MySQL", "id":"mysql", "notes":""}, {"text":"PHP", "id":"php", "notes":""}, {"text":"Python - Dict", "id":"python", "notes":""}, {"text":"Ruby", "id":"ruby", "notes":""}, {"text":"XML - Properties", "id":"xmlProperties", "notes":""}, {"text":"XML - Nodes", "id":"xml", "notes":""}, {"text":"XML - Illustrator", "id":"xmlIllustrator", "notes":""}]; this.outputDataType = "json"; this.columnDelimiter = "\t"; this.rowDelimiter = "\n"; this.inputTextArea = {}; this.outputTextArea = {}; this.inputHeader = {}; this.outputHeader = {}; this.dataSelect = {}; this.inputText = ""; this.outputText = ""; this.newLine = "\n"; this.indent = " "; this.commentLine = "//"; this.commentLineEnd = ""; this.tableName = "MrDataConverter" this.useUnderscores = true; this.headersProvided = true; this.downcaseHeaders = true; this.upcaseHeaders = false; this.includeWhiteSpace = true; this.useTabsForIndent = false; } //--------------------------------------- // PUBLIC METHODS //--------------------------------------- DataConverter.prototype.create = function(w,h) { var self = this; //build HTML for converter this.inputHeader = $('<div class="groupHeader" id="inputHeader"><p class="groupHeadline">Input CSV or tab-delimited data. <span class="subhead"> Using Excel? Simply copy and paste. No data on hand? <a href="#" id="insertSample">Use sample</a></span></p></div>'); this.inputTextArea = $('<textarea class="textInputs" id="dataInput"></textarea>'); var outputHeaderText = '<div class="groupHeader" id="inputHeader"><p class="groupHeadline">Output as <select name="Data Types" id="dataSelector" >'; for (var i=0; i < this.outputDataTypes.length; i++) { outputHeaderText += '<option value="'+this.outputDataTypes[i]["id"]+'" ' + (this.outputDataTypes[i]["id"] == this.outputDataType ? 'selected="selected"' : '') + '>' + this.outputDataTypes[i]["text"]+'</option>'; }; outputHeaderText += '</select><span class="subhead" id="outputNotes"></span></p></div>'; this.outputHeader = $(outputHeaderText); this.outputTextArea = $('<textarea class="textInputs" id="dataOutput"></textarea>'); this.node.append(this.inputHeader); this.node.append(this.inputTextArea); this.node.append(this.outputHeader); this.node.append(this.outputTextArea); this.dataSelect = this.outputHeader.find("#dataSelector"); //add event listeners // $("#convertButton").bind('click',function(evt){ // evt.preventDefault(); // self.convert(); // }); this.outputTextArea.click(function(evt){this.select();}); $("#insertSample").bind('click',function(evt){ evt.preventDefault(); self.insertSampleData(); self.convert(); _gaq.push(['_trackEvent', 'SampleData','InsertGeneric']); }); $("#dataInput").keyup(function() {self.convert()}); $("#dataInput").change(function() { self.convert(); _gaq.push(['_trackEvent', 'DataType',self.outputDataType]); }); $("#dataSelector").bind('change',function(evt){ self.outputDataType = $(this).val(); self.convert(); }); this.resize(w,h); } DataConverter.prototype.resize = function(w,h) { var paneWidth = w; var paneHeight = (h-90)/2-20; this.node.css({width:paneWidth}); this.inputTextArea.css({width:paneWidth-20,height:paneHeight}); this.outputTextArea.css({width: paneWidth-20, height:paneHeight}); } DataConverter.prototype.convert = function() { this.inputText = this.inputTextArea.val(); this.outputText = ""; //make sure there is input data before converting... if (this.inputText.length > 0) { if (this.includeWhiteSpace) { this.newLine = "\n"; // console.log("yes") } else { this.indent = ""; this.newLine = ""; // console.log("no") } CSVParser.resetLog(); var parseOutput = CSVParser.parse(this.inputText, this.headersProvided, this.delimiter, this.downcaseHeaders, this.upcaseHeaders); var dataGrid = parseOutput.dataGrid; var headerNames = parseOutput.headerNames; var headerTypes = parseOutput.headerTypes; var errors = parseOutput.errors; this.outputText = DataGridRenderer[this.outputDataType](dataGrid, headerNames, headerTypes, this.indent, this.newLine); this.outputTextArea.val(errors + this.outputText); }; //end test for existence of input text } DataConverter.prototype.insertSampleData = function() { this.inputTextArea.val("NAME\tVALUE\tCOLOR\tDATE\nAlan\t12\tblue\tSep. 25, 2009\nShan\t13\t\"green\tblue\"\tSep. 27, 2009\nJohn\t45\torange\tSep. 29, 2009\nMinna\t27\tteal\tSep. 30, 2009"); }
/** * @license * Visual Blocks Editor * * Copyright 2016 Google Inc. * https://developers.google.com/blockly/ * * 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. */ /** * @fileoverview Events fired as a result of actions in Blockly's editor. * @author fraser@google.com (Neil Fraser) */ 'use strict'; /** * Events fired as a result of actions in Blockly's editor. * @namespace Blockly.Events */ goog.provide('Blockly.Events'); goog.require('goog.array'); goog.require('goog.math.Coordinate'); /** * Group ID for new events. Grouped events are indivisible. * @type {string} * @private */ Blockly.Events.group_ = ''; /** * Sets whether events should be added to the undo stack. * @type {boolean} */ Blockly.Events.recordUndo = true; /** * Allow change events to be created and fired. * @type {number} * @private */ Blockly.Events.disabled_ = 0; /** * Name of event that creates a block. * @const */ Blockly.Events.CREATE = 'create'; /** * Name of event that deletes a block. * @const */ Blockly.Events.DELETE = 'delete'; /** * Name of event that changes a block. * @const */ Blockly.Events.CHANGE = 'change'; /** * Name of event that moves a block. * @const */ Blockly.Events.MOVE = 'move'; /** * Name of event that records a UI change. * @const */ Blockly.Events.UI = 'ui'; /** * List of events queued for firing. * @private */ Blockly.Events.FIRE_QUEUE_ = []; /** * Create a custom event and fire it. * @param {!Blockly.Events.Abstract} event Custom data for event. */ Blockly.Events.fire = function(event) { if (!Blockly.Events.isEnabled()) { return; } if (!Blockly.Events.FIRE_QUEUE_.length) { // First event added; schedule a firing of the event queue. setTimeout(Blockly.Events.fireNow_, 0); } Blockly.Events.FIRE_QUEUE_.push(event); }; /** * Fire all queued events. * @private */ Blockly.Events.fireNow_ = function() { var queue = Blockly.Events.filter(Blockly.Events.FIRE_QUEUE_, true); Blockly.Events.FIRE_QUEUE_.length = 0; for (var i = 0, event; event = queue[i]; i++) { var workspace = Blockly.Workspace.getById(event.workspaceId); if (workspace) { workspace.fireChangeListener(event); } } }; /** * Filter the queued events and merge duplicates. * @param {!Array.<!Blockly.Events.Abstract>} queueIn Array of events. * @param {boolean} forward True if forward (redo), false if backward (undo). * @return {!Array.<!Blockly.Events.Abstract>} Array of filtered events. */ Blockly.Events.filter = function(queueIn, forward) { var queue = goog.array.clone(queueIn); if (!forward) { // Undo is merged in reverse order. queue.reverse(); } // Merge duplicates. O(n^2), but n should be very small. for (var i = 0, event1; event1 = queue[i]; i++) { for (var j = i + 1, event2; event2 = queue[j]; j++) { if (event1.type == event2.type && event1.blockId == event2.blockId && event1.workspaceId == event2.workspaceId) { if (event1.type == Blockly.Events.MOVE) { // Merge move events. event1.newParentId = event2.newParentId; event1.newInputName = event2.newInputName; event1.newCoordinate = event2.newCoordinate; queue.splice(j, 1); j--; } else if (event1.type == Blockly.Events.CHANGE && event1.element == event2.element && event1.name == event2.name) { // Merge change events. event1.newValue = event2.newValue; queue.splice(j, 1); j--; } else if (event1.type == Blockly.Events.UI && event2.element == 'click' && (event1.element == 'commentOpen' || event1.element == 'mutatorOpen' || event1.element == 'warningOpen')) { // Merge change events. event1.newValue = event2.newValue; queue.splice(j, 1); j--; } } } } // Remove null events. for (var i = queue.length - 1; i >= 0; i--) { if (queue[i].isNull()) { queue.splice(i, 1); } } if (!forward) { // Restore undo order. queue.reverse(); } // Move mutation events to the top of the queue. // Intentionally skip first event. for (var i = 1, event; event = queue[i]; i++) { if (event.type == Blockly.Events.CHANGE && event.element == 'mutation') { queue.unshift(queue.splice(i, 1)[0]); } } return queue; }; /** * Modify pending undo events so that when they are fired they don't land * in the undo stack. Called by Blockly.Workspace.clearUndo. */ Blockly.Events.clearPendingUndo = function() { for (var i = 0, event; event = Blockly.Events.FIRE_QUEUE_[i]; i++) { event.recordUndo = false; } }; /** * Stop sending events. Every call to this function MUST also call enable. */ Blockly.Events.disable = function() { Blockly.Events.disabled_++; }; /** * Start sending events. Unless events were already disabled when the * corresponding call to disable was made. */ Blockly.Events.enable = function() { Blockly.Events.disabled_--; }; /** * Returns whether events may be fired or not. * @return {boolean} True if enabled. */ Blockly.Events.isEnabled = function() { return Blockly.Events.disabled_ == 0; }; /** * Current group. * @return {string} ID string. */ Blockly.Events.getGroup = function() { return Blockly.Events.group_; }; /** * Start or stop a group. * @param {boolean|string} state True to start new group, false to end group. * String to set group explicitly. */ Blockly.Events.setGroup = function(state) { if (typeof state == 'boolean') { Blockly.Events.group_ = state ? Blockly.utils.genUid() : ''; } else { Blockly.Events.group_ = state; } }; /** * Compute a list of the IDs of the specified block and all its descendants. * @param {!Blockly.Block} block The root block. * @return {!Array.<string>} List of block IDs. * @private */ Blockly.Events.getDescendantIds_ = function(block) { var ids = []; var descendants = block.getDescendants(); for (var i = 0, descendant; descendant = descendants[i]; i++) { ids[i] = descendant.id; } return ids; }; /** * Decode the JSON into an event. * @param {!Object} json JSON representation. * @param {!Blockly.Workspace} workspace Target workspace for event. * @return {!Blockly.Events.Abstract} The event represented by the JSON. */ Blockly.Events.fromJson = function(json, workspace) { var event; switch (json.type) { case Blockly.Events.CREATE: event = new Blockly.Events.Create(null); break; case Blockly.Events.DELETE: event = new Blockly.Events.Delete(null); break; case Blockly.Events.CHANGE: event = new Blockly.Events.Change(null); break; case Blockly.Events.MOVE: event = new Blockly.Events.Move(null); break; case Blockly.Events.UI: event = new Blockly.Events.Ui(null); break; default: throw 'Unknown event type.'; } event.fromJson(json); event.workspaceId = workspace.id; return event; }; /** * Abstract class for an event. * @param {Blockly.Block} block The block. * @constructor */ Blockly.Events.Abstract = function(block) { if (block) { this.blockId = block.id; this.workspaceId = block.workspace.id; } this.group = Blockly.Events.group_; this.recordUndo = Blockly.Events.recordUndo; }; /** * Encode the event as JSON. * @return {!Object} JSON representation. */ Blockly.Events.Abstract.prototype.toJson = function() { var json = { 'type': this.type }; if (this.blockId) { json['blockId'] = this.blockId; } if (this.group) { json['group'] = this.group; } return json; }; /** * Decode the JSON event. * @param {!Object} json JSON representation. */ Blockly.Events.Abstract.prototype.fromJson = function(json) { this.blockId = json['blockId']; this.group = json['group']; }; /** * Does this event record any change of state? * @return {boolean} True if null, false if something changed. */ Blockly.Events.Abstract.prototype.isNull = function() { return false; }; /** * Run an event. * @param {boolean} forward True if run forward, false if run backward (undo). */ Blockly.Events.Abstract.prototype.run = function(forward) { // Defined by subclasses. }; /** * Class for a block creation event. * @param {Blockly.Block} block The created block. Null for a blank event. * @extends {Blockly.Events.Abstract} * @constructor */ Blockly.Events.Create = function(block) { if (!block) { return; // Blank event to be populated by fromJson. } Blockly.Events.Create.superClass_.constructor.call(this, block); if (block.workspace.rendered) { this.xml = Blockly.Xml.blockToDomWithXY(block); } else { this.xml = Blockly.Xml.blockToDom(block); } this.ids = Blockly.Events.getDescendantIds_(block); }; goog.inherits(Blockly.Events.Create, Blockly.Events.Abstract); /** * Type of this event. * @type {string} */ Blockly.Events.Create.prototype.type = Blockly.Events.CREATE; /** * Encode the event as JSON. * @return {!Object} JSON representation. */ Blockly.Events.Create.prototype.toJson = function() { var json = Blockly.Events.Create.superClass_.toJson.call(this); json['xml'] = Blockly.Xml.domToText(this.xml); json['ids'] = this.ids; return json; }; /** * Decode the JSON event. * @param {!Object} json JSON representation. */ Blockly.Events.Create.prototype.fromJson = function(json) { Blockly.Events.Create.superClass_.fromJson.call(this, json); this.xml = Blockly.Xml.textToDom('<xml>' + json['xml'] + '</xml>').firstChild; this.ids = json['ids']; }; /** * Run a creation event. * @param {boolean} forward True if run forward, false if run backward (undo). */ Blockly.Events.Create.prototype.run = function(forward) { var workspace = Blockly.Workspace.getById(this.workspaceId); if (forward) { var xml = goog.dom.createDom('xml'); xml.appendChild(this.xml); Blockly.Xml.domToWorkspace(xml, workspace); } else { for (var i = 0, id; id = this.ids[i]; i++) { var block = workspace.getBlockById(id); if (block) { block.dispose(false, false); } else if (id == this.blockId) { // Only complain about root-level block. console.warn("Can't uncreate non-existant block: " + id); } } } }; /** * Class for a block deletion event. * @param {Blockly.Block} block The deleted block. Null for a blank event. * @extends {Blockly.Events.Abstract} * @constructor */ Blockly.Events.Delete = function(block) { if (!block) { return; // Blank event to be populated by fromJson. } if (block.getParent()) { throw 'Connected blocks cannot be deleted.'; } Blockly.Events.Delete.superClass_.constructor.call(this, block); if (block.workspace.rendered) { this.oldXml = Blockly.Xml.blockToDomWithXY(block); } else { this.oldXml = Blockly.Xml.blockToDom(block); } this.ids = Blockly.Events.getDescendantIds_(block); }; goog.inherits(Blockly.Events.Delete, Blockly.Events.Abstract); /** * Type of this event. * @type {string} */ Blockly.Events.Delete.prototype.type = Blockly.Events.DELETE; /** * Encode the event as JSON. * @return {!Object} JSON representation. */ Blockly.Events.Delete.prototype.toJson = function() { var json = Blockly.Events.Delete.superClass_.toJson.call(this); json['ids'] = this.ids; return json; }; /** * Decode the JSON event. * @param {!Object} json JSON representation. */ Blockly.Events.Delete.prototype.fromJson = function(json) { Blockly.Events.Delete.superClass_.fromJson.call(this, json); this.ids = json['ids']; }; /** * Run a deletion event. * @param {boolean} forward True if run forward, false if run backward (undo). */ Blockly.Events.Delete.prototype.run = function(forward) { var workspace = Blockly.Workspace.getById(this.workspaceId); if (forward) { for (var i = 0, id; id = this.ids[i]; i++) { var block = workspace.getBlockById(id); if (block) { block.dispose(false, false); } else if (id == this.blockId) { // Only complain about root-level block. console.warn("Can't delete non-existant block: " + id); } } } else { var xml = goog.dom.createDom('xml'); xml.appendChild(this.oldXml); Blockly.Xml.domToWorkspace(xml, workspace); } }; /** * Class for a block change event. * @param {Blockly.Block} block The changed block. Null for a blank event. * @param {string} element One of 'field', 'comment', 'disabled', etc. * @param {?string} name Name of input or field affected, or null. * @param {string} oldValue Previous value of element. * @param {string} newValue New value of element. * @extends {Blockly.Events.Abstract} * @constructor */ Blockly.Events.Change = function(block, element, name, oldValue, newValue) { if (!block) { return; // Blank event to be populated by fromJson. } Blockly.Events.Change.superClass_.constructor.call(this, block); this.element = element; this.name = name; this.oldValue = oldValue; this.newValue = newValue; }; goog.inherits(Blockly.Events.Change, Blockly.Events.Abstract); /** * Type of this event. * @type {string} */ Blockly.Events.Change.prototype.type = Blockly.Events.CHANGE; /** * Encode the event as JSON. * @return {!Object} JSON representation. */ Blockly.Events.Change.prototype.toJson = function() { var json = Blockly.Events.Change.superClass_.toJson.call(this); json['element'] = this.element; if (this.name) { json['name'] = this.name; } json['newValue'] = this.newValue; return json; }; /** * Decode the JSON event. * @param {!Object} json JSON representation. */ Blockly.Events.Change.prototype.fromJson = function(json) { Blockly.Events.Change.superClass_.fromJson.call(this, json); this.element = json['element']; this.name = json['name']; this.newValue = json['newValue']; }; /** * Does this event record any change of state? * @return {boolean} True if something changed. */ Blockly.Events.Change.prototype.isNull = function() { return this.oldValue == this.newValue; }; /** * Run a change event. * @param {boolean} forward True if run forward, false if run backward (undo). */ Blockly.Events.Change.prototype.run = function(forward) { var workspace = Blockly.Workspace.getById(this.workspaceId); var block = workspace.getBlockById(this.blockId); if (!block) { console.warn("Can't change non-existant block: " + this.blockId); return; } if (block.mutator) { // Close the mutator (if open) since we don't want to update it. block.mutator.setVisible(false); } var value = forward ? this.newValue : this.oldValue; switch (this.element) { case 'field': var field = block.getField(this.name); if (field) { // Run the validator for any side-effects it may have. // The validator's opinion on validity is ignored. field.callValidator(value); field.setValue(value); } else { console.warn("Can't set non-existant field: " + this.name); } break; case 'comment': block.setCommentText(value || null); break; case 'collapsed': block.setCollapsed(value); break; case 'disabled': block.setDisabled(value); break; case 'inline': block.setInputsInline(value); break; case 'mutation': var oldMutation = ''; if (block.mutationToDom) { var oldMutationDom = block.mutationToDom(); oldMutation = oldMutationDom && Blockly.Xml.domToText(oldMutationDom); } if (block.domToMutation) { value = value || '<mutation></mutation>'; var dom = Blockly.Xml.textToDom('<xml>' + value + '</xml>'); block.domToMutation(dom.firstChild); } Blockly.Events.fire(new Blockly.Events.Change( block, 'mutation', null, oldMutation, value)); break; default: console.warn('Unknown change type: ' + this.element); } }; /** * Class for a block move event. Created before the move. * @param {Blockly.Block} block The moved block. Null for a blank event. * @extends {Blockly.Events.Abstract} * @constructor */ Blockly.Events.Move = function(block) { if (!block) { return; // Blank event to be populated by fromJson. } Blockly.Events.Move.superClass_.constructor.call(this, block); var location = this.currentLocation_(); this.oldParentId = location.parentId; this.oldInputName = location.inputName; this.oldCoordinate = location.coordinate; }; goog.inherits(Blockly.Events.Move, Blockly.Events.Abstract); /** * Type of this event. * @type {string} */ Blockly.Events.Move.prototype.type = Blockly.Events.MOVE; /** * Encode the event as JSON. * @return {!Object} JSON representation. */ Blockly.Events.Move.prototype.toJson = function() { var json = Blockly.Events.Move.superClass_.toJson.call(this); if (this.newParentId) { json['newParentId'] = this.newParentId; } if (this.newInputName) { json['newInputName'] = this.newInputName; } if (this.newCoordinate) { json['newCoordinate'] = Math.round(this.newCoordinate.x) + ',' + Math.round(this.newCoordinate.y); } return json; }; /** * Decode the JSON event. * @param {!Object} json JSON representation. */ Blockly.Events.Move.prototype.fromJson = function(json) { Blockly.Events.Move.superClass_.fromJson.call(this, json); this.newParentId = json['newParentId']; this.newInputName = json['newInputName']; if (json['newCoordinate']) { var xy = json['newCoordinate'].split(','); this.newCoordinate = new goog.math.Coordinate(parseFloat(xy[0]), parseFloat(xy[1])); } }; /** * Record the block's new location. Called after the move. */ Blockly.Events.Move.prototype.recordNew = function() { var location = this.currentLocation_(); this.newParentId = location.parentId; this.newInputName = location.inputName; this.newCoordinate = location.coordinate; }; /** * Returns the parentId and input if the block is connected, * or the XY location if disconnected. * @return {!Object} Collection of location info. * @private */ Blockly.Events.Move.prototype.currentLocation_ = function() { var workspace = Blockly.Workspace.getById(this.workspaceId); var block = workspace.getBlockById(this.blockId); var location = {}; var parent = block.getParent(); if (parent) { location.parentId = parent.id; var input = parent.getInputWithBlock(block); if (input) { location.inputName = input.name; } } else { location.coordinate = block.getRelativeToSurfaceXY(); } return location; }; /** * Does this event record any change of state? * @return {boolean} True if something changed. */ Blockly.Events.Move.prototype.isNull = function() { return this.oldParentId == this.newParentId && this.oldInputName == this.newInputName && goog.math.Coordinate.equals(this.oldCoordinate, this.newCoordinate); }; /** * Run a move event. * @param {boolean} forward True if run forward, false if run backward (undo). */ Blockly.Events.Move.prototype.run = function(forward) { var workspace = Blockly.Workspace.getById(this.workspaceId); var block = workspace.getBlockById(this.blockId); if (!block) { console.warn("Can't move non-existant block: " + this.blockId); return; } var parentId = forward ? this.newParentId : this.oldParentId; var inputName = forward ? this.newInputName : this.oldInputName; var coordinate = forward ? this.newCoordinate : this.oldCoordinate; var parentBlock = null; if (parentId) { parentBlock = workspace.getBlockById(parentId); if (!parentBlock) { console.warn("Can't connect to non-existant block: " + parentId); return; } } if (block.getParent()) { block.unplug(); } if (coordinate) { var xy = block.getRelativeToSurfaceXY(); block.moveBy(coordinate.x - xy.x, coordinate.y - xy.y); } else { var blockConnection = block.outputConnection || block.previousConnection; var parentConnection; if (inputName) { var input = parentBlock.getInput(inputName); if (input) { parentConnection = input.connection; } } else if (blockConnection.type == Blockly.PREVIOUS_STATEMENT) { parentConnection = parentBlock.nextConnection; } if (parentConnection) { blockConnection.connect(parentConnection); } else { console.warn("Can't connect to non-existant input: " + inputName); } } }; /** * Class for a UI event. * @param {Blockly.Block} block The affected block. * @param {string} element One of 'selected', 'comment', 'mutator', etc. * @param {string} oldValue Previous value of element. * @param {string} newValue New value of element. * @extends {Blockly.Events.Abstract} * @constructor */ Blockly.Events.Ui = function(block, element, oldValue, newValue) { Blockly.Events.Ui.superClass_.constructor.call(this, block); this.element = element; this.oldValue = oldValue; this.newValue = newValue; this.recordUndo = false; }; goog.inherits(Blockly.Events.Ui, Blockly.Events.Abstract); /** * Type of this event. * @type {string} */ Blockly.Events.Ui.prototype.type = Blockly.Events.UI; /** * Encode the event as JSON. * @return {!Object} JSON representation. */ Blockly.Events.Ui.prototype.toJson = function() { var json = Blockly.Events.Ui.superClass_.toJson.call(this); json['element'] = this.element; if (this.newValue !== undefined) { json['newValue'] = this.newValue; } return json; }; /** * Decode the JSON event. * @param {!Object} json JSON representation. */ Blockly.Events.Ui.prototype.fromJson = function(json) { Blockly.Events.Ui.superClass_.fromJson.call(this, json); this.element = json['element']; this.newValue = json['newValue']; }; /** * Enable/disable a block depending on whether it is properly connected. * Use this on applications where all blocks should be connected to a top block. * Recommend setting the 'disable' option to 'false' in the config so that * users don't try to reenable disabled orphan blocks. * @param {!Blockly.Events.Abstract} event Custom data for event. */ Blockly.Events.disableOrphans = function(event) { if (event.type == Blockly.Events.MOVE || event.type == Blockly.Events.CREATE) { Blockly.Events.disable(); var workspace = Blockly.Workspace.getById(event.workspaceId); var block = workspace.getBlockById(event.blockId); if (block) { if (block.getParent() && !block.getParent().disabled) { var children = block.getDescendants(); for (var i = 0, child; child = children[i]; i++) { child.setDisabled(false); } } else if ((block.outputConnection || block.previousConnection) && Blockly.dragMode_ == Blockly.DRAG_NONE) { do { block.setDisabled(true); block = block.getNextBlock(); } while (block); } } Blockly.Events.enable(); } };
/** * @license AngularJS v1.3.4 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document, undefined) {'use strict'; /** * @description * * This object provides a utility for producing rich Error messages within * Angular. It can be called as follows: * * var exampleMinErr = minErr('example'); * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); * * The above creates an instance of minErr in the example namespace. The * resulting error will have a namespaced error code of example.one. The * resulting error will replace {0} with the value of foo, and {1} with the * value of bar. The object is not restricted in the number of arguments it can * take. * * If fewer arguments are specified than necessary for interpolation, the extra * interpolation markers will be preserved in the final string. * * Since data will be parsed statically during a build step, some restrictions * are applied with respect to how minErr instances are created and called. * Instances should have names of the form namespaceMinErr for a minErr created * using minErr('namespace') . Error codes, namespaces and template strings * should all be static strings, not variables or general expressions. * * @param {string} module The namespace to use for the new minErr instance. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning * error from returned function, for cases when a particular type of error is useful. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance */ function minErr(module, ErrorConstructor) { ErrorConstructor = ErrorConstructor || Error; return function() { var code = arguments[0], prefix = '[' + (module ? module + ':' : '') + code + '] ', template = arguments[1], templateArgs = arguments, message, i; message = prefix + template.replace(/\{\d+\}/g, function(match) { var index = +match.slice(1, -1), arg; if (index + 2 < templateArgs.length) { return toDebugString(templateArgs[index + 2]); } return match; }); message = message + '\nhttp://errors.angularjs.org/1.3.4/' + (module ? module + '/' : '') + code; for (i = 2; i < arguments.length; i++) { message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' + encodeURIComponent(toDebugString(arguments[i])); } return new ErrorConstructor(message); }; } /* We need to tell jshint what variables are being exported */ /* global angular: true, msie: true, jqLite: true, jQuery: true, slice: true, splice: true, push: true, toString: true, ngMinErr: true, angularModule: true, uid: true, REGEX_STRING_REGEXP: true, VALIDITY_STATE_PROPERTY: true, lowercase: true, uppercase: true, manualLowercase: true, manualUppercase: true, nodeName_: true, isArrayLike: true, forEach: true, sortedKeys: true, forEachSorted: true, reverseParams: true, nextUid: true, setHashKey: true, extend: true, int: true, inherit: true, noop: true, identity: true, valueFn: true, isUndefined: true, isDefined: true, isObject: true, isString: true, isNumber: true, isDate: true, isArray: true, isFunction: true, isRegExp: true, isWindow: true, isScope: true, isFile: true, isBlob: true, isBoolean: true, isPromiseLike: true, trim: true, escapeForRegexp: true, isElement: true, makeMap: true, includes: true, arrayRemove: true, copy: true, shallowCopy: true, equals: true, csp: true, concat: true, sliceArgs: true, bind: true, toJsonReplacer: true, toJson: true, fromJson: true, startingTag: true, tryDecodeURIComponent: true, parseKeyValue: true, toKeyValue: true, encodeUriSegment: true, encodeUriQuery: true, angularInit: true, bootstrap: true, getTestability: true, snake_case: true, bindJQuery: true, assertArg: true, assertArgFn: true, assertNotHasOwnProperty: true, getter: true, getBlockNodes: true, hasOwnProperty: true, createMap: true, NODE_TYPE_ELEMENT: true, NODE_TYPE_TEXT: true, NODE_TYPE_COMMENT: true, NODE_TYPE_DOCUMENT: true, NODE_TYPE_DOCUMENT_FRAGMENT: true, */ //////////////////////////////////// /** * @ngdoc module * @name ng * @module ng * @description * * # ng (core module) * The ng module is loaded by default when an AngularJS application is started. The module itself * contains the essential components for an AngularJS application to function. The table below * lists a high level breakdown of each of the services/factories, filters, directives and testing * components available within this core module. * * <div doc-module-components="ng"></div> */ var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; // The name of a form control's ValidityState property. // This is used so that it's possible for internal tests to create mock ValidityStates. var VALIDITY_STATE_PROPERTY = 'validity'; /** * @ngdoc function * @name angular.lowercase * @module ng * @kind function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;}; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * @ngdoc function * @name angular.uppercase * @module ng * @kind function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { /* jshint bitwise: false */ return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { /* jshint bitwise: false */ return isString(s) ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } var /** holds major version number for IE or NaN for real browsers */ msie, jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, splice = [].splice, push = [].push, toString = Object.prototype.toString, ngMinErr = minErr('ng'), /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, uid = 0; /** * documentMode is an IE-only property * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx */ msie = document.documentMode; /** * @private * @param {*} obj * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, * String ...) */ function isArrayLike(obj) { if (obj == null || isWindow(obj)) { return false; } var length = obj.length; if (obj.nodeType === NODE_TYPE_ELEMENT && length) { return true; } return isString(obj) || isArray(obj) || length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj; } /** * @ngdoc function * @name angular.forEach * @module ng * @kind function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value` * is the value of an object property or an array element, `key` is the object property key or * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional. * * It is worth noting that `.forEach` does not iterate over inherited properties because it filters * using the `hasOwnProperty` method. * * Unlike ES262's * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18), * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just * return the value provided. * ```js var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key) { this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender: male']); ``` * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key, length; if (obj) { if (isFunction(obj)) { for (key in obj) { // Need to check if hasOwnProperty exists, // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) { iterator.call(context, obj[key], key, obj); } } } else if (isArray(obj) || isArrayLike(obj)) { var isPrimitive = typeof obj !== 'object'; for (key = 0, length = obj.length; key < length; key++) { if (isPrimitive || key in obj) { iterator.call(context, obj[key], key, obj); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context, obj); } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key, obj); } } } } return obj; } function sortedKeys(obj) { return Object.keys(obj).sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for (var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value); }; } /** * A consistent way of creating unique IDs in angular. * * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before * we hit number precision issues in JavaScript. * * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M * * @returns {number} an unique alpha-numeric string */ function nextUid() { return ++uid; } /** * Set or clear the hashkey for an object. * @param obj object * @param h the hashkey (!truthy to delete the hashkey) */ function setHashKey(obj, h) { if (h) { obj.$$hashKey = h; } else { delete obj.$$hashKey; } } /** * @ngdoc function * @name angular.extend * @module ng * @kind function * * @description * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`. * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy). * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ function extend(dst) { var h = dst.$$hashKey; for (var i = 1, ii = arguments.length; i < ii; i++) { var obj = arguments[i]; if (obj) { var keys = Object.keys(obj); for (var j = 0, jj = keys.length; j < jj; j++) { var key = keys[j]; dst[key] = obj[key]; } } } setHashKey(dst, h); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(Object.create(parent), extra); } /** * @ngdoc function * @name angular.noop * @module ng * @kind function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. ```js function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } ``` */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @module ng * @kind function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * ```js function transformer(transformationFn, value) { return (transformationFn || angular.identity)(value); }; ``` */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @module ng * @kind function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value) {return typeof value === 'undefined';} /** * @ngdoc function * @name angular.isDefined * @module ng * @kind function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value) {return typeof value !== 'undefined';} /** * @ngdoc function * @name angular.isObject * @module ng * @kind function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. Note that JavaScript arrays are objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value) { // http://jsperf.com/isobject4 return value !== null && typeof value === 'object'; } /** * @ngdoc function * @name angular.isString * @module ng * @kind function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value) {return typeof value === 'string';} /** * @ngdoc function * @name angular.isNumber * @module ng * @kind function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value) {return typeof value === 'number';} /** * @ngdoc function * @name angular.isDate * @module ng * @kind function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value) { return toString.call(value) === '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @module ng * @kind function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ var isArray = Array.isArray; /** * @ngdoc function * @name angular.isFunction * @module ng * @kind function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value) {return typeof value === 'function';} /** * Determines if a value is a regular expression object. * * @private * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `RegExp`. */ function isRegExp(value) { return toString.call(value) === '[object RegExp]'; } /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.window === obj; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.call(obj) === '[object File]'; } function isBlob(obj) { return toString.call(obj) === '[object Blob]'; } function isBoolean(value) { return typeof value === 'boolean'; } function isPromiseLike(obj) { return obj && isFunction(obj.then); } var trim = function(value) { return isString(value) ? value.trim() : value; }; // Copied from: // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021 // Prereq: s is a string. var escapeForRegexp = function(s) { return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1'). replace(/\x08/g, '\\x08'); }; /** * @ngdoc function * @name angular.isElement * @module ng * @kind function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return !!(node && (node.nodeName // we are a direct element || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str) { var obj = {}, items = str.split(","), i; for (i = 0; i < items.length; i++) obj[ items[i] ] = true; return obj; } function nodeName_(element) { return lowercase(element.nodeName || (element[0] && element[0].nodeName)); } function includes(array, obj) { return Array.prototype.indexOf.call(array, obj) != -1; } function arrayRemove(array, value) { var index = array.indexOf(value); if (index >= 0) array.splice(index, 1); return value; } /** * @ngdoc function * @name angular.copy * @module ng * @kind function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. * * If `source` is identical to 'destination' an exception will be thrown. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. * * @example <example module="copyExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form novalidate class="simple-form"> Name: <input type="text" ng-model="user.name" /><br /> E-mail: <input type="email" ng-model="user.email" /><br /> Gender: <input type="radio" ng-model="user.gender" value="male" />male <input type="radio" ng-model="user.gender" value="female" />female<br /> <button ng-click="reset()">RESET</button> <button ng-click="update(user)">SAVE</button> </form> <pre>form = {{user | json}}</pre> <pre>master = {{master | json}}</pre> </div> <script> angular.module('copyExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.master= {}; $scope.update = function(user) { // Example with 1 argument $scope.master= angular.copy(user); }; $scope.reset = function() { // Example with 2 arguments angular.copy($scope.master, $scope.user); }; $scope.reset(); }]); </script> </file> </example> */ function copy(source, destination, stackSource, stackDest) { if (isWindow(source) || isScope(source)) { throw ngMinErr('cpws', "Can't copy! Making copies of Window or Scope instances is not supported."); } if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); destination.lastIndex = source.lastIndex; } else if (isObject(source)) { var emptyObject = Object.create(Object.getPrototypeOf(source)); destination = copy(source, emptyObject, stackSource, stackDest); } } } else { if (source === destination) throw ngMinErr('cpi', "Can't copy! Source and destination are identical."); stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = stackSource.indexOf(source); if (index !== -1) return stackDest[index]; stackSource.push(source); stackDest.push(destination); } var result; if (isArray(source)) { destination.length = 0; for (var i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { var h = destination.$$hashKey; if (isArray(destination)) { destination.length = 0; } else { forEach(destination, function(value, key) { delete destination[key]; }); } for (var key in source) { if (source.hasOwnProperty(key)) { result = copy(source[key], null, stackSource, stackDest); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } setHashKey(destination,h); } } return destination; } /** * Creates a shallow copy of an object, an array or a primitive. * * Assumes that there are no proto properties for objects. */ function shallowCopy(src, dst) { if (isArray(src)) { dst = dst || []; for (var i = 0, ii = src.length; i < ii; i++) { dst[i] = src[i]; } } else if (isObject(src)) { dst = dst || {}; for (var key in src) { if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { dst[key] = src[key]; } } } return dst || src; } /** * @ngdoc function * @name angular.equals * @module ng * @kind function * * @description * Determines if two objects or two values are equivalent. Supports value types, regular * expressions, arrays and objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties are equal by * comparing them with `angular.equals`. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) * * Both values represent the same regular expression (In JavaScript, * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual * representation matches). * * During a property comparison, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only by identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if (!isArray(o2)) return false; if ((length = o1.length) == o2.length) { for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { if (!isDate(o2)) return false; return equals(o1.getTime(), o2.getTime()); } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false; keySet = {}; for (key in o1) { if (key.charAt(0) === '$' || isFunction(o1[key])) continue; if (!equals(o1[key], o2[key])) return false; keySet[key] = true; } for (key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) return false; } return true; } } } return false; } var csp = function() { if (isDefined(csp.isActive_)) return csp.isActive_; var active = !!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]')); if (!active) { try { /* jshint -W031, -W054 */ new Function(''); /* jshint +W031, +W054 */ } catch (e) { active = true; } } return (csp.isActive_ = active); }; function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /* jshint -W101 */ /** * @ngdoc function * @name angular.bind * @module ng * @kind function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are prebound to the function. This feature is also * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ /* jshint +W101 */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, concat(curryArgs, arguments, 0)) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @module ng * @kind function * * @description * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be * stripped since angular uses this notation internally. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string|undefined} JSON-ified string representing `obj`. */ function toJson(obj, pretty) { if (typeof obj === 'undefined') return undefined; return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } /** * @ngdoc function * @name angular.fromJson * @module ng * @kind function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.empty(); } catch (e) {} var elemHtml = jqLite('<div>').append(element).html(); try { return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) : elemHtml. match(/^(<[^>]+>)/)[1]. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); } catch (e) { return lowercase(elemHtml); } } ///////////////////////////////////////////////// /** * Tries to decode the URI component without throwing an exception. * * @private * @param str value potential URI component to check. * @returns {boolean} True if `value` can be decoded * with the decodeURIComponent function. */ function tryDecodeURIComponent(value) { try { return decodeURIComponent(value); } catch (e) { // Ignore any invalid uri component } } /** * Parses an escaped url query string into key-value pairs. * @returns {Object.<string,boolean|Array>} */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue) { if (keyValue) { key_value = keyValue.replace(/\+/g,'%20').split('='); key = tryDecodeURIComponent(key_value[0]); if (isDefined(key)) { var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; if (!hasOwnProperty.call(obj, key)) { obj[key] = val; } else if (isArray(obj[key])) { obj[key].push(val); } else { obj[key] = [obj[key],val]; } } } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { if (isArray(value)) { forEach(value, function(arrayValue) { parts.push(encodeUriQuery(key, true) + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); }); } else { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); } }); return parts.length ? parts.join('&') : ''; } /** * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%3B/gi, ';'). replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); } var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; function getNgAttribute(element, ngAttr) { var attr, i, ii = ngAttrPrefixes.length; element = jqLite(element); for (i = 0; i < ii; ++i) { attr = ngAttrPrefixes[i] + ngAttr; if (isString(attr = element.attr(attr))) { return attr; } } return null; } /** * @ngdoc directive * @name ngApp * @module ng * * @element ANY * @param {angular.Module} ngApp an optional application * {@link angular.module module} name to load. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be * created in "strict-di" mode. This means that the application will fail to invoke functions which * do not use explicit function annotation (and are thus unsuitable for minification), as described * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in * tracking down the root of these bugs. * * @description * * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive * designates the **root element** of the application and is typically placed near the root element * of the page - e.g. on the `<body>` or `<html>` tags. * * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` * found in the document will be used to define the root element to auto-bootstrap as an * application. To run multiple applications in an HTML document you must manually bootstrap them using * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. * * You can specify an **AngularJS module** to be used as the root module for the application. This * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and * should contain the application code needed or have dependencies on other modules that will * contain the code. See {@link angular.module} for more information. * * In the example below if the `ngApp` directive were not placed on the `html` element then the * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` * would not be resolved to `3`. * * `ngApp` is the easiest, and most common, way to bootstrap an application. * <example module="ngAppDemo"> <file name="index.html"> <div ng-controller="ngAppDemoController"> I can add: {{a}} + {{b}} = {{ a+b }} </div> </file> <file name="script.js"> angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { $scope.a = 1; $scope.b = 2; }); </file> </example> * * Using `ngStrictDi`, you would see something like this: * <example ng-app-included="true"> <file name="index.html"> <div ng-app="ngAppStrictDemo" ng-strict-di> <div ng-controller="GoodController1"> I can add: {{a}} + {{b}} = {{ a+b }} <p>This renders because the controller does not fail to instantiate, by using explicit annotation style (see script.js for details) </p> </div> <div ng-controller="GoodController2"> Name: <input ng-model="name"><br /> Hello, {{name}}! <p>This renders because the controller does not fail to instantiate, by using explicit annotation style (see script.js for details) </p> </div> <div ng-controller="BadController"> I can add: {{a}} + {{b}} = {{ a+b }} <p>The controller could not be instantiated, due to relying on automatic function annotations (which are disabled in strict mode). As such, the content of this section is not interpolated, and there should be an error in your web console. </p> </div> </div> </file> <file name="script.js"> angular.module('ngAppStrictDemo', []) // BadController will fail to instantiate, due to relying on automatic function annotation, // rather than an explicit annotation .controller('BadController', function($scope) { $scope.a = 1; $scope.b = 2; }) // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated, // due to using explicit annotations using the array style and $inject property, respectively. .controller('GoodController1', ['$scope', function($scope) { $scope.a = 1; $scope.b = 2; }]) .controller('GoodController2', GoodController2); function GoodController2($scope) { $scope.name = "World"; } GoodController2.$inject = ['$scope']; </file> <file name="style.css"> div[ng-controller] { margin-bottom: 1em; -webkit-border-radius: 4px; border-radius: 4px; border: 1px solid; padding: .5em; } div[ng-controller^=Good] { border-color: #d6e9c6; background-color: #dff0d8; color: #3c763d; } div[ng-controller^=Bad] { border-color: #ebccd1; background-color: #f2dede; color: #a94442; margin-bottom: 0; } </file> </example> */ function angularInit(element, bootstrap) { var appElement, module, config = {}; // The element `element` has priority over any other element forEach(ngAttrPrefixes, function(prefix) { var name = prefix + 'app'; if (!appElement && element.hasAttribute && element.hasAttribute(name)) { appElement = element; module = element.getAttribute(name); } }); forEach(ngAttrPrefixes, function(prefix) { var name = prefix + 'app'; var candidate; if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) { appElement = candidate; module = candidate.getAttribute(name); } }); if (appElement) { config.strictDi = getNgAttribute(appElement, "strict-di") !== null; bootstrap(appElement, module ? [module] : [], config); } } /** * @ngdoc function * @name angular.bootstrap * @module ng * @description * Use this function to manually start up angular application. * * See: {@link guide/bootstrap Bootstrap} * * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually. * They must use {@link ng.directive:ngApp ngApp}. * * Angular will detect if it has been loaded into the browser more than once and only allow the * first loaded script to be bootstrapped and will report a warning to the browser console for * each of the subsequent scripts. This prevents strange results in applications, where otherwise * multiple instances of Angular try to work on the DOM. * * ```html * <!doctype html> * <html> * <body> * <div ng-controller="WelcomeController"> * {{greeting}} * </div> * * <script src="angular.js"></script> * <script> * var app = angular.module('demo', []) * .controller('WelcomeController', function($scope) { * $scope.greeting = 'Welcome!'; * }); * angular.bootstrap(document, ['demo']); * </script> * </body> * </html> * ``` * * @param {DOMElement} element DOM element which is the root of angular application. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application. * Each item in the array should be the name of a predefined module or a (DI annotated) * function that will be invoked by the injector as a run block. * See: {@link angular.module modules} * @param {Object=} config an object for defining configuration options for the application. The * following keys are supported: * * * `strictDi` - disable automatic function annotation for the application. This is meant to * assist in finding bugs which break minified code. Defaults to `false`. * * @returns {auto.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules, config) { if (!isObject(config)) config = {}; var defaultConfig = { strictDi: false }; config = extend(defaultConfig, config); var doBootstrap = function() { element = jqLite(element); if (element.injector()) { var tag = (element[0] === document) ? 'document' : startingTag(element); //Encode angle brackets to prevent input from being sanitized to empty string #8683 throw ngMinErr( 'btstrpd', "App Already Bootstrapped with this Element '{0}'", tag.replace(/</,'&lt;').replace(/>/,'&gt;')); } modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); if (config.debugInfoEnabled) { // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`. modules.push(['$compileProvider', function($compileProvider) { $compileProvider.debugInfoEnabled(true); }]); } modules.unshift('ng'); var injector = createInjector(modules, config.strictDi); injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', function bootstrapApply(scope, element, compile, injector) { scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); }] ); return injector; }; var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/; var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) { config.debugInfoEnabled = true; window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, ''); } if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { return doBootstrap(); } window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); angular.resumeBootstrap = function(extraModules) { forEach(extraModules, function(module) { modules.push(module); }); doBootstrap(); }; } /** * @ngdoc function * @name angular.reloadWithDebugInfo * @module ng * @description * Use this function to reload the current application with debug information turned on. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`. * * See {@link ng.$compileProvider#debugInfoEnabled} for more. */ function reloadWithDebugInfo() { window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name; window.location.reload(); } /** * @name angular.getTestability * @module ng * @description * Get the testability service for the instance of Angular on the given * element. * @param {DOMElement} element DOM element which is the root of angular application. */ function getTestability(rootElement) { return angular.element(rootElement).injector().get('$$testability'); } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator) { separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } var bindJQueryFired = false; var skipDestroyOnNextJQueryCleanData; function bindJQuery() { var originalCleanData; if (bindJQueryFired) { return; } // bind to jQuery if present; jQuery = window.jQuery; // Use jQuery if it exists with proper functionality, otherwise default to us. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older // versions. It will not work for sure with jQuery <1.7, though. if (jQuery && jQuery.fn.on) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, isolateScope: JQLitePrototype.isolateScope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); // All nodes removed from the DOM via various jQuery APIs like .remove() // are passed through jQuery.cleanData. Monkey-patch this method to fire // the $destroy event on all removed nodes. originalCleanData = jQuery.cleanData; jQuery.cleanData = function(elems) { var events; if (!skipDestroyOnNextJQueryCleanData) { for (var i = 0, elem; (elem = elems[i]) != null; i++) { events = jQuery._data(elem, "events"); if (events && events.$destroy) { jQuery(elem).triggerHandler('$destroy'); } } } else { skipDestroyOnNextJQueryCleanData = false; } originalCleanData(elems); }; } else { jqLite = JQLite; } angular.element = jqLite; // Prevent double-proxying. bindJQueryFired = true; } /** * throw error if the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * throw error if the name given is hasOwnProperty * @param {String} name the name to test * @param {String} context the context in which the name is used, such as module or directive */ function assertNotHasOwnProperty(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); } } /** * Return the value accessible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {String} path path to traverse * @param {boolean} [bindFnToScope=true] * @returns {Object} value as accessible by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } /** * Return the DOM siblings between the first and last node in the given array. * @param {Array} array like object * @returns {jqLite} jqLite collection containing the nodes */ function getBlockNodes(nodes) { // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original // collection, otherwise update the original collection. var node = nodes[0]; var endNode = nodes[nodes.length - 1]; var blockNodes = [node]; do { node = node.nextSibling; if (!node) break; blockNodes.push(node); } while (node !== endNode); return jqLite(blockNodes); } /** * Creates a new object without a prototype. This object is useful for lookup without having to * guard against prototypically inherited properties via hasOwnProperty. * * Related micro-benchmarks: * - http://jsperf.com/object-create2 * - http://jsperf.com/proto-map-lookup/2 * - http://jsperf.com/for-in-vs-object-keys2 * * @returns {Object} */ function createMap() { return Object.create(null); } var NODE_TYPE_ELEMENT = 1; var NODE_TYPE_TEXT = 3; var NODE_TYPE_COMMENT = 8; var NODE_TYPE_DOCUMENT = 9; var NODE_TYPE_DOCUMENT_FRAGMENT = 11; /** * @ngdoc type * @name angular.Module * @module ng * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { var $injectorMinErr = minErr('$injector'); var ngMinErr = minErr('ng'); function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } var angular = ensure(window, 'angular', Object); // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap angular.$$minErr = angular.$$minErr || minErr; return ensure(angular, 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @module ng * @description * * The `angular.module` is a global place for creating, registering and retrieving Angular * modules. * All modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * When passed two or more arguments, a new module is created. If passed only one argument, an * existing module (the name passed as the first argument to `module`) is retrieved. * * * # Module * * A module is a collection of services, directives, controllers, filters, and configuration information. * `angular.module` is used to configure the {@link auto.$injector $injector}. * * ```js * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(['$locationProvider', function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }]); * ``` * * Then you can create an injector and load your modules like this: * * ```js * var injector = angular.injector(['ng', 'myModule']) * ``` * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {!Array.<string>=} requires If specified then new module is being created. If * unspecified then the module is being retrieved for further configuration. * @param {Function=} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { var assertNotHasOwnProperty = function(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); } }; assertNotHasOwnProperty(name, 'module'); if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + "the module name or forgot to load it. If registering a module ensure that you " + "specify the dependencies as the second argument.", name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var configBlocks = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke', 'push', configBlocks); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _configBlocks: configBlocks, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @module ng * * @description * Holds the list of modules which the injector will load before the current module is * loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @module ng * * @description * Name of the module. */ name: name, /** * @ngdoc method * @name angular.Module#provider * @module ng * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the * service. * @description * See {@link auto.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @module ng * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link auto.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @module ng * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link auto.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @module ng * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link auto.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @module ng * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link auto.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#animation * @module ng * @param {string} name animation name * @param {Function} animationFactory Factory function for creating new instance of an * animation. * @description * * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. * * * Defines an animation hook that can be later used with * {@link ngAnimate.$animate $animate} service and directives that use this service. * * ```js * module.animation('.animation-name', function($inject1, $inject2) { * return { * eventName : function(element, done) { * //code to run the animation * //once complete, then run done() * return function cancellationFunction(element) { * //code to cancel the animation * } * } * } * }) * ``` * * See {@link ng.$animateProvider#register $animateProvider.register()} and * {@link ngAnimate ngAnimate module} for more information. */ animation: invokeLater('$animateProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @module ng * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @module ng * @param {string|Object} name Controller name, or an object map of controllers where the * keys are the names and the values are the constructors. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @module ng * @param {string|Object} name Directive name, or an object map of directives where the * keys are the names and the values are the factories. * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @module ng * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. * For more about how to configure services, see * {@link providers#provider-recipe Provider Recipe}. */ config: config, /** * @ngdoc method * @name angular.Module#run * @module ng * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which should be performed when the injector is done * loading all modules. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod, queue) { if (!queue) queue = invokeQueue; return function() { queue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; }; } }); }; }); } /* global: toDebugString: true */ function serializeObject(obj) { var seen = []; return JSON.stringify(obj, function(key, val) { val = toJsonReplacer(key, val); if (isObject(val)) { if (seen.indexOf(val) >= 0) return '<<already seen>>'; seen.push(val); } return val; }); } function toDebugString(obj) { if (typeof obj === 'function') { return obj.toString().replace(/ \{[\s\S]*$/, ''); } else if (typeof obj === 'undefined') { return 'undefined'; } else if (typeof obj !== 'string') { return serializeObject(obj); } return obj; } /* global angularModule: true, version: true, $LocaleProvider, $CompileProvider, htmlAnchorDirective, inputDirective, inputDirective, formDirective, scriptDirective, selectDirective, styleDirective, optionDirective, ngBindDirective, ngBindHtmlDirective, ngBindTemplateDirective, ngClassDirective, ngClassEvenDirective, ngClassOddDirective, ngCspDirective, ngCloakDirective, ngControllerDirective, ngFormDirective, ngHideDirective, ngIfDirective, ngIncludeDirective, ngIncludeFillContentDirective, ngInitDirective, ngNonBindableDirective, ngPluralizeDirective, ngRepeatDirective, ngShowDirective, ngStyleDirective, ngSwitchDirective, ngSwitchWhenDirective, ngSwitchDefaultDirective, ngOptionsDirective, ngTranscludeDirective, ngModelDirective, ngListDirective, ngChangeDirective, patternDirective, patternDirective, requiredDirective, requiredDirective, minlengthDirective, minlengthDirective, maxlengthDirective, maxlengthDirective, ngValueDirective, ngModelOptionsDirective, ngAttributeAliasDirectives, ngEventDirectives, $AnchorScrollProvider, $AnimateProvider, $BrowserProvider, $CacheFactoryProvider, $ControllerProvider, $DocumentProvider, $ExceptionHandlerProvider, $FilterProvider, $InterpolateProvider, $IntervalProvider, $HttpProvider, $HttpBackendProvider, $LocationProvider, $LogProvider, $ParseProvider, $RootScopeProvider, $QProvider, $$QProvider, $$SanitizeUriProvider, $SceProvider, $SceDelegateProvider, $SnifferProvider, $TemplateCacheProvider, $TemplateRequestProvider, $$TestabilityProvider, $TimeoutProvider, $$RAFProvider, $$AsyncCallbackProvider, $WindowProvider */ /** * @ngdoc object * @name angular.version * @module ng * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.3.4', // all of these placeholder strings will be replaced by grunt's major: 1, // package task minor: 3, dot: 4, codeName: 'highfalutin-petroglyph' }; function publishExternalAPI(angular) { extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop': noop, 'bind': bind, 'toJson': toJson, 'fromJson': fromJson, 'identity': identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0}, 'getTestability': getTestability, '$$minErr': minErr, '$$csp': csp, 'reloadWithDebugInfo': reloadWithDebugInfo }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. $provide.provider({ $$sanitizeUri: $$SanitizeUriProvider }); $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtml: ngBindHtmlDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngIf: ngIfDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, pattern: patternDirective, ngPattern: patternDirective, required: requiredDirective, ngRequired: requiredDirective, minlength: minlengthDirective, ngMinlength: minlengthDirective, maxlength: maxlengthDirective, ngMaxlength: maxlengthDirective, ngValue: ngValueDirective, ngModelOptions: ngModelOptionsDirective }). directive({ ngInclude: ngIncludeFillContentDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $animate: $AnimateProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $interval: $IntervalProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $$q: $$QProvider, $sce: $SceProvider, $sceDelegate: $SceDelegateProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $templateRequest: $TemplateRequestProvider, $$testability: $$TestabilityProvider, $timeout: $TimeoutProvider, $window: $WindowProvider, $$rAF: $$RAFProvider, $$asyncCallback: $$AsyncCallbackProvider }); } ]); } /* global JQLitePrototype: true, addEventListenerFn: true, removeEventListenerFn: true, BOOLEAN_ATTR: true, ALIASED_ATTR: true, */ ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @module ng * @kind function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * * If jQuery is available, `angular.element` is an alias for the * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." * * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most * commonly needed functionality with the goal of having a very small footprint.</div> * * To use jQuery, simply load it before `DOMContentLoaded` event fired. * * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or * jqLite; they are never raw DOM references.</div> * * ## Angular's jqLite * jqLite provides only the following jQuery methods: * * - [`addClass()`](http://api.jquery.com/addClass/) * - [`after()`](http://api.jquery.com/after/) * - [`append()`](http://api.jquery.com/append/) * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData * - [`children()`](http://api.jquery.com/children/) - Does not support selectors * - [`clone()`](http://api.jquery.com/clone/) * - [`contents()`](http://api.jquery.com/contents/) * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()` * - [`data()`](http://api.jquery.com/data/) * - [`detach()`](http://api.jquery.com/detach/) * - [`empty()`](http://api.jquery.com/empty/) * - [`eq()`](http://api.jquery.com/eq/) * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name * - [`hasClass()`](http://api.jquery.com/hasClass/) * - [`html()`](http://api.jquery.com/html/) * - [`next()`](http://api.jquery.com/next/) - Does not support selectors * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors * - [`prepend()`](http://api.jquery.com/prepend/) * - [`prop()`](http://api.jquery.com/prop/) * - [`ready()`](http://api.jquery.com/ready/) * - [`remove()`](http://api.jquery.com/remove/) * - [`removeAttr()`](http://api.jquery.com/removeAttr/) * - [`removeClass()`](http://api.jquery.com/removeClass/) * - [`removeData()`](http://api.jquery.com/removeData/) * - [`replaceWith()`](http://api.jquery.com/replaceWith/) * - [`text()`](http://api.jquery.com/text/) * - [`toggleClass()`](http://api.jquery.com/toggleClass/) * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces * - [`val()`](http://api.jquery.com/val/) * - [`wrap()`](http://api.jquery.com/wrap/) * * ## jQuery/jqLite Extras * Angular also provides the following additional methods and events to both jQuery and jqLite: * * ### Events * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM * element before it is removed. * * ### Methods * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to * be enabled. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the * current element. This getter should be used only on elements that contain a directive which starts a new isolate * scope. Calling `scope()` on this element always returns the original non-isolate scope. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ JQLite.expando = 'ng339'; var jqCache = JQLite.cache = {}, jqId = 1, addEventListenerFn = function(element, type, fn) { element.addEventListener(type, fn, false); }, removeEventListenerFn = function(element, type, fn) { element.removeEventListener(type, fn, false); }; /* * !!! This is an undocumented "private" function !!! */ JQLite._data = function(node) { //jQuery always returns an object on cache miss return this.cache[node[this.expando]] || {}; }; function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"}; var jqLiteMinErr = minErr('jqLite'); /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; var HTML_REGEXP = /<|&#?\w+;/; var TAG_NAME_REGEXP = /<([\w:]+)/; var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi; var wrapMap = { 'option': [1, '<select multiple="multiple">', '</select>'], 'thead': [1, '<table>', '</table>'], 'col': [2, '<table><colgroup>', '</colgroup></table>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'], '_default': [0, "", ""] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function jqLiteIsTextNode(html) { return !HTML_REGEXP.test(html); } function jqLiteAcceptsData(node) { // The window object can accept data but has no nodeType // Otherwise we are only interested in elements (1) and documents (9) var nodeType = node.nodeType; return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT; } function jqLiteBuildFragment(html, context) { var tmp, tag, wrap, fragment = context.createDocumentFragment(), nodes = [], i; if (jqLiteIsTextNode(html)) { // Convert non-html into a text node nodes.push(context.createTextNode(html)); } else { // Convert html into DOM nodes tmp = tmp || fragment.appendChild(context.createElement("div")); tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase(); wrap = wrapMap[tag] || wrapMap._default; tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2]; // Descend through wrappers to the right content i = wrap[0]; while (i--) { tmp = tmp.lastChild; } nodes = concat(nodes, tmp.childNodes); tmp = fragment.firstChild; tmp.textContent = ""; } // Remove wrapper from fragment fragment.textContent = ""; fragment.innerHTML = ""; // Clear inner HTML forEach(nodes, function(node) { fragment.appendChild(node); }); return fragment; } function jqLiteParseHTML(html, context) { context = context || document; var parsed; if ((parsed = SINGLE_TAG_REGEXP.exec(html))) { return [context.createElement(parsed[1])]; } if ((parsed = jqLiteBuildFragment(html, context))) { return parsed.childNodes; } return []; } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } var argIsString; if (isString(element)) { element = trim(element); argIsString = true; } if (!(this instanceof JQLite)) { if (argIsString && element.charAt(0) != '<') { throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); } return new JQLite(element); } if (argIsString) { jqLiteAddNodes(this, jqLiteParseHTML(element)); } else { jqLiteAddNodes(this, element); } } function jqLiteClone(element) { return element.cloneNode(true); } function jqLiteDealoc(element, onlyDescendants) { if (!onlyDescendants) jqLiteRemoveData(element); if (element.querySelectorAll) { var descendants = element.querySelectorAll('*'); for (var i = 0, l = descendants.length; i < l; i++) { jqLiteRemoveData(descendants[i]); } } } function jqLiteOff(element, type, fn, unsupported) { if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); var expandoStore = jqLiteExpandoStore(element); var events = expandoStore && expandoStore.events; var handle = expandoStore && expandoStore.handle; if (!handle) return; //no listeners registered if (!type) { for (type in events) { if (type !== '$destroy') { removeEventListenerFn(element, type, handle); } delete events[type]; } } else { forEach(type.split(' '), function(type) { if (isDefined(fn)) { var listenerFns = events[type]; arrayRemove(listenerFns || [], fn); if (listenerFns && listenerFns.length > 0) { return; } } removeEventListenerFn(element, type, handle); delete events[type]; }); } } function jqLiteRemoveData(element, name) { var expandoId = element.ng339; var expandoStore = expandoId && jqCache[expandoId]; if (expandoStore) { if (name) { delete expandoStore.data[name]; return; } if (expandoStore.handle) { if (expandoStore.events.$destroy) { expandoStore.handle({}, '$destroy'); } jqLiteOff(element); } delete jqCache[expandoId]; element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it } } function jqLiteExpandoStore(element, createIfNecessary) { var expandoId = element.ng339, expandoStore = expandoId && jqCache[expandoId]; if (createIfNecessary && !expandoStore) { element.ng339 = expandoId = jqNextId(); expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined}; } return expandoStore; } function jqLiteData(element, key, value) { if (jqLiteAcceptsData(element)) { var isSimpleSetter = isDefined(value); var isSimpleGetter = !isSimpleSetter && key && !isObject(key); var massGetter = !key; var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter); var data = expandoStore && expandoStore.data; if (isSimpleSetter) { // data('key', value) data[key] = value; } else { if (massGetter) { // data() return data; } else { if (isSimpleGetter) { // data('key') // don't force creation of expandoStore if it doesn't exist yet return data && data[key]; } else { // mass-setter: data({key1: val1, key2: val2}) extend(data, key); } } } } } function jqLiteHasClass(element, selector) { if (!element.getAttribute) return false; return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " "). indexOf(" " + selector + " ") > -1); } function jqLiteRemoveClass(element, cssClasses) { if (cssClasses && element.setAttribute) { forEach(cssClasses.split(' '), function(cssClass) { element.setAttribute('class', trim( (" " + (element.getAttribute('class') || '') + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ")) ); }); } } function jqLiteAddClass(element, cssClasses) { if (cssClasses && element.setAttribute) { var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') .replace(/[\n\t]/g, " "); forEach(cssClasses.split(' '), function(cssClass) { cssClass = trim(cssClass); if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { existingClasses += cssClass + ' '; } }); element.setAttribute('class', trim(existingClasses)); } } function jqLiteAddNodes(root, elements) { // THIS CODE IS VERY HOT. Don't make changes without benchmarking. if (elements) { // if a Node (the most common case) if (elements.nodeType) { root[root.length++] = elements; } else { var length = elements.length; // if an Array or NodeList and not a Window if (typeof length === 'number' && elements.window !== elements) { if (length) { for (var i = 0; i < length; i++) { root[root.length++] = elements[i]; } } } else { root[root.length++] = elements; } } } } function jqLiteController(element, name) { return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller'); } function jqLiteInheritedData(element, name, value) { // if element is the document object work with the html element instead // this makes $(document).scope() possible if (element.nodeType == NODE_TYPE_DOCUMENT) { element = element.documentElement; } var names = isArray(name) ? name : [name]; while (element) { for (var i = 0, ii = names.length; i < ii; i++) { if ((value = jqLite.data(element, names[i])) !== undefined) return value; } // If dealing with a document fragment node with a host element, and no parent, use the host // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM // to lookup parent controllers. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host); } } function jqLiteEmpty(element) { jqLiteDealoc(element, true); while (element.firstChild) { element.removeChild(element.firstChild); } } function jqLiteRemove(element, keepData) { if (!keepData) jqLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); } function jqLiteDocumentLoaded(action, win) { win = win || window; if (win.document.readyState === 'complete') { // Force the action to be run async for consistent behaviour // from the action's point of view // i.e. it will definitely not be in a $apply win.setTimeout(action); } else { // No need to unbind this handler as load is only ever called once jqLite(win).on('load', action); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } // check if document is already loaded if (document.readyState === 'complete') { setTimeout(trigger); } else { this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. // jshint -W064 JQLite(window).on('load', trigger); // fallback to window.onload for others // jshint +W064 } }, toString: function() { var value = []; forEach(this, function(e) { value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { BOOLEAN_ELEMENTS[value] = true; }); var ALIASED_ATTR = { 'ngMinlength': 'minlength', 'ngMaxlength': 'maxlength', 'ngMin': 'min', 'ngMax': 'max', 'ngPattern': 'pattern' }; function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr; } function getAliasedAttrName(element, name) { var nodeName = element.nodeName; return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name]; } forEach({ data: jqLiteData, removeData: jqLiteRemoveData }, function(fn, name) { JQLite[name] = fn; }); forEach({ data: jqLiteData, inheritedData: jqLiteInheritedData, scope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); }, isolateScope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); }, controller: jqLiteController, injector: function(element) { return jqLiteInheritedData(element, '$injector'); }, removeAttr: function(element, name) { element.removeAttribute(name); }, hasClass: jqLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { return element.style[name]; } }, attr: function(element, name, value) { var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name) || noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: (function() { getText.$dv = ''; return getText; function getText(element, value) { if (isUndefined(value)) { var nodeType = element.nodeType; return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : ''; } element.textContent = value; } })(), val: function(element, value) { if (isUndefined(value)) { if (element.multiple && nodeName_(element) === 'select') { var result = []; forEach(element.options, function(option) { if (option.selected) { result.push(option.value || option.text); } }); return result.length === 0 ? null : result; } return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } jqLiteDealoc(element, true); element.innerHTML = value; }, empty: jqLiteEmpty }, function(fn, name) { /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; var nodeCount = this.length; // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. // jqLiteEmpty takes no arguments but is a setter. if (fn !== jqLiteEmpty && (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for (i = 0; i < nodeCount; i++) { if (fn === jqLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { for (key in arg1) { fn(this[i], key, arg1[key]); } } } // return self for chaining return this; } else { // we are a read, so read the first child. // TODO: do we still need this? var value = fn.$dv; // Only if we have $dv do we iterate over all, otherwise it is just the first element. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount; for (var j = 0; j < jj; j++) { var nodeValue = fn(this[j], arg1, arg2); value = value ? value + nodeValue : nodeValue; } return value; } } else { // we are a write, so apply to all children for (i = 0; i < nodeCount; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } }; }); function createEventHandler(element, events) { var eventHandler = function(event, type) { // jQuery specific api event.isDefaultPrevented = function() { return event.defaultPrevented; }; var eventFns = events[type || event.type]; var eventFnsLength = eventFns ? eventFns.length : 0; if (!eventFnsLength) return; if (isUndefined(event.immediatePropagationStopped)) { var originalStopImmediatePropagation = event.stopImmediatePropagation; event.stopImmediatePropagation = function() { event.immediatePropagationStopped = true; if (event.stopPropagation) { event.stopPropagation(); } if (originalStopImmediatePropagation) { originalStopImmediatePropagation.call(event); } }; } event.isImmediatePropagationStopped = function() { return event.immediatePropagationStopped === true; }; // Copy event handlers in case event handlers array is modified during execution. if ((eventFnsLength > 1)) { eventFns = shallowCopy(eventFns); } for (var i = 0; i < eventFnsLength; i++) { if (!event.isImmediatePropagationStopped()) { eventFns[i].call(element, event); } } }; // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all // events on `element` eventHandler.elem = element; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: jqLiteRemoveData, on: function jqLiteOn(element, type, fn, unsupported) { if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); // Do not add event handlers to non-elements because they will not be cleaned up. if (!jqLiteAcceptsData(element)) { return; } var expandoStore = jqLiteExpandoStore(element, true); var events = expandoStore.events; var handle = expandoStore.handle; if (!handle) { handle = expandoStore.handle = createEventHandler(element, events); } // http://jsperf.com/string-indexof-vs-split var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type]; var i = types.length; while (i--) { type = types[i]; var eventFns = events[type]; if (!eventFns) { events[type] = []; if (type === 'mouseenter' || type === 'mouseleave') { // Refer to jQuery's implementation of mouseenter & mouseleave // Read about mouseenter and mouseleave: // http://www.quirksmode.org/js/events_mouse.html#link8 jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) { var target = this, related = event.relatedTarget; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if (!related || (related !== target && !target.contains(related))) { handle(event, type); } }); } else { if (type !== '$destroy') { addEventListenerFn(element, type, handle); } } eventFns = events[type]; } eventFns.push(fn); } }, off: jqLiteOff, one: function(element, type, fn) { element = jqLite(element); //add the listener twice so that when it is called //you can remove the original function and still be //able to call element.off(ev, fn) normally element.on(type, function onFn() { element.off(type, fn); element.off(type, onFn); }); element.on(type, fn); }, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; jqLiteDealoc(element); forEach(new JQLite(replaceNode), function(node) { if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element) { if (element.nodeType === NODE_TYPE_ELEMENT) children.push(element); }); return children; }, contents: function(element) { return element.contentDocument || element.childNodes || []; }, append: function(element, node) { var nodeType = element.nodeType; if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return; node = new JQLite(node); for (var i = 0, ii = node.length; i < ii; i++) { var child = node[i]; element.appendChild(child); } }, prepend: function(element, node) { if (element.nodeType === NODE_TYPE_ELEMENT) { var index = element.firstChild; forEach(new JQLite(node), function(child) { element.insertBefore(child, index); }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode).eq(0).clone()[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: jqLiteRemove, detach: function(element) { jqLiteRemove(element, true); }, after: function(element, newElement) { var index = element, parent = element.parentNode; newElement = new JQLite(newElement); for (var i = 0, ii = newElement.length; i < ii; i++) { var node = newElement[i]; parent.insertBefore(node, index.nextSibling); index = node; } }, addClass: jqLiteAddClass, removeClass: jqLiteRemoveClass, toggleClass: function(element, selector, condition) { if (selector) { forEach(selector.split(' '), function(className) { var classCondition = condition; if (isUndefined(classCondition)) { classCondition = !jqLiteHasClass(element, className); } (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className); }); } }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null; }, next: function(element) { return element.nextElementSibling; }, find: function(element, selector) { if (element.getElementsByTagName) { return element.getElementsByTagName(selector); } else { return []; } }, clone: jqLiteClone, triggerHandler: function(element, event, extraParameters) { var dummyEvent, eventFnsCopy, handlerArgs; var eventName = event.type || event; var expandoStore = jqLiteExpandoStore(element); var events = expandoStore && expandoStore.events; var eventFns = events && events[eventName]; if (eventFns) { // Create a dummy event to pass to the handlers dummyEvent = { preventDefault: function() { this.defaultPrevented = true; }, isDefaultPrevented: function() { return this.defaultPrevented === true; }, stopImmediatePropagation: function() { this.immediatePropagationStopped = true; }, isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; }, stopPropagation: noop, type: eventName, target: element }; // If a custom event was provided then extend our dummy event with it if (event.type) { dummyEvent = extend(dummyEvent, event); } // Copy event handlers in case event handlers array is modified during execution. eventFnsCopy = shallowCopy(eventFns); handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; forEach(eventFnsCopy, function(fn) { if (!dummyEvent.isImmediatePropagationStopped()) { fn.apply(element, handlerArgs); } }); } } }, function(fn, name) { /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2, arg3) { var value; for (var i = 0, ii = this.length; i < ii; i++) { if (isUndefined(value)) { value = fn(this[i], arg1, arg2, arg3); if (isDefined(value)) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); } } return isDefined(value) ? value : this; }; // bind legacy bind/unbind to on/off JQLite.prototype.bind = JQLite.prototype.on; JQLite.prototype.unbind = JQLite.prototype.off; }); /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj, nextUidFn) { var key = obj && obj.$$hashKey; if (key) { if (typeof key === 'function') { key = obj.$$hashKey(); } return key; } var objType = typeof obj; if (objType == 'function' || (objType == 'object' && obj !== null)) { key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)(); } else { key = objType + ':' + obj; } return key; } /** * HashMap which can use objects as keys */ function HashMap(array, isolatedUid) { if (isolatedUid) { var uid = 0; this.nextUid = function() { return ++uid; }; } forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key, this.nextUid)] = value; }, /** * @param key * @returns {Object} the value for the key */ get: function(key) { return this[hashKey(key, this.nextUid)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key, this.nextUid)]; delete this[key]; return value; } }; /** * @ngdoc function * @module ng * @name angular.injector * @kind function * * @description * Creates an injector object that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which * disallows argument name annotation inference. * @returns {injector} Injector object. See {@link auto.$injector $injector}. * * @example * Typical usage * ```js * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document) { * $compile($document)($rootScope); * $rootScope.$digest(); * }); * ``` * * Sometimes you want to get access to the injector of a currently running Angular app * from outside Angular. Perhaps, you want to inject and compile some markup after the * application has been bootstrapped. You can do this using the extra `injector()` added * to JQuery/jqLite elements. See {@link angular.element}. * * *This is fairly rare but could be the case if a third party library is injecting the * markup.* * * In the following example a new block of HTML containing a `ng-controller` * directive is added to the end of the document body by JQuery. We then compile and link * it into the current AngularJS scope. * * ```js * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); * $(document.body).append($div); * * angular.element(document).injector().invoke(function($compile) { * var scope = angular.element($div).scope(); * $compile($div)(scope); * }); * ``` */ /** * @ngdoc module * @name auto * @description * * Implicit module which gets automatically added to each {@link auto.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var $injectorMinErr = minErr('$injector'); function anonFn(fn) { // For anonymous functions, showing at the very least the function signature can help in // debugging. var fnText = fn.toString().replace(STRIP_COMMENTS, ''), args = fnText.match(FN_ARGS); if (args) { return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; } return 'fn'; } function annotate(fn, strictDi, name) { var $inject, fnText, argDecl, last; if (typeof fn === 'function') { if (!($inject = fn.$inject)) { $inject = []; if (fn.length) { if (strictDi) { if (!isString(name) || !name) { name = fn.name || anonFn(fn); } throw $injectorMinErr('strictdi', '{0} is not using explicit annotation and cannot be invoked in strict mode', name); } fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { arg.replace(FN_ARG, function(all, underscore, name) { $inject.push(name); }); }); } fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn'); $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc service * @name $injector * * @description * * `$injector` is used to retrieve object instances as defined by * {@link auto.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * ```js * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector) { * return $injector; * })).toBe($injector); * ``` * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. * * ```js * // inferred (only works if code not minified/obfuscated) * $injector.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $injector.invoke(explicit); * * // inline * $injector.invoke(['serviceA', function(serviceA){}]); * ``` * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition * can then be parsed and the function arguments can be extracted. This method of discovering * annotations is disallowed when the injector is in strict mode. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the * argument names. * * ## `$inject` Annotation * By adding an `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name $injector#get * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name $injector#invoke * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!Function} fn The function to invoke. Function parameters are injected according to the * {@link guide/di $inject Annotation} rules. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name $injector#has * * @description * Allows the user to query if the particular service exists. * * @param {string} name Name of the service to query. * @returns {boolean} `true` if injector has given service. */ /** * @ngdoc method * @name $injector#instantiate * @description * Create a new instance of JS type. The method takes a constructor function, invokes the new * operator, and supplies all of the arguments to the constructor function as specified by the * constructor annotation. * * @param {Function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name $injector#annotate * * @description * Returns an array of service names which the function is requesting for injection. This API is * used by the injector to determine which services need to be injected into the function when the * function is invoked. There are three ways in which the function can be annotated with the needed * dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done * by converting the function into a string using `toString()` method and extracting the argument * names. * ```js * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * You can disallow this method by using strict injection mode. * * This method does not work with code minification / obfuscation. For this reason the following * annotation strategies are supported. * * # The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings * represent names of services to be injected into the function. * ```js * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController['$inject'] = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property * is very inconvenient. In these situations using the array notation to specify the dependencies in * a way that survives minification is a better choice: * * ```js * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tmpFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * ``` * * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to * be retrieved as described above. * * @param {boolean=} [strictDi=false] Disallow argument name annotation inference. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc service * @name $provide * * @description * * The {@link auto.$provide $provide} service has a number of methods for registering components * with the {@link auto.$injector $injector}. Many of these functions are also exposed on * {@link angular.Module}. * * An Angular **service** is a singleton object created by a **service factory**. These **service * factories** are functions which, in turn, are created by a **service provider**. * The **service providers** are constructor functions. When instantiated they must contain a * property called `$get`, which holds the **service factory** function. * * When you request a service, the {@link auto.$injector $injector} is responsible for finding the * correct **service provider**, instantiating it and then calling its `$get` **service factory** * function to get the instance of the **service**. * * Often services have no configuration options and there is no need to add methods to the service * provider. The provider will be no more than a constructor function with a `$get` property. For * these cases the {@link auto.$provide $provide} service has additional helper methods to register * services without specifying a provider. * * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the * {@link auto.$injector $injector} * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by * providers and services. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by * services, not providers. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, * that will be wrapped in a **service provider** object, whose `$get` property will contain the * given factory function. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` * that will be wrapped in a **service provider** object, whose `$get` property will instantiate * a new object using the given constructor function. * * See the individual methods for more information and examples. */ /** * @ngdoc method * @name $provide#provider * @description * * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions * are constructor functions, whose instances are responsible for "providing" a factory for a * service. * * Service provider names start with the name of the service they provide followed by `Provider`. * For example, the {@link ng.$log $log} service has a provider called * {@link ng.$logProvider $logProvider}. * * Service provider objects can have additional methods which allow configuration of the provider * and its service. Importantly, you can configure what kind of service is created by the `$get` * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a * method {@link ng.$logProvider#debugEnabled debugEnabled} * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the * console or not. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance * @example * * The following example shows how to create a simple event tracking service and register it using * {@link auto.$provide#provider $provide.provider()}. * * ```js * // Define the eventTracker provider * function EventTrackerProvider() { * var trackingUrl = '/track'; * * // A provider method for configuring where the tracked events should been saved * this.setTrackingUrl = function(url) { * trackingUrl = url; * }; * * // The service factory function * this.$get = ['$http', function($http) { * var trackedEvents = {}; * return { * // Call this to track an event * event: function(event) { * var count = trackedEvents[event] || 0; * count += 1; * trackedEvents[event] = count; * return count; * }, * // Call this to save the tracked events to the trackingUrl * save: function() { * $http.post(trackingUrl, trackedEvents); * } * }; * }]; * } * * describe('eventTracker', function() { * var postSpy; * * beforeEach(module(function($provide) { * // Register the eventTracker provider * $provide.provider('eventTracker', EventTrackerProvider); * })); * * beforeEach(module(function(eventTrackerProvider) { * // Configure eventTracker provider * eventTrackerProvider.setTrackingUrl('/custom-track'); * })); * * it('tracks events', inject(function(eventTracker) { * expect(eventTracker.event('login')).toEqual(1); * expect(eventTracker.event('login')).toEqual(2); * })); * * it('saves to the tracking url', inject(function(eventTracker, $http) { * postSpy = spyOn($http, 'post'); * eventTracker.event('login'); * eventTracker.save(); * expect(postSpy).toHaveBeenCalled(); * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); * })); * }); * ``` */ /** * @ngdoc method * @name $provide#factory * @description * * Register a **service factory**, which will be called to return the service instance. * This is short for registering a service where its provider consists of only a `$get` property, * which is the given service factory function. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to * configure your service in a provider. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand * for `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service * ```js * $provide.factory('ping', ['$http', function($http) { * return function ping() { * return $http.send('/ping'); * }; * }]); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping(); * }]); * ``` */ /** * @ngdoc method * @name $provide#service * @description * * Register a **service constructor**, which will be invoked with `new` to create the service * instance. * This is short for registering a service where its provider's `$get` property is the service * constructor function that will be used to instantiate the service instance. * * You should use {@link auto.$provide#service $provide.service(class)} if you define your service * as a type/class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service using * {@link auto.$provide#service $provide.service(class)}. * ```js * var Ping = function($http) { * this.$http = $http; * }; * * Ping.$inject = ['$http']; * * Ping.prototype.send = function() { * return this.$http.get('/ping'); * }; * $provide.service('ping', Ping); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping.send(); * }]); * ``` */ /** * @ngdoc method * @name $provide#value * @description * * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a * number, an array, an object or a function. This is short for registering a service where its * provider's `$get` property is a factory function that takes no arguments and returns the **value * service**. * * Value services are similar to constant services, except that they cannot be injected into a * module configuration function (see {@link angular.Module#config}) but they can be overridden by * an Angular * {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance * * @example * Here are some examples of creating value services. * ```js * $provide.value('ADMIN_USER', 'admin'); * * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); * * $provide.value('halfOf', function(value) { * return value / 2; * }); * ``` */ /** * @ngdoc method * @name $provide#constant * @description * * Register a **constant service**, such as a string, a number, an array, an object or a function, * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be * injected into a module configuration function (see {@link angular.Module#config}) and it cannot * be overridden by an Angular {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance * * @example * Here a some examples of creating constants: * ```js * $provide.constant('SHARD_HEIGHT', 306); * * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); * * $provide.constant('double', function(value) { * return value * 2; * }); * ``` */ /** * @ngdoc method * @name $provide#decorator * @description * * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator * intercepts the creation of a service, allowing it to override or modify the behaviour of the * service. The object returned by the decorator may be the original service, or a new service * object which replaces or wraps and delegates to the original service. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instantiated and should return the decorated service instance. The function is called using * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. * Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. * * @example * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting * calls to {@link ng.$log#error $log.warn()}. * ```js * $provide.decorator('$log', ['$delegate', function($delegate) { * $delegate.warn = $delegate.error; * return $delegate; * }]); * ``` */ function createInjector(modulesToLoad, strictDi) { strictDi = (strictDi === true); var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap([], true), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function() { throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); })), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider, undefined, servicename); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } }; } function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_; } function enforceReturnValue(name, factory) { return function enforcedReturnValue() { var result = instanceInjector.invoke(factory, this, undefined, name); if (isUndefined(result)) { throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name); } return result; }; } function factory(name, factoryFn, enforce) { return provider(name, { $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, val) { return factory(name, valueFn(val), false); } function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad) { var runBlocks = [], moduleFn; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); function runInvokeQueue(queue) { var i, ii; for (i = 0, ii = queue.length; i < ii; i++) { var invokeArgs = queue[i], provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } try { if (isString(module)) { moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); runInvokeQueue(moduleFn._invokeQueue); runInvokeQueue(moduleFn._configBlocks); } else if (isFunction(module)) { runBlocks.push(providerInjector.invoke(module)); } else if (isArray(module)) { runBlocks.push(providerInjector.invoke(module)); } else { assertArgFn(module, 'module'); } } catch (e) { if (isArray(module)) { module = module[module.length - 1]; } if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { // Safari & FF's stack traces don't contain error.message content // unlike those of Chrome and IE // So if stack doesn't contain message, we create a new string that contains both. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. /* jshint -W022 */ e = e.message + '\n' + e.stack; } throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", module, e.stack || e.message || e); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw $injectorMinErr('cdep', 'Circular dependency found: {0}', serviceName + ' <- ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } catch (err) { if (cache[serviceName] === INSTANTIATING) { delete cache[serviceName]; } throw err; } finally { path.shift(); } } } function invoke(fn, self, locals, serviceName) { if (typeof locals === 'string') { serviceName = locals; locals = null; } var args = [], $inject = annotate(fn, strictDi, serviceName), length, i, key; for (i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; if (typeof key !== 'string') { throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); } args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key) ); } if (isArray(fn)) { fn = fn[length]; } // http://jsperf.com/angularjs-invoke-apply-vs-switch // #5388 return fn.apply(self, args); } function instantiate(Type, locals, serviceName) { // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); // Object creation: http://jsperf.com/create-constructor/2 var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype); var returnedValue = invoke(Type, instance, locals, serviceName); return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } }; } } createInjector.$$annotate = annotate; /** * @ngdoc provider * @name $anchorScrollProvider * * @description * Use `$anchorScrollProvider` to disable automatic scrolling whenever * {@link ng.$location#hash $location.hash()} changes. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; /** * @ngdoc method * @name $anchorScrollProvider#disableAutoScrolling * * @description * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br /> * Use this method to disable automatic scrolling. * * If automatic scrolling is disabled, one must explicitly call * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the * current hash. */ this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; /** * @ngdoc service * @name $anchorScroll * @kind function * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and * scrolls to the related element, according to the rules specified in the * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document). * * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to * match any anchor whenever it changes. This can be disabled by calling * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}. * * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a * vertical scroll-offset (either fixed or dynamic). * * @property {(number|function|jqLite)} yOffset * If set, specifies a vertical scroll-offset. This is often useful when there are fixed * positioned elements at the top of the page, such as navbars, headers etc. * * `yOffset` can be specified in various ways: * - **number**: A fixed number of pixels to be used as offset.<br /><br /> * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return * a number representing the offset (in pixels).<br /><br /> * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from * the top of the page to the element's bottom will be used as offset.<br /> * **Note**: The element will be taken into account only as long as its `position` is set to * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust * their height and/or positioning according to the viewport's size. * * <br /> * <div class="alert alert-warning"> * In order for `yOffset` to work properly, scrolling should take place on the document's root and * not some child element. * </div> * * @example <example module="anchorScrollExample"> <file name="index.html"> <div id="scrollArea" ng-controller="ScrollController"> <a ng-click="gotoBottom()">Go to bottom</a> <a id="bottom"></a> You're at the bottom! </div> </file> <file name="script.js"> angular.module('anchorScrollExample', []) .controller('ScrollController', ['$scope', '$location', '$anchorScroll', function ($scope, $location, $anchorScroll) { $scope.gotoBottom = function() { // set the location.hash to the id of // the element you wish to scroll to. $location.hash('bottom'); // call $anchorScroll() $anchorScroll(); }; }]); </file> <file name="style.css"> #scrollArea { height: 280px; overflow: auto; } #bottom { display: block; margin-top: 2000px; } </file> </example> * * <hr /> * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value). * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details. * * @example <example module="anchorScrollOffsetExample"> <file name="index.html"> <div class="fixed-header" ng-controller="headerCtrl"> <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]"> Go to anchor {{x}} </a> </div> <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]"> Anchor {{x}} of 5 </div> </file> <file name="script.js"> angular.module('anchorScrollOffsetExample', []) .run(['$anchorScroll', function($anchorScroll) { $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels }]) .controller('headerCtrl', ['$anchorScroll', '$location', '$scope', function ($anchorScroll, $location, $scope) { $scope.gotoAnchor = function(x) { var newHash = 'anchor' + x; if ($location.hash() !== newHash) { // set the $location.hash to `newHash` and // $anchorScroll will automatically scroll to it $location.hash('anchor' + x); } else { // call $anchorScroll() explicitly, // since $location.hash hasn't changed $anchorScroll(); } }; } ]); </file> <file name="style.css"> body { padding-top: 50px; } .anchor { border: 2px dashed DarkOrchid; padding: 10px 10px 200px 10px; } .fixed-header { background-color: rgba(0, 0, 0, 0.2); height: 50px; position: fixed; top: 0; left: 0; right: 0; } .fixed-header > a { display: inline-block; margin: 5px 15px; } </file> </example> */ this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // Helper function to get first anchor from a NodeList // (using `Array#some()` instead of `angular#forEach()` since it's more performant // and working in all supported browsers.) function getFirstAnchor(list) { var result = null; Array.prototype.some.call(list, function(element) { if (nodeName_(element) === 'a') { result = element; return true; } }); return result; } function getYOffset() { var offset = scroll.yOffset; if (isFunction(offset)) { offset = offset(); } else if (isElement(offset)) { var elem = offset[0]; var style = $window.getComputedStyle(elem); if (style.position !== 'fixed') { offset = 0; } else { offset = elem.getBoundingClientRect().bottom; } } else if (!isNumber(offset)) { offset = 0; } return offset; } function scrollTo(elem) { if (elem) { elem.scrollIntoView(); var offset = getYOffset(); if (offset) { // `offset` is the number of pixels we should scroll UP in order to align `elem` properly. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the // top of the viewport. // // IF the number of pixels from the top of `elem` to the end of the page's content is less // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some // way down the page. // // This is often the case for elements near the bottom of the page. // // In such cases we do not need to scroll the whole `offset` up, just the difference between // the top of the element and the offset, which is enough to align the top of `elem` at the // desired position. var elemTop = elem.getBoundingClientRect().top; $window.scrollBy(0, elemTop - offset); } } else { $window.scrollTo(0, 0); } } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) scrollTo(null); // element with given id else if ((elm = document.getElementById(hash))) scrollTo(elm); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') scrollTo(null); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $location.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, function autoScrollWatchAction(newVal, oldVal) { // skip the initial scroll if $location.hash is empty if (newVal === oldVal && newVal === '') return; jqLiteDocumentLoaded(function() { $rootScope.$evalAsync(scroll); }); }); } return scroll; }]; } var $animateMinErr = minErr('$animate'); /** * @ngdoc provider * @name $animateProvider * * @description * Default implementation of $animate that doesn't perform any animations, instead just * synchronously performs DOM * updates and calls done() callbacks. * * In order to enable animations the ngAnimate module has to be loaded. * * To see the functional implementation check out src/ngAnimate/animate.js */ var $AnimateProvider = ['$provide', function($provide) { this.$$selectors = {}; /** * @ngdoc method * @name $animateProvider#register * * @description * Registers a new injectable animation factory function. The factory function produces the * animation object which contains callback functions for each event that is expected to be * animated. * * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` * must be called once the element animation is complete. If a function is returned then the * animation service will use this function to cancel the animation whenever a cancel event is * triggered. * * * ```js * return { * eventFn : function(element, done) { * //code to run the animation * //once complete, then run done() * return function cancellationFunction() { * //code to cancel the animation * } * } * } * ``` * * @param {string} name The name of the animation. * @param {Function} factory The factory function that will be executed to return the animation * object. */ this.register = function(name, factory) { var key = name + '-animation'; if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name); this.$$selectors[name.substr(1)] = key; $provide.factory(key, factory); }; /** * @ngdoc method * @name $animateProvider#classNameFilter * * @description * Sets and/or returns the CSS class regular expression that is checked when performing * an animation. Upon bootstrap the classNameFilter value is not set at all and will * therefore enable $animate to attempt to perform an animation on any element. * When setting the classNameFilter value, animations will only be performed on elements * that successfully match the filter expression. This in turn can boost performance * for low-powered devices as well as applications containing a lot of structural operations. * @param {RegExp=} expression The className expression which will be checked against all animations * @return {RegExp} The current CSS className expression value. If null then there is no expression value */ this.classNameFilter = function(expression) { if (arguments.length === 1) { this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; } return this.$$classNameFilter; }; this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) { var currentDefer; function runAnimationPostDigest(fn) { var cancelFn, defer = $$q.defer(); defer.promise.$$cancelFn = function ngAnimateMaybeCancel() { cancelFn && cancelFn(); }; $rootScope.$$postDigest(function ngAnimatePostDigest() { cancelFn = fn(function ngAnimateNotifyComplete() { defer.resolve(); }); }); return defer.promise; } function resolveElementClasses(element, classes) { var toAdd = [], toRemove = []; var hasClasses = createMap(); forEach((element.attr('class') || '').split(/\s+/), function(className) { hasClasses[className] = true; }); forEach(classes, function(status, className) { var hasClass = hasClasses[className]; // If the most recent class manipulation (via $animate) was to remove the class, and the // element currently has the class, the class is scheduled for removal. Otherwise, if // the most recent class manipulation (via $animate) was to add the class, and the // element does not currently have the class, the class is scheduled to be added. if (status === false && hasClass) { toRemove.push(className); } else if (status === true && !hasClass) { toAdd.push(className); } }); return (toAdd.length + toRemove.length) > 0 && [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null]; } function cachedClassManipulation(cache, classes, op) { for (var i=0, ii = classes.length; i < ii; ++i) { var className = classes[i]; cache[className] = op; } } function asyncPromise() { // only serve one instance of a promise in order to save CPU cycles if (!currentDefer) { currentDefer = $$q.defer(); $$asyncCallback(function() { currentDefer.resolve(); currentDefer = null; }); } return currentDefer.promise; } function applyStyles(element, options) { if (angular.isObject(options)) { var styles = extend(options.from || {}, options.to || {}); element.css(styles); } } /** * * @ngdoc service * @name $animate * @description The $animate service provides rudimentary DOM manipulation functions to * insert, remove and move elements within the DOM, as well as adding and removing classes. * This service is the core service used by the ngAnimate $animator service which provides * high-level animation hooks for CSS and JavaScript. * * $animate is available in the AngularJS core, however, the ngAnimate module must be included * to enable full out animation support. Otherwise, $animate will only perform simple DOM * manipulation operations. * * To learn more about enabling animation support, click here to visit the {@link ngAnimate * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service * page}. */ return { animate: function(element, from, to) { applyStyles(element, { from: from, to: to }); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#enter * @kind function * @description Inserts the element into the DOM either after the `after` element or * as the first child within the `parent` element. When the function is called a promise * is returned that will be resolved at a later time. * @param {DOMElement} element the element which will be inserted into the DOM * @param {DOMElement} parent the parent element which will append the element as * a child (if the after element is not present) * @param {DOMElement} after the sibling element which will append the element * after itself * @param {object=} options an optional collection of styles that will be applied to the element. * @return {Promise} the animation callback promise */ enter: function(element, parent, after, options) { applyStyles(element, options); after ? after.after(element) : parent.prepend(element); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#leave * @kind function * @description Removes the element from the DOM. When the function is called a promise * is returned that will be resolved at a later time. * @param {DOMElement} element the element which will be removed from the DOM * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ leave: function(element, options) { element.remove(); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#move * @kind function * @description Moves the position of the provided element within the DOM to be placed * either after the `after` element or inside of the `parent` element. When the function * is called a promise is returned that will be resolved at a later time. * * @param {DOMElement} element the element which will be moved around within the * DOM * @param {DOMElement} parent the parent element where the element will be * inserted into (if the after element is not present) * @param {DOMElement} after the sibling element where the element will be * positioned next to * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ move: function(element, parent, after, options) { // Do not remove element before insert. Removing will cause data associated with the // element to be dropped. Insert will implicitly do the remove. return this.enter(element, parent, after, options); }, /** * * @ngdoc method * @name $animate#addClass * @kind function * @description Adds the provided className CSS class value to the provided element. * When the function is called a promise is returned that will be resolved at a later time. * @param {DOMElement} element the element which will have the className value * added to it * @param {string} className the CSS class which will be added to the element * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ addClass: function(element, className, options) { return this.setClass(element, className, [], options); }, $$addClassImmediately: function(element, className, options) { element = jqLite(element); className = !isString(className) ? (isArray(className) ? className.join(' ') : '') : className; forEach(element, function(element) { jqLiteAddClass(element, className); }); applyStyles(element, options); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#removeClass * @kind function * @description Removes the provided className CSS class value from the provided element. * When the function is called a promise is returned that will be resolved at a later time. * @param {DOMElement} element the element which will have the className value * removed from it * @param {string} className the CSS class which will be removed from the element * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ removeClass: function(element, className, options) { return this.setClass(element, [], className, options); }, $$removeClassImmediately: function(element, className, options) { element = jqLite(element); className = !isString(className) ? (isArray(className) ? className.join(' ') : '') : className; forEach(element, function(element) { jqLiteRemoveClass(element, className); }); applyStyles(element, options); return asyncPromise(); }, /** * * @ngdoc method * @name $animate#setClass * @kind function * @description Adds and/or removes the given CSS classes to and from the element. * When the function is called a promise is returned that will be resolved at a later time. * @param {DOMElement} element the element which will have its CSS classes changed * removed from it * @param {string} add the CSS classes which will be added to the element * @param {string} remove the CSS class which will be removed from the element * @param {object=} options an optional collection of options that will be applied to the element. * @return {Promise} the animation callback promise */ setClass: function(element, add, remove, options) { var self = this; var STORAGE_KEY = '$$animateClasses'; var createdCache = false; element = jqLite(element); var cache = element.data(STORAGE_KEY); if (!cache) { cache = { classes: {}, options: options }; createdCache = true; } else if (options && cache.options) { cache.options = angular.extend(cache.options || {}, options); } var classes = cache.classes; add = isArray(add) ? add : add.split(' '); remove = isArray(remove) ? remove : remove.split(' '); cachedClassManipulation(classes, add, true); cachedClassManipulation(classes, remove, false); if (createdCache) { cache.promise = runAnimationPostDigest(function(done) { var cache = element.data(STORAGE_KEY); element.removeData(STORAGE_KEY); // in the event that the element is removed before postDigest // is run then the cache will be undefined and there will be // no need anymore to add or remove and of the element classes if (cache) { var classes = resolveElementClasses(element, cache.classes); if (classes) { self.$$setClassImmediately(element, classes[0], classes[1], cache.options); } } done(); }); element.data(STORAGE_KEY, cache); } return cache.promise; }, $$setClassImmediately: function(element, add, remove, options) { add && this.$$addClassImmediately(element, add); remove && this.$$removeClassImmediately(element, remove); applyStyles(element, options); return asyncPromise(); }, enabled: noop, cancel: noop }; }]; }]; function $$AsyncCallbackProvider() { this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) { return $$rAF.supported ? function(fn) { return $$rAF(fn); } : function(fn) { return $timeout(fn, 0, false); }; }]; } /* global stripHash: true */ /** * ! This is a private undocumented service ! * * @name $browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {object} $log window.console or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while (outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn) { pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @name $browser#addPollFn * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn) { pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var cachedState, lastHistoryState, lastBrowserUrl = location.href, baseElement = document.find('base'), reloadLocation = null; cacheState(); lastHistoryState = cachedState; /** * @name $browser#url * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record? * @param {object=} state object to use with pushState/replaceState */ self.url = function(url, replace, state) { // In modern browsers `history.state` is `null` by default; treating it separately // from `undefined` would cause `$browser.url('/foo')` to change `history.state` // to undefined via `pushState`. Instead, let's change `undefined` to `null` here. if (isUndefined(state)) { state = null; } // Android Browser BFCache causes location, history reference to become stale. if (location !== window.location) location = window.location; if (history !== window.history) history = window.history; // setter if (url) { var sameState = lastHistoryState === state; // Don't change anything if previous and current URLs and states match. This also prevents // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode. // See https://github.com/angular/angular.js/commit/ffb2701 if (lastBrowserUrl === url && (!$sniffer.history || sameState)) { return self; } var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); lastBrowserUrl = url; lastHistoryState = state; // Don't use history API if only the hash changed // due to a bug in IE10/IE11 which leads // to not firing a `hashchange` nor `popstate` event // in some cases (see #9143). if ($sniffer.history && (!sameBase || !sameState)) { history[replace ? 'replaceState' : 'pushState'](state, '', url); cacheState(); // Do the assignment again so that those two variables are referentially identical. lastHistoryState = cachedState; } else { if (!sameBase) { reloadLocation = url; } if (replace) { location.replace(url); } else { location.href = url; } } return self; // getter } else { // - reloadLocation is needed as browsers don't allow to read out // the new location.href if a reload happened. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return reloadLocation || location.href.replace(/%27/g,"'"); } }; /** * @name $browser#state * * @description * This method is a getter. * * Return history.state or null if history.state is undefined. * * @returns {object} state */ self.state = function() { return cachedState; }; var urlChangeListeners = [], urlChangeInit = false; function cacheStateAndFireUrlChange() { cacheState(); fireUrlChange(); } // This variable should be used *only* inside the cacheState function. var lastCachedState = null; function cacheState() { // This should be the only place in $browser where `history.state` is read. cachedState = window.history.state; cachedState = isUndefined(cachedState) ? null : cachedState; // Prevent callbacks fo fire twice if both hashchange & popstate were fired. if (equals(cachedState, lastCachedState)) { cachedState = lastCachedState; } lastCachedState = cachedState; } function fireUrlChange() { if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) { return; } lastBrowserUrl = self.url(); lastHistoryState = cachedState; forEach(urlChangeListeners, function(listener) { listener(self.url(), cachedState); }); } /** * @name $browser#onUrlChange * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed from outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { // TODO(vojta): refactor to use node's syntax for events if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange); // hashchange event jqLite(window).on('hashchange', cacheStateAndFireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; /** * Checks whether the url has changed outside of Angular. * Needs to be exported to be able to check for changes that have been done in sync, * as hashchange/popstate events fire in async. */ self.$$checkUrlChange = fireUrlChange; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * @name $browser#baseHref * * @description * Returns current <base href> * (always relative - without domain) * * @returns {string} The current base href */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); function safeDecodeURIComponent(str) { try { return decodeURIComponent(str); } catch (e) { return str; } } /** * @name $browser#cookies * * @param {string=} name Cookie name * @param {string=} value Cookie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify * it * - cookies(name, value) -> set name to value, if value is undefined delete the cookie * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that * way) * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';path=' + cookiePath).length + 1; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if (cookieLength > 4096) { $log.warn("Cookie '" + name + "' possibly not set or overflowed because it was too large (" + cookieLength + " > 4096 bytes)!"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies name = safeDecodeURIComponent(cookie.substring(0, index)); // the first value that is seen for a cookie is the most // specific one. values for the same cookie name that // follow are for less specific paths. if (lastCookies[name] === undefined) { lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1)); } } } } return lastCookies; } }; /** * @name $browser#defer * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchronously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * @name $browser#defer.cancel * * @description * Cancels a deferred task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider() { this.$get = ['$window', '$log', '$sniffer', '$document', function($window, $log, $sniffer, $document) { return new Browser($window, $document, $log, $sniffer); }]; } /** * @ngdoc service * @name $cacheFactory * * @description * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to * them. * * ```js * * var cache = $cacheFactory('cacheId'); * expect($cacheFactory.get('cacheId')).toBe(cache); * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); * * cache.put("key", "value"); * cache.put("another key", "another value"); * * // We've specified no options on creation * expect(cache.info()).toEqual({id: 'cacheId', size: 2}); * * ``` * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns * it. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. * - `{void}` `removeAll()` — Removes all cached values. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. * * @example <example module="cacheExampleApp"> <file name="index.html"> <div ng-controller="CacheController"> <input ng-model="newCacheKey" placeholder="Key"> <input ng-model="newCacheValue" placeholder="Value"> <button ng-click="put(newCacheKey, newCacheValue)">Cache</button> <p ng-if="keys.length">Cached Values</p> <div ng-repeat="key in keys"> <span ng-bind="key"></span> <span>: </span> <b ng-bind="cache.get(key)"></b> </div> <p>Cache Info</p> <div ng-repeat="(key, value) in cache.info()"> <span ng-bind="key"></span> <span>: </span> <b ng-bind="value"></b> </div> </div> </file> <file name="script.js"> angular.module('cacheExampleApp', []). controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) { $scope.keys = []; $scope.cache = $cacheFactory('cacheId'); $scope.put = function(key, value) { if ($scope.cache.get(key) === undefined) { $scope.keys.push(key); } $scope.cache.put(key, value === undefined ? null : value); }; }]); </file> <file name="style.css"> p { margin: 10px 0 3px; } </file> </example> */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; /** * @ngdoc type * @name $cacheFactory.Cache * * @description * A cache object used to store and retrieve data, primarily used by * {@link $http $http} and the {@link ng.directive:script script} directive to cache * templates and other data. * * ```js * angular.module('superCache') * .factory('superCache', ['$cacheFactory', function($cacheFactory) { * return $cacheFactory('super-cache'); * }]); * ``` * * Example test: * * ```js * it('should behave like a cache', inject(function(superCache) { * superCache.put('key', 'value'); * superCache.put('another key', 'another value'); * * expect(superCache.info()).toEqual({ * id: 'super-cache', * size: 2 * }); * * superCache.remove('another key'); * expect(superCache.get('another key')).toBeUndefined(); * * superCache.removeAll(); * expect(superCache.info()).toEqual({ * id: 'super-cache', * size: 0 * }); * })); * ``` */ return caches[cacheId] = { /** * @ngdoc method * @name $cacheFactory.Cache#put * @kind function * * @description * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be * retrieved later, and incrementing the size of the cache if the key was not already * present in the cache. If behaving like an LRU cache, it will also remove stale * entries from the set. * * It will not insert undefined values into the cache. * * @param {string} key the key under which the cached data is stored. * @param {*} value the value to store alongside the key. If it is undefined, the key * will not be stored. * @returns {*} the value stored. */ put: function(key, value) { if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); } if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } return value; }, /** * @ngdoc method * @name $cacheFactory.Cache#get * @kind function * * @description * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. * * @param {string} key the key of the data to be retrieved * @returns {*} the value stored. */ get: function(key) { if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); } return data[key]; }, /** * @ngdoc method * @name $cacheFactory.Cache#remove * @kind function * * @description * Removes an entry from the {@link $cacheFactory.Cache Cache} object. * * @param {string} key the key of the entry to be removed */ remove: function(key) { if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key]; if (!lruEntry) return; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; } delete data[key]; size--; }, /** * @ngdoc method * @name $cacheFactory.Cache#removeAll * @kind function * * @description * Clears the cache object of any entries. */ removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, /** * @ngdoc method * @name $cacheFactory.Cache#destroy * @kind function * * @description * Destroys the {@link $cacheFactory.Cache Cache} object entirely, * removing it from the {@link $cacheFactory $cacheFactory} set. */ destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, /** * @ngdoc method * @name $cacheFactory.Cache#info * @kind function * * @description * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. * * @returns {object} an object with the following properties: * <ul> * <li>**id**: the id of the cache instance</li> * <li>**size**: the number of entries kept in the cache instance</li> * <li>**...**: any additional properties from the options object when creating the * cache.</li> * </ul> */ info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } /** * @ngdoc method * @name $cacheFactory#info * * @description * Get information about all the caches that have been created * * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` */ cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; /** * @ngdoc method * @name $cacheFactory#get * * @description * Get access to a cache object by the `cacheId` used when it was created. * * @param {string} cacheId Name or id of a cache to access. * @returns {object} Cache object identified by the cacheId or undefined if no such cache. */ cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } /** * @ngdoc service * @name $templateCache * * @description * The first time a template is used, it is loaded in the template cache for quick retrieval. You * can load templates directly into the cache in a `script` tag, or by consuming the * `$templateCache` service directly. * * Adding via the `script` tag: * * ```html * <script type="text/ng-template" id="templateId.html"> * <p>This is the content of the template</p> * </script> * ``` * * **Note:** the `script` tag containing the template does not need to be included in the `head` of * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE, * element with ng-app attribute), otherwise the template will be ignored. * * Adding via the $templateCache service: * * ```js * var myApp = angular.module('myApp', []); * myApp.run(function($templateCache) { * $templateCache.put('templateId.html', 'This is the content of the template'); * }); * ``` * * To retrieve the template later, simply use it in your HTML: * ```html * <div ng-include=" 'templateId.html' "></div> * ``` * * or get it via Javascript: * ```js * $templateCache.get('templateId.html') * ``` * * See {@link ng.$cacheFactory $cacheFactory}. * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: * * - "node" - DOM Node * - "element" - DOM Element or Node * - "$node" or "$element" - jqLite-wrapped node or element * * * Compiler related stuff: * * - "linkFn" - linking fn of a single directive * - "nodeLinkFn" - function that aggregates all linking fns for a particular node * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) */ /** * @ngdoc service * @name $compile * @kind function * * @description * Compiles an HTML string or DOM into a template and produces a template function, which * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. * * The compilation is a process of walking the DOM tree and matching DOM elements to * {@link ng.$compileProvider#directive directives}. * * <div class="alert alert-warning"> * **Note:** This document is an in-depth reference of all directive options. * For a gentle introduction to directives with examples of common use cases, * see the {@link guide/directive directive guide}. * </div> * * ## Comprehensive Directive API * * There are many different options for a directive. * * The difference resides in the return value of the factory function. * You can either return a "Directive Definition Object" (see below) that defines the directive properties, * or just the `postLink` function (all other properties will have the default values). * * <div class="alert alert-success"> * **Best Practice:** It's recommended to use the "directive definition object" form. * </div> * * Here's an example directive declared with a Directive Definition Object: * * ```js * var myModule = angular.module(...); * * myModule.directive('directiveName', function factory(injectables) { * var directiveDefinitionObject = { * priority: 0, * template: '<div></div>', // or // function(tElement, tAttrs) { ... }, * // or * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, * transclude: false, * restrict: 'A', * templateNamespace: 'html', * scope: false, * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, * controllerAs: 'stringAlias', * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], * compile: function compile(tElement, tAttrs, transclude) { * return { * pre: function preLink(scope, iElement, iAttrs, controller) { ... }, * post: function postLink(scope, iElement, iAttrs, controller) { ... } * } * // or * // return function postLink( ... ) { ... } * }, * // or * // link: { * // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, * // post: function postLink(scope, iElement, iAttrs, controller) { ... } * // } * // or * // link: function postLink( ... ) { ... } * }; * return directiveDefinitionObject; * }); * ``` * * <div class="alert alert-warning"> * **Note:** Any unspecified options will use the default value. You can see the default values below. * </div> * * Therefore the above can be simplified as: * * ```js * var myModule = angular.module(...); * * myModule.directive('directiveName', function factory(injectables) { * var directiveDefinitionObject = { * link: function postLink(scope, iElement, iAttrs) { ... } * }; * return directiveDefinitionObject; * // or * // return function postLink(scope, iElement, iAttrs) { ... } * }); * ``` * * * * ### Directive Definition Object * * The directive definition object provides instructions to the {@link ng.$compile * compiler}. The attributes are: * * #### `multiElement` * When this property is set to true, the HTML compiler will collect DOM nodes between * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them * together as the directive elements. It is recomended that this feature be used on directives * which are not strictly behavioural (such as {@link ngClick}), and which * do not manipulate or replace child nodes (such as {@link ngInclude}). * * #### `priority` * When there are multiple directives defined on a single DOM element, sometimes it * is necessary to specify the order in which the directives are applied. The `priority` is used * to sort the directives before their `compile` functions get called. Priority is defined as a * number. Directives with greater numerical `priority` are compiled first. Pre-link functions * are also run in priority order, but post-link functions are run in reverse order. The order * of directives with the same priority is undefined. The default priority is `0`. * * #### `terminal` * If set to true then the current `priority` will be the last set of directives * which will execute (any directives at the current priority will still execute * as the order of execution on same `priority` is undefined). Note that expressions * and other directives used in the directive's template will also be excluded from execution. * * #### `scope` * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the * same element request a new scope, only one new scope is created. The new scope rule does not * apply for the root of the template since the root of the template always gets a new scope. * * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from * normal scope in that it does not prototypically inherit from the parent scope. This is useful * when creating reusable components, which should not accidentally read or modify data in the * parent scope. * * The 'isolate' scope takes an object hash which defines a set of local scope properties * derived from the parent scope. These local properties are useful for aliasing values for * templates. Locals definition is a hash of local scope property to its source: * * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is * always a string since DOM attributes are strings. If no `attr` name is specified then the * attribute name is assumed to be the same as the local name. * Given `<widget my-attr="hello {{name}}">` and widget definition * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the * `localName` property on the widget scope. The `name` is read from the parent scope (not * component scope). * * * `=` or `=attr` - set up bi-directional binding between a local scope property and the * parent scope property of name defined via the value of the `attr` attribute. If no `attr` * name is specified then the attribute name is assumed to be the same as the local name. * Given `<widget my-attr="parentModel">` and widget definition of * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional). * * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. * If no `attr` name is specified then the attribute name is assumed to be the same as the * local name. Given `<widget my-attr="count = count + value">` and widget definition of * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to * a function wrapper for the `count = count + value` expression. Often it's desirable to * pass data from the isolated scope via an expression to the parent scope, this can be * done by passing a map of local variable names and values into the expression wrapper fn. * For example, if the expression is `increment(amount)` then we can specify the amount value * by calling the `localFn` as `localFn({amount: 22})`. * * * #### `bindToController` * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will * allow a component to have its properties bound to the controller, rather than to scope. When the controller * is instantiated, the initial values of the isolate scope bindings are already available. * * #### `controller` * Controller constructor function. The controller is instantiated before the * pre-linking phase and it is shared with other directives (see * `require` attribute). This allows the directives to communicate with each other and augment * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: * * * `$scope` - Current scope associated with the element * * `$element` - Current element * * `$attrs` - Current attributes object for the element * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope: * `function([scope], cloneLinkingFn, futureParentElement)`. * * `scope`: optional argument to override the scope. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content. * * `futureParentElement`: * * defines the parent to which the `cloneLinkingFn` will add the cloned elements. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements) * and when the `cloneLinkinFn` is passed, * as those elements need to created and cloned in a special way when they are defined outside their * usual containers (e.g. like `<svg>`). * * See also the `directive.templateNamespace` property. * * * #### `require` * Require another directive and inject its controller as the fourth argument to the linking function. The * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the * injected argument will be an array in corresponding order. If no such directive can be * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: * * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass * `null` to the `link` fn if not found. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass * `null` to the `link` fn if not found. * * * #### `controllerAs` * Controller alias at the directive scope. An alias for the controller so it * can be referenced at the directive template. The directive needs to define a scope for this * configuration to be used. Useful in the case when directive is used as component. * * * #### `restrict` * String of subset of `EACM` which restricts the directive to a specific directive * declaration style. If omitted, the defaults (elements and attributes) are used. * * * `E` - Element name (default): `<my-directive></my-directive>` * * `A` - Attribute (default): `<div my-directive="exp"></div>` * * `C` - Class: `<div class="my-directive: exp;"></div>` * * `M` - Comment: `<!-- directive: my-directive exp -->` * * * #### `templateNamespace` * String representing the document type used by the markup in the template. * AngularJS needs this information as those elements need to be created and cloned * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`. * * * `html` - All root nodes in the template are HTML. Root nodes may also be * top-level elements such as `<svg>` or `<math>`. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`). * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`). * * If no `templateNamespace` is specified, then the namespace is considered to be `html`. * * #### `template` * HTML markup that may: * * Replace the contents of the directive's element (default). * * Replace the directive's element itself (if `replace` is true - DEPRECATED). * * Wrap the contents of the directive's element (if `transclude` is true). * * Value may be: * * * A string. For example `<div red-on-hover>{{delete_str}}</div>`. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile` * function api below) and returns a string value. * * * #### `templateUrl` * This is similar to `template` but the template is loaded from the specified URL, asynchronously. * * Because template loading is asynchronous the compiler will suspend compilation of directives on that element * for later when the template has been resolved. In the meantime it will continue to compile and link * sibling and parent elements as though this element had not contained any directives. * * The compiler does not suspend the entire compilation to wait for templates to be loaded because this * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the * case when only one deeply nested directive has `templateUrl`. * * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache} * * You can specify `templateUrl` as a string representing the URL or as a function which takes two * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns * a string value representing the url. In either case, the template URL is passed through {@link * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. * * * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0) * specify what the template should replace. Defaults to `false`. * * * `true` - the template will replace the directive's element. * * `false` - the template will replace the contents of the directive's element. * * The replacement process migrates all of the attributes / classes from the old element to the new * one. See the {@link guide/directive#template-expanding-directive * Directives Guide} for an example. * * There are very few scenarios where element replacement is required for the application function, * the main one being reusable custom components that are used within SVG contexts * (because SVG doesn't work with custom elements in the DOM tree). * * #### `transclude` * Extract the contents of the element where the directive appears and make it available to the directive. * The contents are compiled and provided to the directive as a **transclusion function**. See the * {@link $compile#transclusion Transclusion} section below. * * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the * directive's element or the entire element: * * * `true` - transclude the content (i.e. the child nodes) of the directive's element. * * `'element'` - transclude the whole of the directive's element including any directives on this * element that defined at a lower priority than this directive. When used, the `template` * property is ignored. * * * #### `compile` * * ```js * function compile(tElement, tAttrs, transclude) { ... } * ``` * * The compile function deals with transforming the template DOM. Since most directives do not do * template transformation, it is not used often. The compile function takes the following arguments: * * * `tElement` - template element - The element where the directive has been declared. It is * safe to do template transformation on the element and child elements only. * * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared * between all directive compile functions. * * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` * * <div class="alert alert-warning"> * **Note:** The template instance and the link instance may be different objects if the template has * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration * should be done in a linking function rather than in a compile function. * </div> * <div class="alert alert-warning"> * **Note:** The compile function cannot handle directives that recursively use themselves in their * own templates or compile functions. Compiling these directives results in an infinite loop and a * stack overflow errors. * * This can be avoided by manually using $compile in the postLink function to imperatively compile * a directive's template instead of relying on automatic template compilation via `template` or * `templateUrl` declaration or manual compilation inside the compile function. * </div> * * <div class="alert alert-error"> * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it * e.g. does not know about the right outer scope. Please use the transclude function that is passed * to the link function instead. * </div> * A compile function can have a return value which can be either a function or an object. * * * returning a (post-link) function - is equivalent to registering the linking function via the * `link` property of the config object when the compile function is empty. * * * returning an object with function(s) registered via `pre` and `post` properties - allows you to * control when a linking function should be called during the linking phase. See info about * pre-linking and post-linking functions below. * * * #### `link` * This property is used only if the `compile` property is not defined. * * ```js * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } * ``` * * The link function is responsible for registering DOM listeners as well as updating the DOM. It is * executed after the template has been cloned. This is where most of the directive logic will be * put. * * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the * directive for registering {@link ng.$rootScope.Scope#$watch watches}. * * * `iElement` - instance element - The element where the directive is to be used. It is safe to * manipulate the children of the element only in `postLink` function since the children have * already been linked. * * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared * between all directive linking functions. * * * `controller` - a controller instance - A controller instance if at least one directive on the * element defines a controller. The controller is shared among all the directives, which allows * the directives to use the controllers as a communication channel. * * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. * This is the same as the `$transclude` * parameter of directive controllers, see there for details. * `function([scope], cloneLinkingFn, futureParentElement)`. * * #### Pre-linking function * * Executed before the child elements are linked. Not safe to do DOM transformation since the * compiler linking function will fail to locate the correct elements for linking. * * #### Post-linking function * * Executed after the child elements are linked. * * Note that child elements that contain `templateUrl` directives will not have been compiled * and linked since they are waiting for their template to load asynchronously and their own * compilation and linking has been suspended until that occurs. * * It is safe to do DOM transformation in the post-linking function on elements that are not waiting * for their async templates to be resolved. * * * ### Transclusion * * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and * copying them to another part of the DOM, while maintaining their connection to the original AngularJS * scope from where they were taken. * * Transclusion is used (often with {@link ngTransclude}) to insert the * original contents of a directive's element into a specified place in the template of the directive. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded * content has access to the properties on the scope from which it was taken, even if the directive * has isolated scope. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}. * * This makes it possible for the widget to have private state for its template, while the transcluded * content has access to its originating scope. * * <div class="alert alert-warning"> * **Note:** When testing an element transclude directive you must not place the directive at the root of the * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives * Testing Transclusion Directives}. * </div> * * #### Transclusion Functions * * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion * function** to the directive's `link` function and `controller`. This transclusion function is a special * **linking function** that will return the compiled contents linked to a new transclusion scope. * * <div class="alert alert-info"> * If you are just using {@link ngTransclude} then you don't need to worry about this function, since * ngTransclude will deal with it for us. * </div> * * If you want to manually control the insertion and removal of the transcluded content in your directive * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery * object that contains the compiled DOM, which is linked to the correct transclusion scope. * * When you call a transclusion function you can pass in a **clone attach function**. This function accepts * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded * content and the `scope` is the newly created transclusion scope, to which the clone is bound. * * <div class="alert alert-info"> * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope. * </div> * * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone * attach function**: * * ```js * var transcludedContent, transclusionScope; * * $transclude(function(clone, scope) { * element.append(clone); * transcludedContent = clone; * transclusionScope = scope; * }); * ``` * * Later, if you want to remove the transcluded content from your DOM then you should also destroy the * associated transclusion scope: * * ```js * transcludedContent.remove(); * transclusionScope.$destroy(); * ``` * * <div class="alert alert-info"> * **Best Practice**: if you intend to add and remove transcluded content manually in your directive * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it), * then you are also responsible for calling `$destroy` on the transclusion scope. * </div> * * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat} * automatically destroy their transluded clones as necessary so you do not need to worry about this if * you are simply using {@link ngTransclude} to inject the transclusion into your directive. * * * #### Transclusion Scopes * * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it * was taken. * * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look * like this: * * ```html * <div ng-app> * <div isolate> * <div transclusion> * </div> * </div> * </div> * ``` * * The `$parent` scope hierarchy will look like this: * * ``` * - $rootScope * - isolate * - transclusion * ``` * * but the scopes will inherit prototypically from different scopes to their `$parent`. * * ``` * - $rootScope * - transclusion * - isolate * ``` * * * ### Attributes * * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the * `link()` or `compile()` functions. It has a variety of uses. * * accessing *Normalized attribute names:* * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. * the attributes object allows for normalized access to * the attributes. * * * *Directive inter-communication:* All directives share the same instance of the attributes * object which allows the directives to use the attributes object as inter directive * communication. * * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object * allowing other directives to read the interpolated value. * * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also * the only way to easily get the actual value because during the linking phase the interpolation * hasn't been evaluated yet and so the value is at this time set to `undefined`. * * ```js * function linkingFn(scope, elm, attrs, ctrl) { * // get the attribute value * console.log(attrs.ngModel); * * // change the attribute * attrs.$set('ngModel', 'new value'); * * // observe changes to interpolated attribute * attrs.$observe('ngModel', function(value) { * console.log('ngModel has changed value to ' + value); * }); * } * ``` * * ## Example * * <div class="alert alert-warning"> * **Note**: Typically directives are registered with `module.directive`. The example below is * to illustrate how `$compile` works. * </div> * <example module="compileExample"> <file name="index.html"> <script> angular.module('compileExample', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }); }) .controller('GreeterController', ['$scope', function($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; }]); </script> <div ng-controller="GreeterController"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </file> <file name="protractor.js" type="protractor"> it('should auto compile', function() { var textarea = $('textarea'); var output = $('div[compile]'); // The initial state reads 'Hello Angular'. expect(output.getText()).toBe('Hello Angular'); textarea.clear(); textarea.sendKeys('{{name}}!'); expect(output.getText()).toBe('Angular!'); }); </file> </example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED. * * <div class="alert alert-error"> * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it * e.g. will not use the right outer scope. Please pass the transclude function as a * `parentBoundTranscludeFn` to the link function instead. * </div> * * @param {number} maxPriority only apply directives lower than given priority (Only effects the * root element(s), not their children) * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * * `options` - An optional object hash with linking options. If `options` is provided, then the following * keys may be used to control linking behavior: * * * `parentBoundTranscludeFn` - the transclude function made available to * directives; if given, it will be passed through to the link functions of * directives found in `element` during compilation. * * `transcludeControllers` - an object hash with keys that map controller names * to controller instances; if given, it will make the controllers * available to directives. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add * the cloned elements; only needed for transcludes that are allowed to contain non html * elements (e.g. SVG elements). See also the directive.controller property. * * Calling the linking function returns the element of the template. It is either the original * element passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * ```js * var element = $compile('<p>{{total}}</p>')(scope); * ``` * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * ```js * var templateElement = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clonedElement` * ``` * * * For information on how the compiler works, see the * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ var $compileMinErr = minErr('$compile'); /** * @ngdoc provider * @name $compileProvider * * @description */ $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; function $CompileProvider($provide, $$sanitizeUriProvider) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/, ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'), REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/; // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes // The assumption is that future DOM event attribute names will begin with // 'on' and be composed of only English letters. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; function parseIsolateBindings(scope, directiveName) { var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/; var bindings = {}; forEach(scope, function(definition, scopeName) { var match = definition.match(LOCAL_REGEXP); if (!match) { throw $compileMinErr('iscp', "Invalid isolate scope definition for directive '{0}'." + " Definition: {... {1}: '{2}' ...}", directiveName, scopeName, definition); } bindings[scopeName] = { mode: match[1][0], collection: match[2] === '*', optional: match[3] === '?', attrName: match[4] || scopeName }; }); return bindings; } /** * @ngdoc method * @name $compileProvider#directive * @kind function * * @description * Register a new directive with the compiler. * * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which * will match as <code>ng-bind</code>), or an object map of directives where the keys are the * names and the values are the factories. * @param {Function|Array} directiveFactory An injectable directive factory function. See * {@link guide/directive} for more info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { assertNotHasOwnProperty(name, 'directive'); if (isString(name)) { assertArg(directiveFactory, 'directiveFactory'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory, index) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.index = index; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'EA'; if (isObject(directive.scope)) { directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name); } directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; /** * @ngdoc method * @name $compileProvider#aHrefSanitizationWhitelist * @kind function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); return this; } else { return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); } }; /** * @ngdoc method * @name $compileProvider#imgSrcSanitizationWhitelist * @kind function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to img[src] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); return this; } else { return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); } }; /** * @ngdoc method * @name $compileProvider#debugInfoEnabled * * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the * current debugInfoEnabled state * @returns {*} current value if used as getter or itself (chaining) if used as setter * * @kind function * * @description * Call this method to enable/disable various debug runtime information in the compiler such as adding * binding information and a reference to the current scope on to DOM elements. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope * * `ng-binding` CSS class * * `$binding` data property containing an array of the binding expressions * * You may want to use this in production for a significant performance boost. See * {@link guide/production#disabling-debug-data Disabling Debug Data} for more. * * The default value is true. */ var debugInfoEnabled = true; this.debugInfoEnabled = function(enabled) { if (isDefined(enabled)) { debugInfoEnabled = enabled; return this; } return debugInfoEnabled; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse', '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse, $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { var Attributes = function(element, attributesToCopy) { if (attributesToCopy) { var keys = Object.keys(attributesToCopy); var i, l, key; for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; this[key] = attributesToCopy[key]; } } else { this.$attr = {}; } this.$$element = element; }; Attributes.prototype = { $normalize: directiveNormalize, /** * @ngdoc method * @name $compile.directive.Attributes#$addClass * @kind function * * @description * Adds the CSS class value specified by the classVal parameter to the element. If animations * are enabled then an animation will be triggered for the class addition. * * @param {string} classVal The className value that will be added to the element */ $addClass: function(classVal) { if (classVal && classVal.length > 0) { $animate.addClass(this.$$element, classVal); } }, /** * @ngdoc method * @name $compile.directive.Attributes#$removeClass * @kind function * * @description * Removes the CSS class value specified by the classVal parameter from the element. If * animations are enabled then an animation will be triggered for the class removal. * * @param {string} classVal The className value that will be removed from the element */ $removeClass: function(classVal) { if (classVal && classVal.length > 0) { $animate.removeClass(this.$$element, classVal); } }, /** * @ngdoc method * @name $compile.directive.Attributes#$updateClass * @kind function * * @description * Adds and removes the appropriate CSS class values to the element based on the difference * between the new and old CSS class values (specified as newClasses and oldClasses). * * @param {string} newClasses The current CSS className value * @param {string} oldClasses The former CSS className value */ $updateClass: function(newClasses, oldClasses) { var toAdd = tokenDifference(newClasses, oldClasses); if (toAdd && toAdd.length) { $animate.addClass(this.$$element, toAdd); } var toRemove = tokenDifference(oldClasses, newClasses); if (toRemove && toRemove.length) { $animate.removeClass(this.$$element, toRemove); } }, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { // TODO: decide whether or not to throw an error if "class" //is set through this function since it may cause $updateClass to //become unstable. var node = this.$$element[0], booleanKey = getBooleanAttrName(node, key), aliasedKey = getAliasedAttrName(node, key), observer = key, nodeName; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } else if (aliasedKey) { this[aliasedKey] = value; observer = aliasedKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } nodeName = nodeName_(this.$$element); if ((nodeName === 'a' && key === 'href') || (nodeName === 'img' && key === 'src')) { // sanitize a[href] and img[src] values this[key] = value = $$sanitizeUri(value, key === 'src'); } else if (nodeName === 'img' && key === 'srcset') { // sanitize img[srcset] values var result = ""; // first check if there are spaces because it's not the same pattern var trimmedSrcset = trim(value); // ( 999x ,| 999w ,| ,|, ) var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/; var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/; // split srcset into tuple of uri and descriptor except for the last item var rawUris = trimmedSrcset.split(pattern); // for each tuples var nbrUrisWith2parts = Math.floor(rawUris.length / 2); for (var i = 0; i < nbrUrisWith2parts; i++) { var innerIdx = i * 2; // sanitize the uri result += $$sanitizeUri(trim(rawUris[innerIdx]), true); // add the descriptor result += (" " + trim(rawUris[innerIdx + 1])); } // split the last item into uri and descriptor var lastTuple = trim(rawUris[i * 2]).split(/\s/); // sanitize the last uri result += $$sanitizeUri(trim(lastTuple[0]), true); // and add the last descriptor if any if (lastTuple.length === 2) { result += (" " + trim(lastTuple[1])); } this[key] = value = result; } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers var $$observers = this.$$observers; $$observers && forEach($$observers[observer], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * @ngdoc method * @name $compile.directive.Attributes#$observe * @kind function * * @description * Observes an interpolated attribute. * * The observer function will be invoked once during the next `$digest` following * compilation. The observer is then invoked whenever the interpolated value * changes. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(interpolatedValue)} fn Function that will be called whenever the interpolated value of the attribute changes. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info. * @returns {function()} Returns a deregistration function for this observer. */ $observe: function(key, fn) { var attrs = this, $$observers = (attrs.$$observers || (attrs.$$observers = createMap())), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { if (!listeners.$$inter && attrs.hasOwnProperty(key)) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); return function() { arrayRemove(listeners, fn); }; } }; function safeAddClass($element, className) { try { $element.addClass(className); } catch (e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } var startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') ? identity : function denormalizeTemplate(template) { return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); }, NG_ATTR_BINDING = /^ngAttr[A-Z]/; compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) { var bindings = $element.data('$binding') || []; if (isArray(binding)) { bindings = bindings.concat(binding); } else { bindings.push(binding); } $element.data('$binding', bindings); } : noop; compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) { safeAddClass($element, 'ng-binding'); } : noop; compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) { var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope'; $element.data(dataName, scope); } : noop; compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) { safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope'); } : noop; return compile; //================================ function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) { if (!($compileNodes instanceof jqLite)) { // jquery always rewraps, whereas we need to preserve the original selector so that we can // modify it. $compileNodes = jqLite($compileNodes); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach($compileNodes, function(node, index) { if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) { $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0]; } }); var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective, previousCompileContext); compile.$$addScopeClass($compileNodes); var namespace = null; return function publicLinkFn(scope, cloneConnectFn, options) { assertArg(scope, 'scope'); options = options || {}; var parentBoundTranscludeFn = options.parentBoundTranscludeFn, transcludeControllers = options.transcludeControllers, futureParentElement = options.futureParentElement; // When `parentBoundTranscludeFn` is passed, it is a // `controllersBoundTransclude` function (it was previously passed // as `transclude` to directive.link) so we must unwrap it to get // its `boundTranscludeFn` if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) { parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude; } if (!namespace) { namespace = detectNamespaceForChildElements(futureParentElement); } var $linkNode; if (namespace !== 'html') { // When using a directive with replace:true and templateUrl the $compileNodes // (or a child element inside of them) // might change, so we need to recreate the namespace adapted compileNodes // for call to the link function. // Note: This will already clone the nodes... $linkNode = jqLite( wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html()) ); } else if (cloneConnectFn) { // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. $linkNode = JQLitePrototype.clone.call($compileNodes); } else { $linkNode = $compileNodes; } if (transcludeControllers) { for (var controllerName in transcludeControllers) { $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance); } } compile.$$addScopeInfo($linkNode, scope); if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); return $linkNode; }; } function detectNamespaceForChildElements(parentElement) { // TODO: Make this detect MathML as well... var node = parentElement && parentElement[0]; if (!node) { return 'html'; } else { return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html'; } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes or NodeList to compile * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then * the rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} maxPriority Max directive priority. * @returns {Function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, previousCompileContext) { var linkFns = [], attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound; for (var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, ignoreDirective); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement, null, [], [], previousCompileContext) : null; if (nodeLinkFn && nodeLinkFn.scope) { compile.$$addScopeClass(attrs.$$element); } childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !(childNodes = nodeList[i].childNodes) || !childNodes.length) ? null : compileNodes(childNodes, nodeLinkFn ? ( (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement) && nodeLinkFn.transclude) : transcludeFn); if (nodeLinkFn || childLinkFn) { linkFns.push(i, nodeLinkFn, childLinkFn); linkFnFound = true; nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn; } //use the previous context only for the first element in the virtual group previousCompileContext = null; } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) { var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn; var stableNodeList; if (nodeLinkFnFound) { // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our // offsets don't get screwed up var nodeListLength = nodeList.length; stableNodeList = new Array(nodeListLength); // create a sparse array by only copying the elements which have a linkFn for (i = 0; i < linkFns.length; i+=3) { idx = linkFns[i]; stableNodeList[idx] = nodeList[idx]; } } else { stableNodeList = nodeList; } for (i = 0, ii = linkFns.length; i < ii;) { node = stableNodeList[linkFns[i++]]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(); compile.$$addScopeInfo(jqLite(node), childScope); } else { childScope = scope; } if (nodeLinkFn.transcludeOnThisElement) { childBoundTranscludeFn = createBoundTranscludeFn( scope, nodeLinkFn.transclude, parentBoundTranscludeFn, nodeLinkFn.elementTranscludeOnThisElement); } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { childBoundTranscludeFn = parentBoundTranscludeFn; } else if (!parentBoundTranscludeFn && transcludeFn) { childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn); } else { childBoundTranscludeFn = null; } nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn); } else if (childLinkFn) { childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn); } } } } function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) { var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { if (!transcludedScope) { transcludedScope = scope.$new(false, containingScope); transcludedScope.$$transcluded = true; } return transcludeFn(transcludedScope, cloneFn, { parentBoundTranscludeFn: previousBoundTranscludeFn, transcludeControllers: controllers, futureParentElement: futureParentElement }); }; return boundTranscludeFn; } /** * Looks for directives on the given node and adds them to the directive collection which is * sorted. * * @param node Node to search. * @param directives An array to which the directives are added to. This array is sorted before * the function returns. * @param attrs The shared attrs object which is used to populate the normalized attributes. * @param {number=} maxPriority Max directive priority. */ function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch (nodeType) { case NODE_TYPE_ELEMENT: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective); // iterate over the attributes for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { var attrStartName = false; var attrEndName = false; attr = nAttrs[j]; name = attr.name; value = trim(attr.value); // support ngAttr attribute binding ngAttrName = directiveNormalize(name); if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) { name = snake_case(ngAttrName.substr(6), '-'); } var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); if (directiveIsMultiElement(directiveNName)) { if (ngAttrName === directiveNName + 'Start') { attrStartName = name; attrEndName = name.substr(0, name.length - 5) + 'end'; name = name.substr(0, name.length - 6); } } nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; if (isNgAttr || !attrs.hasOwnProperty(nName)) { attrs[nName] = value; if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } } addAttrInterpolateDirective(node, directives, value, nName, isNgAttr); addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, attrEndName); } // use class as directive className = node.className; if (isString(className) && className !== '') { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case NODE_TYPE_TEXT: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case NODE_TYPE_COMMENT: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read // comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Given a node with an directive-start it collects all of the siblings until it finds * directive-end. * @param node * @param attrStart * @param attrEnd * @returns {*} */ function groupScan(node, attrStart, attrEnd) { var nodes = []; var depth = 0; if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { do { if (!node) { throw $compileMinErr('uterdir', "Unterminated attribute, found '{0}' but no matching '{1}' found.", attrStart, attrEnd); } if (node.nodeType == NODE_TYPE_ELEMENT) { if (node.hasAttribute(attrStart)) depth++; if (node.hasAttribute(attrEnd)) depth--; } nodes.push(node); node = node.nextSibling; } while (depth > 0); } else { nodes.push(node); } return jqLite(nodes); } /** * Wrapper for linking function which converts normal linking function into a grouped * linking function. * @param linkFn * @param attrStart * @param attrEnd * @returns {Function} */ function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { return function(scope, element, attrs, controllers, transcludeFn) { element = groupScan(element[0], attrStart, attrEnd); return linkFn(scope, element, attrs, controllers, transcludeFn); }; } /** * Once the directives have been collected, their compile functions are executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the * scope argument is auto-generated to the new * child of the transcluded parent scope. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace nodes * on it. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when * compiling the transclusion. * @param {Array.<Function>} preLinkFns * @param {Array.<Function>} postLinkFns * @param {Object} previousCompileContext Context used for previous compilation of the current * node * @returns {Function} linkFn */ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, previousCompileContext) { previousCompileContext = previousCompileContext || {}; var terminalPriority = -Number.MAX_VALUE, newScopeDirective, controllerDirectives = previousCompileContext.controllerDirectives, controllers, newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, templateDirective = previousCompileContext.templateDirective, nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, hasTranscludeDirective = false, hasTemplate = false, hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, replaceDirective = originalReplaceDirective, childTranscludeFn = transcludeFn, linkFn, directiveValue; // executes all directives on the current element for (var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; var attrStart = directive.$$start; var attrEnd = directive.$$end; // collect multiblock sections if (attrStart) { $compileNode = groupScan(compileNode, attrStart, attrEnd); } $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { // skip the check for directives with async templates, we'll check the derived sync // directive when the template arrives if (!directive.templateUrl) { if (isObject(directiveValue)) { // This directive is trying to add an isolated scope. // Check that there is no scope of any kind already assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective, directive, $compileNode); newIsolateScopeDirective = directive; } else { // This directive is trying to add a child scope. // Check that there is no isolated scope already assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, $compileNode); } } newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (!directive.templateUrl && directive.controller) { directiveValue = directive.controller; controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { hasTranscludeDirective = true; // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. // This option should only be used by directives that know how to safely handle element transclusion, // where the transcluded nodes are added or replaced after linking. if (!directive.$$tlb) { assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); nonTlbTranscludeDirective = directive; } if (directiveValue == 'element') { hasElementTranscludeDirective = true; terminalPriority = directive.priority; $template = $compileNode; $compileNode = templateAttrs.$$element = jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); compileNode = $compileNode[0]; replaceWith(jqCollection, sliceArgs($template), compileNode); childTranscludeFn = compile($template, transcludeFn, terminalPriority, replaceDirective && replaceDirective.name, { // Don't pass in: // - controllerDirectives - otherwise we'll create duplicates controllers // - newIsolateScopeDirective or templateDirective - combining templates with // element transclusion doesn't make sense. // // We need only nonTlbTranscludeDirective so that we prevent putting transclusion // on the same element more than once. nonTlbTranscludeDirective: nonTlbTranscludeDirective }); } else { $template = jqLite(jqLiteClone(compileNode)).contents(); $compileNode.empty(); // clear contents childTranscludeFn = compile($template, transcludeFn); } } if (directive.template) { hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; directiveValue = (isFunction(directive.template)) ? directive.template($compileNode, templateAttrs) : directive.template; directiveValue = denormalizeTemplate(directiveValue); if (directive.replace) { replaceDirective = directive; if (jqLiteIsTextNode(directiveValue)) { $template = []; } else { $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue))); } compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", directiveName, ''); } replaceWith(jqCollection, $compileNode, compileNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) // - collect directives from the template and sort them by priority // - combine directives as: processed + template + unprocessed var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); if (newIsolateScopeDirective) { markDirectivesAsIsolate(templateDirectives); } directives = directives.concat(templateDirectives).concat(unprocessedDirectives); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { $compileNode.html(directiveValue); } } if (directive.templateUrl) { hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; if (directive.replace) { replaceDirective = directive; } nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { controllerDirectives: controllerDirectives, newIsolateScopeDirective: newIsolateScopeDirective, templateDirective: templateDirective, nonTlbTranscludeDirective: nonTlbTranscludeDirective }); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { addLinkFns(null, linkFn, attrStart, attrEnd); } else if (linkFn) { addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); } } if (directive.terminal) { nodeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective; nodeLinkFn.templateOnThisElement = hasTemplate; nodeLinkFn.transclude = childTranscludeFn; previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// function addLinkFns(pre, post, attrStart, attrEnd) { if (pre) { if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); pre.require = directive.require; pre.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { pre = cloneAndAnnotateFn(pre, {isolateScope: true}); } preLinkFns.push(pre); } if (post) { if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); post.require = directive.require; post.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { post = cloneAndAnnotateFn(post, {isolateScope: true}); } postLinkFns.push(post); } } function getControllers(directiveName, require, $element, elementControllers) { var value, retrievalMethod = 'data', optional = false; var $searchElement = $element; var match; if (isString(require)) { match = require.match(REQUIRE_PREFIX_REGEXP); require = require.substring(match[0].length); if (match[3]) { if (match[1]) match[3] = null; else match[1] = match[3]; } if (match[1] === '^') { retrievalMethod = 'inheritedData'; } else if (match[1] === '^^') { retrievalMethod = 'inheritedData'; $searchElement = $element.parent(); } if (match[2] === '?') { optional = true; } value = null; if (elementControllers && retrievalMethod === 'data') { if (value = elementControllers[require]) { value = value.instance; } } value = value || $searchElement[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw $compileMinErr('ctreq', "Controller '{0}', required by directive '{1}', can't be found!", require, directiveName); } return value || null; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(directiveName, require, $element, elementControllers)); }); } return value; } function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element, attrs; if (compileNode === linkNode) { attrs = templateAttrs; $element = templateAttrs.$$element; } else { $element = jqLite(linkNode); attrs = new Attributes($element, templateAttrs); } if (newIsolateScopeDirective) { isolateScope = scope.$new(true); } if (boundTranscludeFn) { // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn` // is later passed as `parentBoundTranscludeFn` to `publicLinkFn` transcludeFn = controllersBoundTransclude; transcludeFn.$$boundTransclude = boundTranscludeFn; } if (controllerDirectives) { // TODO: merge `controllers` and `elementControllers` into single object. controllers = {}; elementControllers = {}; forEach(controllerDirectives, function(directive) { var locals = { $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, $element: $element, $attrs: attrs, $transclude: transcludeFn }, controllerInstance; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } controllerInstance = $controller(controller, locals, true, directive.controllerAs); // For directives with element transclusion the element is a comment, // but jQuery .data doesn't support attaching data to comment nodes as it's hard to // clean up (http://bugs.jquery.com/ticket/8335). // Instead, we save the controllers for the element in a local hash and attach to .data // later, once we have the actual element. elementControllers[directive.name] = controllerInstance; if (!hasElementTranscludeDirective) { $element.data('$' + directive.name + 'Controller', controllerInstance.instance); } controllers[directive.name] = controllerInstance; }); } if (newIsolateScopeDirective) { compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective || templateDirective === newIsolateScopeDirective.$$originalDirective))); compile.$$addScopeClass($element, true); var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name]; var isolateBindingContext = isolateScope; if (isolateScopeController && isolateScopeController.identifier && newIsolateScopeDirective.bindToController === true) { isolateBindingContext = isolateScopeController.instance; } forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) { var attrName = definition.attrName, optional = definition.optional, mode = definition.mode, // @, =, or & lastValue, parentGet, parentSet, compare; switch (mode) { case '@': attrs.$observe(attrName, function(value) { isolateBindingContext[scopeName] = value; }); attrs.$$observers[attrName].$$scope = scope; if (attrs[attrName]) { // If the attribute has been provided then we trigger an interpolation to ensure // the value is there for use in the link fn isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope); } break; case '=': if (optional && !attrs[attrName]) { return; } parentGet = $parse(attrs[attrName]); if (parentGet.literal) { compare = equals; } else { compare = function(a, b) { return a === b || (a !== a && b !== b); }; } parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest lastValue = isolateBindingContext[scopeName] = parentGet(scope); throw $compileMinErr('nonassign', "Expression '{0}' used with directive '{1}' is non-assignable!", attrs[attrName], newIsolateScopeDirective.name); }; lastValue = isolateBindingContext[scopeName] = parentGet(scope); var parentValueWatch = function parentValueWatch(parentValue) { if (!compare(parentValue, isolateBindingContext[scopeName])) { // we are out of sync and need to copy if (!compare(parentValue, lastValue)) { // parent changed and it has precedence isolateBindingContext[scopeName] = parentValue; } else { // if the parent can be assigned then do so parentSet(scope, parentValue = isolateBindingContext[scopeName]); } } return lastValue = parentValue; }; parentValueWatch.$stateful = true; var unwatch; if (definition.collection) { unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch); } else { unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal); } isolateScope.$on('$destroy', unwatch); break; case '&': parentGet = $parse(attrs[attrName]); isolateBindingContext[scopeName] = function(locals) { return parentGet(scope, locals); }; break; } }); } if (controllers) { forEach(controllers, function(controller) { controller(); }); controllers = null; } // PRELINKING for (i = 0, ii = preLinkFns.length; i < ii; i++) { linkFn = preLinkFns[i]; invokeLinkFn(linkFn, linkFn.isolateScope ? isolateScope : scope, $element, attrs, linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn ); } // RECURSION // We only pass the isolate scope, if the isolate directive has a template, // otherwise the child elements do not belong to the isolate directive. var scopeToChild = scope; if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { scopeToChild = isolateScope; } childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for (i = postLinkFns.length - 1; i >= 0; i--) { linkFn = postLinkFns[i]; invokeLinkFn(linkFn, linkFn.isolateScope ? isolateScope : scope, $element, attrs, linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn ); } // This is the function that is injected as `$transclude`. // Note: all arguments are optional! function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) { var transcludeControllers; // No scope passed in: if (!isScope(scope)) { futureParentElement = cloneAttachFn; cloneAttachFn = scope; scope = undefined; } if (hasElementTranscludeDirective) { transcludeControllers = elementControllers; } if (!futureParentElement) { futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element; } return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); } } } function markDirectivesAsIsolate(directives) { // mark all directives as needing isolate scope. for (var j = 0, jj = directives.length; j < jj; j++) { directives[j] = inherit(directives[j], {$$isolateScope: true}); } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns {boolean} true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, endAttrName) { if (name === ignoreDirective) return null; var match = null; if (hasDirectives.hasOwnProperty(name)) { for (var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i < ii; i++) { try { directive = directives[i]; if ((maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { if (startAttrName) { directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); } tDirectives.push(directive); match = directive; } } catch (e) { $exceptionHandler(e); } } } return match; } /** * looks up the directive and returns true if it is a multi-element directive, * and therefore requires DOM nodes between -start and -end markers to be grouped * together. * * @param {string} name name of the directive to look up. * @returns true if directive was registered as multi-element. */ function directiveIsMultiElement(name) { if (hasDirectives.hasOwnProperty(name)) { for (var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; if (directive.multiElement) { return true; } } } return false; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key] && src[key] !== value) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; // `dst` will never contain hasOwnProperty as DOM parser won't let it. // You will get an "InvalidCharacterError: DOM Exception 5" error if you // have an attribute like "has-own-property" or "data-has-own-property", etc. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, $compileNode, tAttrs, $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective }), templateUrl = (isFunction(origAsyncDirective.templateUrl)) ? origAsyncDirective.templateUrl($compileNode, tAttrs) : origAsyncDirective.templateUrl, templateNamespace = origAsyncDirective.templateNamespace; $compileNode.empty(); $templateRequest($sce.getTrustedResourceUrl(templateUrl)) .then(function(content) { var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; content = denormalizeTemplate(content); if (origAsyncDirective.replace) { if (jqLiteIsTextNode(content)) { $template = []; } else { $template = removeComments(wrapTemplate(templateNamespace, trim(content))); } compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { throw $compileMinErr('tplrt', "Template for directive '{0}' must have exactly one root element. {1}", origAsyncDirective.name, templateUrl); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); if (isObject(origAsyncDirective.scope)) { markDirectivesAsIsolate(templateDirectives); } directives = templateDirectives.concat(directives); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; $compileNode.html(content); } directives.unshift(derivedSyncDirective); afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, previousCompileContext); forEach($rootElement, function(node, i) { if (node == compileNode) { $rootElement[i] = $compileNode[0]; } }); afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); while (linkQueue.length) { var scope = linkQueue.shift(), beforeTemplateLinkNode = linkQueue.shift(), linkRootElement = linkQueue.shift(), boundTranscludeFn = linkQueue.shift(), linkNode = $compileNode[0]; if (scope.$$destroyed) continue; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { var oldClasses = beforeTemplateLinkNode.className; if (!(previousCompileContext.hasElementTranscludeDirective && origAsyncDirective.replace)) { // it was cloned therefore we have to clone as well. linkNode = jqLiteClone(compileNode); } replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); // Copy in CSS classes from original node safeAddClass(jqLite(linkNode), oldClasses); } if (afterTemplateNodeLinkFn.transcludeOnThisElement) { childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); } else { childBoundTranscludeFn = boundTranscludeFn; } afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, childBoundTranscludeFn); } linkQueue = null; }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { var childBoundTranscludeFn = boundTranscludeFn; if (scope.$$destroyed) return; if (linkQueue) { linkQueue.push(scope, node, rootElement, childBoundTranscludeFn); } else { if (afterTemplateNodeLinkFn.transcludeOnThisElement) { childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); } afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { var diff = b.priority - a.priority; if (diff !== 0) return diff; if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; return a.index - b.index; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', previousDirective.name, directive.name, what, startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: function textInterpolateCompileFn(templateNode) { var templateNodeParent = templateNode.parent(), hasCompileParent = !!templateNodeParent.length; // When transcluding a template that has bindings in the root // we don't have a parent and thus need to add the class during linking fn. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent); return function textInterpolateLinkFn(scope, node) { var parent = node.parent(); if (!hasCompileParent) compile.$$addBindingClass(parent); compile.$$addBindingInfo(parent, interpolateFn.expressions); scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { node[0].nodeValue = value; }); }; } }); } } function wrapTemplate(type, template) { type = lowercase(type || 'html'); switch (type) { case 'svg': case 'math': var wrapper = document.createElement('div'); wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>'; return wrapper.childNodes[0].childNodes; default: return template; } } function getTrustedContext(node, attrNormalizedName) { if (attrNormalizedName == "srcdoc") { return $sce.HTML; } var tag = nodeName_(node); // maction[xlink:href] can source SVG. It's not limited to <maction>. if (attrNormalizedName == "xlinkHref" || (tag == "form" && attrNormalizedName == "action") || (tag != "img" && (attrNormalizedName == "src" || attrNormalizedName == "ngSrc"))) { return $sce.RESOURCE_URL; } } function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) { var interpolateFn = $interpolate(value, true); // no interpolation found -> ignore if (!interpolateFn) return; if (name === "multiple" && nodeName_(node) === "select") { throw $compileMinErr("selmulti", "Binding to the 'multiple' attribute is not supported. Element: {0}", startingTag(node)); } directives.push({ priority: 100, compile: function() { return { pre: function attrInterpolatePreLinkFn(scope, element, attr) { var $$observers = (attr.$$observers || (attr.$$observers = {})); if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { throw $compileMinErr('nodomevents', "Interpolations for HTML DOM event attributes are disallowed. Please use the " + "ng- versions (such as ng-click instead of onclick) instead."); } // If the attribute was removed, then we are done if (!attr[name]) { return; } // we need to interpolate again, in case the attribute value has been updated // (e.g. by another directive's compile function) interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name), ALL_OR_NOTHING_ATTRS[name] || allOrNothing); // if attribute was updated so that there is no interpolation going on we don't want to // register any observers if (!interpolateFn) return; // initialize attr object so that it's ready in case we need the value for isolate // scope initialization, otherwise the value would not be available from isolate // directive's linking fn during linking phase attr[name] = interpolateFn(scope); ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { //special case for class attribute addition + removal //so that class changes can tap into the animation //hooks provided by the $animate service. Be sure to //skip animations when the first digest occurs (when //both the new and the old values are the same) since //the CSS classes are the non-interpolated values if (name === 'class' && newValue != oldValue) { attr.$updateClass(newValue, oldValue); } else { attr.$set(name, newValue); } }); } }; } }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep * the shell, but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith($rootElement, elementsToRemove, newNode) { var firstElementToRemove = elementsToRemove[0], removeCount = elementsToRemove.length, parent = firstElementToRemove.parentNode, i, ii; if ($rootElement) { for (i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] == firstElementToRemove) { $rootElement[i++] = newNode; for (var j = i, j2 = j + removeCount - 1, jj = $rootElement.length; j < jj; j++, j2++) { if (j2 < jj) { $rootElement[j] = $rootElement[j2]; } else { delete $rootElement[j]; } } $rootElement.length -= removeCount - 1; // If the replaced element is also the jQuery .context then replace it // .context is a deprecated jQuery api, so we should set it only when jQuery set it // http://api.jquery.com/context/ if ($rootElement.context === firstElementToRemove) { $rootElement.context = newNode; } break; } } } if (parent) { parent.replaceChild(newNode, firstElementToRemove); } // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it? var fragment = document.createDocumentFragment(); fragment.appendChild(firstElementToRemove); // Copy over user data (that includes Angular's $scope etc.). Don't copy private // data here because there's no public interface in jQuery to do that and copying over // event listeners (which is the main use of private data) wouldn't work anyway. jqLite(newNode).data(jqLite(firstElementToRemove).data()); // Remove data of the replaced element. We cannot just call .remove() // on the element it since that would deallocate scope that is needed // for the new node. Instead, remove the data "manually". if (!jQuery) { delete jqLite.cache[firstElementToRemove[jqLite.expando]]; } else { // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after // the replaced element. The cleanData version monkey-patched by Angular would cause // the scope to be trashed and we do need the very same scope to work with the new // element. However, we cannot just cache the non-patched version and use it here as // that would break if another library patches the method after Angular does (one // example is jQuery UI). Instead, set a flag indicating scope destroying should be // skipped this one time. skipDestroyOnNextJQueryCleanData = true; jQuery.cleanData([firstElementToRemove]); } for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { var element = elementsToRemove[k]; jqLite(element).remove(); // must do this way to clean up expando fragment.appendChild(element); delete elementsToRemove[k]; } elementsToRemove[0] = newNode; elementsToRemove.length = 1; } function cloneAndAnnotateFn(fn, annotation) { return extend(function() { return fn.apply(null, arguments); }, fn, annotation); } function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) { try { linkFn(scope, $element, attrs, controllers, transcludeFn); } catch (e) { $exceptionHandler(e, startingTag($element)); } } }]; } var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': * my:Directive * my-directive * x-my-directive * data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * @ngdoc type * @name $compile.directive.Attributes * * @description * A shared object between directive compile / linking functions which contains normalized DOM * element attributes. The values reflect current binding state `{{ }}`. The normalization is * needed since all of these are treated as equivalent in Angular: * * ``` * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> * ``` */ /** * @ngdoc property * @name $compile.directive.Attributes#$attr * * @description * A map of DOM element attribute names to the normalized name. This is * needed to do reverse lookup from normalized name back to actual name. */ /** * @ngdoc method * @name $compile.directive.Attributes#$set * @kind function * * @description * Set DOM element attribute value. * * * @param {string} name Normalized element attribute name of the property to modify. The name is * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. * @param {string} value Value to set the attribute to. The value can be an interpolated string. */ /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ) {} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ) {} function tokenDifference(str1, str2) { var values = '', tokens1 = str1.split(/\s+/), tokens2 = str2.split(/\s+/); outer: for (var i = 0; i < tokens1.length; i++) { var token = tokens1[i]; for (var j = 0; j < tokens2.length; j++) { if (token == tokens2[j]) continue outer; } values += (values.length > 0 ? ' ' : '') + token; } return values; } function removeComments(jqNodes) { jqNodes = jqLite(jqNodes); var i = jqNodes.length; if (i <= 1) { return jqNodes; } while (i--) { var node = jqNodes[i]; if (node.nodeType === NODE_TYPE_COMMENT) { splice.call(jqNodes, i, 1); } } return jqNodes; } /** * @ngdoc provider * @name $controllerProvider * @description * The {@link ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}, globals = false, CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; /** * @ngdoc method * @name $controllerProvider#register * @param {string|Object} name Controller name, or an object map of controllers where the keys are * the names and the values are the constructors. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { assertNotHasOwnProperty(name, 'controller'); if (isObject(name)) { extend(controllers, name); } else { controllers[name] = constructor; } }; /** * @ngdoc method * @name $controllerProvider#allowGlobals * @description If called, allows `$controller` to find controller constructors on `window` */ this.allowGlobals = function() { globals = true; }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc service * @name $controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global * `window` object (not recommended) * * The string can use the `controller as property` syntax, where the controller instance is published * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this * to work correctly. * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just a simple call to {@link auto.$injector $injector}, but extracted into * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). */ return function(expression, locals, later, ident) { // PRIVATE API: // param `later` --- indicates that the controller's constructor is invoked at a later time. // If true, $controller will allocate the object with the correct // prototype chain, but will not invoke the controller until a returned // callback is invoked. // param `ident` --- An optional label which overrides the label parsed from the controller // expression, if any. var instance, match, constructor, identifier; later = later === true; if (ident && isString(ident)) { identifier = ident; } if (isString(expression)) { match = expression.match(CNTRL_REG), constructor = match[1], identifier = identifier || match[3]; expression = controllers.hasOwnProperty(constructor) ? controllers[constructor] : getter(locals.$scope, constructor, true) || (globals ? getter($window, constructor, true) : undefined); assertArgFn(expression, constructor, true); } if (later) { // Instantiate controller later: // This machinery is used to create an instance of the object before calling the // controller's constructor itself. // // This allows properties to be added to the controller before the constructor is // invoked. Primarily, this is used for isolate scope bindings in $compile. // // This feature is not intended for use by applications, and is thus not documented // publicly. // Object creation: http://jsperf.com/create-constructor/2 var controllerPrototype = (isArray(expression) ? expression[expression.length - 1] : expression).prototype; instance = Object.create(controllerPrototype); if (identifier) { addIdentifier(locals, identifier, instance, constructor || expression.name); } return extend(function() { $injector.invoke(expression, instance, locals, constructor); return instance; }, { instance: instance, identifier: identifier }); } instance = $injector.instantiate(expression, locals, constructor); if (identifier) { addIdentifier(locals, identifier, instance, constructor || expression.name); } return instance; }; function addIdentifier(locals, identifier, instance, name) { if (!(locals && isObject(locals.$scope))) { throw minErr('$controller')('noscp', "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", name, identifier); } locals.$scope[identifier] = instance; } }]; } /** * @ngdoc service * @name $document * @requires $window * * @description * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. * * @example <example module="documentExample"> <file name="index.html"> <div ng-controller="ExampleController"> <p>$document title: <b ng-bind="title"></b></p> <p>window.document title: <b ng-bind="windowTitle"></b></p> </div> </file> <file name="script.js"> angular.module('documentExample', []) .controller('ExampleController', ['$scope', '$document', function($scope, $document) { $scope.title = $document[0].title; $scope.windowTitle = angular.element(window.document)[0].title; }]); </file> </example> */ function $DocumentProvider() { this.$get = ['$window', function(window) { return jqLite(window.document); }]; } /** * @ngdoc service * @name $exceptionHandler * @requires ng.$log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. * * ## Example: * * ```js * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() { * return function(exception, cause) { * exception.message += ' (caused by "' + cause + '")'; * throw exception; * }; * }); * ``` * * This example will override the normal action of `$exceptionHandler`, to make angular * exceptions fail hard when they happen, instead of just logging to the console. * * <hr /> * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind` * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler} * (unless executed during a digest). * * If you wish, you can manually delegate exceptions, e.g. * `try { ... } catch(e) { $exceptionHandler(e); }` * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. * */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log) { return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } var APPLICATION_JSON = 'application/json'; var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; var JSON_START = /^\s*(\[|\{[^\{])/; var JSON_END = /[\}\]]\s*$/; var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/; function defaultHttpResponseTransform(data, headers) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(JSON_PROTECTION_PREFIX, ''); var contentType = headers('Content-Type'); if ((contentType && contentType.indexOf(APPLICATION_JSON) === 0 && data.trim()) || (JSON_START.test(data) && JSON_END.test(data))) { data = fromJson(data); } } return data; } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = createMap(), key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } }); return parsed; } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { var value = headersObj[lowercase(name)]; if (value === void 0) { value = null; } return value; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers Http headers getter fn. * @param {(Function|Array.<Function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, fns) { if (isFunction(fns)) return fns(data, headers); forEach(fns, function(fn) { data = fn(data, headers); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } /** * @ngdoc provider * @name $httpProvider * @description * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. * */ function $HttpProvider() { /** * @ngdoc property * @name $httpProvider#defaults * @description * * Object containing default values for all {@link ng.$http $http} requests. * * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`} * that will provide the cache for all requests who set their `cache` property to `true`. * If you set the `default.cache = false` then only requests that specify their own custom * cache object will be cached. See {@link $http#caching $http Caching} for more information. * * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. * Defaults value is `'XSRF-TOKEN'`. * * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. * * - **`defaults.headers`** - {Object} - Default headers for all $http requests. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on * setting default headers. * - **`defaults.headers.common`** * - **`defaults.headers.post`** * - **`defaults.headers.put`** * - **`defaults.headers.patch`** * **/ var defaults = this.defaults = { // transform incoming response data transformResponse: [defaultHttpResponseTransform], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*' }, post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) }, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' }; var useApplyAsync = false; /** * @ngdoc method * @name $httpProvider#useApplyAsync * @description * * Configure $http service to combine processing of multiple http responses received at around * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in * significant performance improvement for bigger applications that make many HTTP requests * concurrently (common during application bootstrap). * * Defaults to false. If no value is specifed, returns the current configured value. * * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window * to load and share the same digest cycle. * * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. * otherwise, returns the current configured value. **/ this.useApplyAsync = function(value) { if (isDefined(value)) { useApplyAsync = !!value; return this; } return useApplyAsync; }; /** * @ngdoc property * @name $httpProvider#interceptors * @description * * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http} * pre-processing of request or postprocessing of responses. * * These service factories are ordered by request, i.e. they are applied in the same order as the * array, on request, but reverse order, on response. * * {@link ng.$http#interceptors Interceptors detailed info} **/ var interceptorFactories = this.interceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'); /** * Interceptors stored in reverse order. Inner interceptors before outer interceptors. * The reversal is needed so that we can build up the interception chain around the * server request. */ var reversedInterceptors = []; forEach(interceptorFactories, function(interceptorFactory) { reversedInterceptors.unshift(isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); /** * @ngdoc service * @kind function * @name $http * @requires ng.$httpBackend * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage * it is important to familiarize yourself with these APIs and the guarantees they provide. * * * ## General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an HTTP request and returns a {@link ng.$q promise} * with two $http specific methods: `success` and `error`. * * ```js * // Simple GET request example : * $http.get('/someUrl'). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * ``` * * ```js * // Simple POST request example (passing data) : * $http.post('/someUrl', {msg:'hello word!'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * ``` * * * Since the returned value of calling the $http function is a `promise`, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the API signature and type info below for more * details. * * A response status code between 200 and 299 is considered a success status and * will result in the success callback being called. Note that if the response is a redirect, * XMLHttpRequest will transparently follow it, meaning that the error callback will not be * called for such responses. * * ## Writing Unit Tests that use $http * When unit testing (using {@link ngMock ngMock}), it is necessary to call * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending * request using trained responses. * * ``` * $httpBackend.expectGET(...); * $http.get(...); * $httpBackend.flush(); * ``` * * ## Shortcut methods * * Shortcut methods are also available. All shortcut methods require passing in the URL, and * request data must be passed in for POST/PUT requests. * * ```js * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * ``` * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * - {@link ng.$http#patch $http.patch} * * * ## Setting HTTP Headers * * The $http service will automatically add certain HTTP headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from these configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with the lowercased HTTP method name as the key, e.g. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. * * The defaults can also be set at runtime via the `$http.defaults` object in the same * fashion. For example: * * ``` * module.run(function($http) { * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' * }); * ``` * * In addition, you can supply a `headers` property in the config object passed when * calling `$http(config)`, which overrides the defaults without changing them globally. * * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, * Use the `headers` property, setting the desired header to `undefined`. For example: * * ```js * var req = { * method: 'POST', * url: 'http://example.com', * headers: { * 'Content-Type': undefined * }, * data: { test: 'test' }, * } * * $http(req).success(function(){...}).error(function(){...}); * ``` * * ## Transforming Requests and Responses * * Both requests and responses can be transformed using transformation functions: `transformRequest` * and `transformResponse`. These properties can be a single function that returns * the transformed value (`{function(data, headersGetter)`) or an array of such transformation functions, * which allows you to `push` or `unshift` a new transformation function into the transformation chain. * * ### Default Transformations * * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and * `defaults.transformResponse` properties. If a request does not provide its own transformations * then these will be applied. * * You can augment or replace the default transformations by modifying these properties by adding to or * replacing the array. * * Angular provides the following default transformations: * * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`): * * - If the `data` property of the request configuration object contains an object, serialize it * into JSON format. * * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`): * * - If XSRF prefix is detected, strip it (see Security Considerations section below). * - If JSON response is detected, deserialize it using a JSON parser. * * * ### Overriding the Default Transformations Per Request * * If you wish override the request/response transformations only for a single request then provide * `transformRequest` and/or `transformResponse` properties on the configuration object passed * into `$http`. * * Note that if you provide these properties on the config object the default transformations will be * overwritten. If you wish to augment the default transformations then you must include them in your * local transformation array. * * The following code demonstrates adding a new response transformation to be run after the default response * transformations have been run. * * ```js * function appendTransform(defaults, transform) { * * // We can't guarantee that the default transformation is an array * defaults = angular.isArray(defaults) ? defaults : [defaults]; * * // Append the new transformation to the defaults * return defaults.concat(transform); * } * * $http({ * url: '...', * method: 'GET', * transformResponse: appendTransform($http.defaults.transformResponse, function(value) { * return doTransform(value); * }) * }); * ``` * * * ## Caching * * To enable caching, set the request configuration `cache` property to `true` (to use default * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). * When the cache is enabled, `$http` stores the response from the server in the specified * cache. The next time the same request is made, the response is served from the cache without * sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same URL that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response from the first request. * * You can change the default cache to a new object (built with * {@link ng.$cacheFactory `$cacheFactory`}) by updating the * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set * their `cache` property to `true` will now use this cache object. * * If you set the default cache to `false` then only requests that specify their own custom * cache object will be cached. * * ## Interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication, or any kind of synchronous or * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be * able to intercept requests before they are handed to the server and * responses before they are handed over to the application code that * initiated these requests. The interceptors leverage the {@link ng.$q * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. * * The interceptors are service factories that are registered with the `$httpProvider` by * adding them to the `$httpProvider.interceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor. * * There are two kinds of interceptors (and two kinds of rejection interceptors): * * * `request`: interceptors get called with a http `config` object. The function is free to * modify the `config` object or create a new one. The function needs to return the `config` * object directly, or a promise containing the `config` or a new `config` object. * * `requestError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * `response`: interceptors get called with http `response` object. The function is free to * modify the `response` object or create a new one. The function needs to return the `response` * object directly, or as a promise containing the `response` or a new `response` object. * * `responseError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * * ```js * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return { * // optional method * 'request': function(config) { * // do something on success * return config; * }, * * // optional method * 'requestError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * }, * * * * // optional method * 'response': function(response) { * // do something on success * return response; * }, * * // optional method * 'responseError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * } * }; * }); * * $httpProvider.interceptors.push('myHttpInterceptor'); * * * // alternatively, register the interceptor via an anonymous factory * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { * return { * 'request': function(config) { * // same as above * }, * * 'response': function(response) { * // same as above * } * }; * }); * ``` * * ## Security Considerations * * When designing web applications, consider security threats from: * * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ### JSON Vulnerability Protection * * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * allows third party website to turn your JSON resource URL into * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * ```js * ['one','two'] * ``` * * which is vulnerable to attack, your server can return: * ```js * )]}', * ['one','two'] * ``` * * Angular will strip the prefix, before processing the JSON. * * * ### Cross Site Request Forgery (XSRF) Protection * * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which * an unauthorized site can gain your user's private data. Angular provides a mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only * JavaScript that runs on your domain could read the cookie, your server can be assured that * the XHR came from JavaScript running on your domain. The header will not be set for * cross-domain requests. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have sent the request. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript from * making up its own tokens). We recommend that the token is a digest of your site's * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;) * for added security. * * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, * or the per-request config object. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be * JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings or functions which return strings representing * HTTP headers to send to the server. If the return value of a function is null, the * header will not be sent. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations} * - **transformResponse** – * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations} * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} * that should abort the request when resolved. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) * for more information. * - **responseType** - `{string}` - see * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). * * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform * functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * - **statusText** – `{string}` – HTTP status text of the response. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example module="httpExample"> <file name="index.html"> <div ng-controller="FetchController"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button id="fetchbtn" ng-click="fetch()">fetch</button><br> <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button id="samplejsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')"> Sample JSONP </button> <button id="invalidjsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')"> Invalid JSONP </button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> angular.module('httpExample', []) .controller('FetchController', ['$scope', '$http', '$templateCache', function($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; }]); </file> <file name="http-hello.html"> Hello, $http! </file> <file name="protractor.js" type="protractor"> var status = element(by.binding('status')); var data = element(by.binding('data')); var fetchBtn = element(by.id('fetchbtn')); var sampleGetBtn = element(by.id('samplegetbtn')); var sampleJsonpBtn = element(by.id('samplejsonpbtn')); var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); it('should make an xhr GET request', function() { sampleGetBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('200'); expect(data.getText()).toMatch(/Hello, \$http!/); }); // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 // it('should make a JSONP request to angularjs.org', function() { // sampleJsonpBtn.click(); // fetchBtn.click(); // expect(status.getText()).toMatch('200'); // expect(data.getText()).toMatch(/Super Hero!/); // }); it('should make JSONP request to invalid URL and invoke the error handler', function() { invalidJsonpBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('0'); expect(data.getText()).toMatch('Request failed'); }); </file> </example> */ function $http(requestConfig) { var config = { method: 'get', transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse }; var headers = mergeHeaders(requestConfig); if (!angular.isObject(requestConfig)) { throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig); } extend(config, requestConfig); config.headers = headers; config.method = uppercase(config.method); var serverRequest = function(config) { headers = config.headers; var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); // strip content-type if data is undefined if (isUndefined(reqData)) { forEach(headers, function(value, header) { if (lowercase(header) === 'content-type') { delete headers[header]; } }); } if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { config.withCredentials = defaults.withCredentials; } // send request return sendReq(config, reqData, headers).then(transformResponse, transformResponse); }; var chain = [serverRequest, undefined]; var promise = $q.when(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { chain.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { chain.push(interceptor.response, interceptor.responseError); } }); while (chain.length) { var thenFn = chain.shift(); var rejectFn = chain.shift(); promise = promise.then(thenFn, rejectFn); } promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response); if (!response.data) { resp.data = response.data; } else { resp.data = transformData(response.data, response.headers, config.transformResponse); } return (isSuccess(response.status)) ? resp : $q.reject(resp); } function mergeHeaders(config) { var defHeaders = defaults.headers, reqHeaders = extend({}, config.headers), defHeaderName, lowercaseDefHeaderName, reqHeaderName; defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); // using for-in instead of forEach to avoid unecessary iteration after header has been found defaultHeadersIteration: for (defHeaderName in defHeaders) { lowercaseDefHeaderName = lowercase(defHeaderName); for (reqHeaderName in reqHeaders) { if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { continue defaultHeadersIteration; } } reqHeaders[defHeaderName] = defHeaders[defHeaderName]; } // execute if header value is a function for merged headers execHeaders(reqHeaders); return reqHeaders; function execHeaders(headers) { var headerContent; forEach(headers, function(headerFn, header) { if (isFunction(headerFn)) { headerContent = headerFn(); if (headerContent != null) { headers[header] = headerContent; } else { delete headers[header]; } } }); } } } $http.pendingRequests = []; /** * @ngdoc method * @name $http#get * * @description * Shortcut method to perform `GET` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#delete * * @description * Shortcut method to perform `DELETE` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#head * * @description * Shortcut method to perform `HEAD` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#jsonp * * @description * Shortcut method to perform `JSONP` request. * * @param {string} url Relative or absolute URL specifying the destination of the request. * The name of the callback should be the string `JSON_CALLBACK`. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name $http#post * * @description * Shortcut method to perform `POST` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#put * * @description * Shortcut method to perform `PUT` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#patch * * @description * Shortcut method to perform `PATCH` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put', 'patch'); /** * @ngdoc property * @name $http#defaults * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers, withCredentials as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = defaults; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request. * * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData, reqHeaders) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = isObject(config.cache) ? config.cache : isObject(defaults.cache) ? defaults.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (isDefined(cachedResp)) { if (isPromiseLike(cachedResp)) { // cached request has already been sent, but there is no response yet cachedResp.then(removePendingReq, removePendingReq); return cachedResp; } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]); } else { resolvePromise(cachedResp, 200, {}, 'OK'); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, set the xsrf headers and // send the request to the backend if (isUndefined(cachedResp)) { var xsrfValue = urlIsSameOrigin(config.url) ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] : undefined; if (xsrfValue) { reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; } $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials, config.responseType); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString, statusText) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString), statusText]); } else { // remove promise from the cache cache.remove(url); } } function resolveHttpPromise() { resolvePromise(response, status, headersString, statusText); } if (useApplyAsync) { $rootScope.$applyAsync(resolveHttpPromise); } else { resolveHttpPromise(); if (!$rootScope.$$phase) $rootScope.$apply(); } } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers, statusText) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config, statusText: statusText }); } function removePendingReq() { var idx = $http.pendingRequests.indexOf(config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value === null || isUndefined(value)) return; if (!isArray(value)) value = [value]; forEach(value, function(v) { if (isObject(v)) { if (isDate(v)) { v = v.toISOString(); } else { v = toJson(v); } } parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); }); }); if (parts.length > 0) { url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } return url; } }]; } function createXhr() { return new window.XMLHttpRequest(); } /** * @ngdoc service * @name $httpBackend * @requires $window * @requires $document * * @description * HTTP backend used by the {@link ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link ng.$http $http} or {@link ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); }]; } function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; callbacks[callbackId].called = true; }; var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), callbackId, function(status, text) { completeRequest(callback, status, callbacks[callbackId].data, "", text); callbacks[callbackId] = noop; }); } else { var xhr = createXhr(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (isDefined(value)) { xhr.setRequestHeader(key, value); } }); xhr.onload = function requestLoaded() { var statusText = xhr.statusText || ''; // responseText is the old-school way of retrieving response (supported by IE8 & 9) // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) var response = ('response' in xhr) ? xhr.response : xhr.responseText; // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) var status = xhr.status === 1223 ? 204 : xhr.status; // fix status code when it is 0 (0 status is undocumented). // Occurs when accessing file resources or on Android 4.1 stock browser // while retrieving files from application cache. if (status === 0) { status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0; } completeRequest(callback, status, response, xhr.getAllResponseHeaders(), statusText); }; var requestError = function() { // The response is always empty // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error completeRequest(callback, -1, null, null, ''); }; xhr.onerror = requestError; xhr.onabort = requestError; if (withCredentials) { xhr.withCredentials = true; } if (responseType) { try { xhr.responseType = responseType; } catch (e) { // WebKit added support for the json responseType value on 09/03/2013 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are // known to throw when setting the value "json" as the response type. Other older // browsers implementing the responseType // // The json response type can be ignored if not supported, because JSON payloads are // parsed on the client-side regardless. if (responseType !== 'json') { throw e; } } } xhr.send(post || null); } if (timeout > 0) { var timeoutId = $browserDefer(timeoutRequest, timeout); } else if (isPromiseLike(timeout)) { timeout.then(timeoutRequest); } function timeoutRequest() { jsonpDone && jsonpDone(); xhr && xhr.abort(); } function completeRequest(callback, status, response, headersString, statusText) { // cancel timeout and subsequent timeout promise resolution timeoutId && $browserDefer.cancel(timeoutId); jsonpDone = xhr = null; callback(status, response, headersString, statusText); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, callbackId, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), callback = null; script.type = "text/javascript"; script.src = url; script.async = true; callback = function(event) { removeEventListenerFn(script, "load", callback); removeEventListenerFn(script, "error", callback); rawDocument.body.removeChild(script); script = null; var status = -1; var text = "unknown"; if (event) { if (event.type === "load" && !callbacks[callbackId].called) { event = { type: "error" }; } text = event.type; status = event.type === "error" ? 404 : 200; } if (done) { done(status, text); } }; addEventListenerFn(script, "load", callback); addEventListenerFn(script, "error", callback); rawDocument.body.appendChild(script); return callback; } } var $interpolateMinErr = minErr('$interpolate'); /** * @ngdoc provider * @name $interpolateProvider * * @description * * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. * * @example <example module="customInterpolationApp"> <file name="index.html"> <script> var customInterpolationApp = angular.module('customInterpolationApp', []); customInterpolationApp.config(function($interpolateProvider) { $interpolateProvider.startSymbol('//'); $interpolateProvider.endSymbol('//'); }); customInterpolationApp.controller('DemoController', function() { this.label = "This binding is brought you by // interpolation symbols."; }); </script> <div ng-app="App" ng-controller="DemoController as demo"> //demo.label// </div> </file> <file name="protractor.js" type="protractor"> it('should interpolate binding with custom symbols', function() { expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.'); }); </file> </example> */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name $interpolateProvider#startSymbol * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @param {string=} value new value to set the starting symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.startSymbol = function(value) { if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name $interpolateProvider#endSymbol * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @param {string=} value new value to set the ending symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.endSymbol = function(value) { if (value) { endSymbol = value; return this; } else { return endSymbol; } }; this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length, escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'), escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g'); function escape(ch) { return '\\\\\\' + ch; } /** * @ngdoc service * @name $interpolate * @kind function * * @requires $parse * @requires $sce * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link ng.$compile $compile} service for data binding. See * {@link ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * * ```js * var $interpolate = ...; // injected * var exp = $interpolate('Hello {{name | uppercase}}!'); * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); * ``` * * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is * `true`, the interpolation function will return `undefined` unless all embedded expressions * evaluate to a value other than `undefined`. * * ```js * var $interpolate = ...; // injected * var context = {greeting: 'Hello', name: undefined }; * * // default "forgiving" mode * var exp = $interpolate('{{greeting}} {{name}}!'); * expect(exp(context)).toEqual('Hello !'); * * // "allOrNothing" mode * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); * expect(exp(context)).toBeUndefined(); * context.name = 'Angular'; * expect(exp(context)).toEqual('Hello Angular!'); * ``` * * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. * * ####Escaped Interpolation * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). * It will be rendered as a regular start/end marker, and will not be interpreted as an expression * or binding. * * This enables web-servers to prevent script injection attacks and defacing attacks, to some * degree, while also enabling code examples to work without relying on the * {@link ng.directive:ngNonBindable ngNonBindable} directive. * * **For security purposes, it is strongly encouraged that web servers escape user-supplied data, * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all * interpolation start/end markers with their escaped counterparts.** * * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered * output when the $interpolate service processes the text. So, for HTML elements interpolated * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such, * this is typically useful only when user-data is used in rendering a template from the server, or * when otherwise untrusted data is used by a directive. * * <example> * <file name="index.html"> * <div ng-init="username='A user'"> * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\} * </p> * <p><strong>{{username}}</strong> attempts to inject code which will deface the * application, but fails to accomplish their task, because the server has correctly * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash) * characters.</p> * <p>Instead, the result of the attempted script injection is visible, and can be removed * from the database by an administrator.</p> * </div> * </file> * </example> * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @param {string=} trustedContext when provided, the returned function passes the interpolated * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that * provides Strict Contextual Escaping for details. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined * unless all embedded expressions evaluate to a value other than `undefined`. * @returns {function(context)} an interpolation function which is used to compute the * interpolated string. The function has these parameters: * * - `context`: evaluation context for all expressions embedded in the interpolated text */ function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { allOrNothing = !!allOrNothing; var startIndex, endIndex, index = 0, expressions = [], parseFns = [], textLength = text.length, exp, concat = [], expressionPositions = []; while (index < textLength) { if (((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) { if (index !== startIndex) { concat.push(unescapeText(text.substring(index, startIndex))); } exp = text.substring(startIndex + startSymbolLength, endIndex); expressions.push(exp); parseFns.push($parse(exp, parseStringifyInterceptor)); index = endIndex + endSymbolLength; expressionPositions.push(concat.length); concat.push(''); } else { // we did not find an interpolation, so we have to add the remainder to the separators array if (index !== textLength) { concat.push(unescapeText(text.substring(index))); } break; } } // Concatenating expressions makes it hard to reason about whether some combination of // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a // single expression be used for iframe[src], object[src], etc., we ensure that the value // that's used is assigned or constructed by some JS code somewhere that is more testable or // make it obvious that you bound the value to some user controlled value. This helps reduce // the load when auditing for XSS issues. if (trustedContext && concat.length > 1) { throw $interpolateMinErr('noconcat', "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + "interpolations that concatenate multiple expressions when a trusted value is " + "required. See http://docs.angularjs.org/api/ng.$sce", text); } if (!mustHaveExpression || expressions.length) { var compute = function(values) { for (var i = 0, ii = expressions.length; i < ii; i++) { if (allOrNothing && isUndefined(values[i])) return; concat[expressionPositions[i]] = values[i]; } return concat.join(''); }; var getValue = function(value) { return trustedContext ? $sce.getTrusted(trustedContext, value) : $sce.valueOf(value); }; var stringify = function(value) { if (value == null) { // null || undefined return ''; } switch (typeof value) { case 'string': break; case 'number': value = '' + value; break; default: value = toJson(value); } return value; }; return extend(function interpolationFn(context) { var i = 0; var ii = expressions.length; var values = new Array(ii); try { for (; i < ii; i++) { values[i] = parseFns[i](context); } return compute(values); } catch (err) { var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString()); $exceptionHandler(newErr); } }, { // all of these properties are undocumented for now exp: text, //just for compatibility with regular watchers created via $watch expressions: expressions, $$watchDelegate: function(scope, listener, objectEquality) { var lastValue; return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) { var currValue = compute(values); if (isFunction(listener)) { listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); } lastValue = currValue; }, objectEquality); } }); } function unescapeText(text) { return text.replace(escapedStartRegexp, startSymbol). replace(escapedEndRegexp, endSymbol); } function parseStringifyInterceptor(value) { try { value = getValue(value); return allOrNothing && !isDefined(value) ? value : stringify(value); } catch (err) { var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString()); $exceptionHandler(newErr); } } } /** * @ngdoc method * @name $interpolate#startSymbol * @description * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. * * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.startSymbol = function() { return startSymbol; }; /** * @ngdoc method * @name $interpolate#endSymbol * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change * the symbol. * * @returns {string} end symbol. */ $interpolate.endSymbol = function() { return endSymbol; }; return $interpolate; }]; } function $IntervalProvider() { this.$get = ['$rootScope', '$window', '$q', '$$q', function($rootScope, $window, $q, $$q) { var intervals = {}; /** * @ngdoc service * @name $interval * * @description * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay` * milliseconds. * * The return value of registering an interval function is a promise. This promise will be * notified upon each tick of the interval, and will be resolved after `count` iterations, or * run indefinitely if `count` is not defined. The value of the notification will be the * number of iterations that have run. * To cancel an interval, call `$interval.cancel(promise)`. * * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * <div class="alert alert-warning"> * **Note**: Intervals created by this service must be explicitly destroyed when you are finished * with them. In particular they are not automatically destroyed when a controller's scope or a * directive's element are destroyed. * You should take this into consideration and make sure to always cancel the interval at the * appropriate moment. See the example below for more details on how and when to do this. * </div> * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {promise} A promise which will be notified on each iteration. * * @example * <example module="intervalExample"> * <file name="index.html"> * <script> * angular.module('intervalExample', []) * .controller('ExampleController', ['$scope', '$interval', * function($scope, $interval) { * $scope.format = 'M/d/yy h:mm:ss a'; * $scope.blood_1 = 100; * $scope.blood_2 = 120; * * var stop; * $scope.fight = function() { * // Don't start a new fight if we are already fighting * if ( angular.isDefined(stop) ) return; * * stop = $interval(function() { * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) { * $scope.blood_1 = $scope.blood_1 - 3; * $scope.blood_2 = $scope.blood_2 - 4; * } else { * $scope.stopFight(); * } * }, 100); * }; * * $scope.stopFight = function() { * if (angular.isDefined(stop)) { * $interval.cancel(stop); * stop = undefined; * } * }; * * $scope.resetFight = function() { * $scope.blood_1 = 100; * $scope.blood_2 = 120; * }; * * $scope.$on('$destroy', function() { * // Make sure that the interval is destroyed too * $scope.stopFight(); * }); * }]) * // Register the 'myCurrentTime' directive factory method. * // We inject $interval and dateFilter service since the factory method is DI. * .directive('myCurrentTime', ['$interval', 'dateFilter', * function($interval, dateFilter) { * // return the directive link function. (compile function not needed) * return function(scope, element, attrs) { * var format, // date format * stopTime; // so that we can cancel the time updates * * // used to update the UI * function updateTime() { * element.text(dateFilter(new Date(), format)); * } * * // watch the expression, and update the UI on change. * scope.$watch(attrs.myCurrentTime, function(value) { * format = value; * updateTime(); * }); * * stopTime = $interval(updateTime, 1000); * * // listen on DOM destroy (removal) event, and cancel the next UI update * // to prevent updating time after the DOM element was removed. * element.on('$destroy', function() { * $interval.cancel(stopTime); * }); * } * }]); * </script> * * <div> * <div ng-controller="ExampleController"> * Date format: <input ng-model="format"> <hr/> * Current time is: <span my-current-time="format"></span> * <hr/> * Blood 1 : <font color='red'>{{blood_1}}</font> * Blood 2 : <font color='red'>{{blood_2}}</font> * <button type="button" data-ng-click="fight()">Fight</button> * <button type="button" data-ng-click="stopFight()">StopFight</button> * <button type="button" data-ng-click="resetFight()">resetFight</button> * </div> * </div> * * </file> * </example> */ function interval(fn, delay, count, invokeApply) { var setInterval = $window.setInterval, clearInterval = $window.clearInterval, iteration = 0, skipApply = (isDefined(invokeApply) && !invokeApply), deferred = (skipApply ? $$q : $q).defer(), promise = deferred.promise; count = isDefined(count) ? count : 0; promise.then(null, null, fn); promise.$$intervalId = setInterval(function tick() { deferred.notify(iteration++); if (count > 0 && iteration >= count) { deferred.resolve(iteration); clearInterval(promise.$$intervalId); delete intervals[promise.$$intervalId]; } if (!skipApply) $rootScope.$apply(); }, delay); intervals[promise.$$intervalId] = deferred; return promise; } /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {promise} promise returned by the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully canceled. */ interval.cancel = function(promise) { if (promise && promise.$$intervalId in intervals) { intervals[promise.$$intervalId].reject('canceled'); $window.clearInterval(promise.$$intervalId); delete intervals[promise.$$intervalId]; return true; } return false; }; return interval; }]; } /** * @ngdoc service * @name $locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider() { this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', 'short': 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; var $locationMinErr = minErr('$location'); /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function parseAbsoluteUrl(absoluteUrl, locationObj) { var parsedUrl = urlResolve(absoluteUrl); locationObj.$$protocol = parsedUrl.protocol; locationObj.$$host = parsedUrl.hostname; locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; } function parseAppUrl(relativeUrl, locationObj) { var prefixed = (relativeUrl.charAt(0) !== '/'); if (prefixed) { relativeUrl = '/' + relativeUrl; } var match = urlResolve(relativeUrl); locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname); locationObj.$$search = parseKeyValue(match.search); locationObj.$$hash = decodeURIComponent(match.hash); // make sure path starts with '/'; if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { locationObj.$$path = '/' + locationObj.$$path; } } /** * * @param {string} begin * @param {string} whole * @returns {string} returns text from whole after begin or undefined if it does not begin with * expected string. */ function beginsWith(begin, whole) { if (whole.indexOf(begin) === 0) { return whole.substr(begin.length); } } function stripHash(url) { var index = url.indexOf('#'); return index == -1 ? url : url.substr(0, index); } function stripFile(url) { return url.substr(0, stripHash(url).lastIndexOf('/') + 1); } /* return the server only (scheme://host:port) */ function serverBase(url) { return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); } /** * LocationHtml5Url represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} appBase application base URL * @param {string} basePrefix url path prefix */ function LocationHtml5Url(appBase, basePrefix) { this.$$html5 = true; basePrefix = basePrefix || ''; var appBaseNoFile = stripFile(appBase); parseAbsoluteUrl(appBase, this); /** * Parse given html5 (regular) url string into properties * @param {string} url HTML5 url * @private */ this.$$parse = function(url) { var pathUrl = beginsWith(appBaseNoFile, url); if (!isString(pathUrl)) { throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, appBaseNoFile); } parseAppUrl(pathUrl, this); if (!this.$$path) { this.$$path = '/'; } this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' }; this.$$parseLinkUrl = function(url, relHref) { if (relHref && relHref[0] === '#') { // special case for links to hash fragments: // keep the old url and only replace the hash fragment this.hash(relHref.slice(1)); return true; } var appUrl, prevAppUrl; var rewrittenUrl; if ((appUrl = beginsWith(appBase, url)) !== undefined) { prevAppUrl = appUrl; if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) { rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl); } else { rewrittenUrl = appBase + prevAppUrl; } } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) { rewrittenUrl = appBaseNoFile + appUrl; } else if (appBaseNoFile == url + '/') { rewrittenUrl = appBaseNoFile; } if (rewrittenUrl) { this.$$parse(rewrittenUrl); } return !!rewrittenUrl; }; } /** * LocationHashbangUrl represents url * This object is exposed as $location service when developer doesn't opt into html5 mode. * It also serves as the base class for html5 mode fallback on legacy browsers. * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangUrl(appBase, hashPrefix) { var appBaseNoFile = stripFile(appBase); parseAbsoluteUrl(appBase, this); /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' ? beginsWith(hashPrefix, withoutBaseUrl) : (this.$$html5) ? withoutBaseUrl : ''; if (!isString(withoutHashUrl)) { throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, hashPrefix); } parseAppUrl(withoutHashUrl, this); this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); this.$$compose(); /* * In Windows, on an anchor node on documents loaded from * the filesystem, the browser will return a pathname * prefixed with the drive name ('/C:/path') when a * pathname without a drive is set: * * a.setAttribute('href', '/foo') * * a.pathname === '/C:/foo' //true * * Inside of Angular, we're always using pathnames that * do not include drive names for routing. */ function removeWindowsDriveName(path, url, base) { /* Matches paths for file protocol on windows, such as /C:/foo/bar, and captures only /foo/bar. */ var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; var firstPathSegmentMatch; //Get the relative path from the input URL. if (url.indexOf(base) === 0) { url = url.replace(base, ''); } // The input URL intentionally contains a first path segment that ends with a colon. if (windowsFilePathExp.exec(url)) { return path; } firstPathSegmentMatch = windowsFilePathExp.exec(path); return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; } }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); }; this.$$parseLinkUrl = function(url, relHref) { if (stripHash(appBase) == stripHash(url)) { this.$$parse(url); return true; } return false; }; } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is enabled but the browser * does not support it. * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangInHtml5Url(appBase, hashPrefix) { this.$$html5 = true; LocationHashbangUrl.apply(this, arguments); var appBaseNoFile = stripFile(appBase); this.$$parseLinkUrl = function(url, relHref) { if (relHref && relHref[0] === '#') { // special case for links to hash fragments: // keep the old url and only replace the hash fragment this.hash(relHref.slice(1)); return true; } var rewrittenUrl; var appUrl; if (appBase == stripHash(url)) { rewrittenUrl = url; } else if ((appUrl = beginsWith(appBaseNoFile, url))) { rewrittenUrl = appBase + hashPrefix + appUrl; } else if (appBaseNoFile === url + '/') { rewrittenUrl = appBaseNoFile; } if (rewrittenUrl) { this.$$parse(rewrittenUrl); } return !!rewrittenUrl; }; this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#' this.$$absUrl = appBase + hashPrefix + this.$$url; }; } var locationPrototype = { /** * Are we in html5 mode? * @private */ $$html5: false, /** * Has any change been replacing? * @private */ $$replace: false, /** * @ngdoc method * @name $location#absUrl * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var absUrl = $location.absUrl(); * // => "http://example.com/#/some/path?foo=bar&baz=xoxo" * ``` * * @return {string} full url */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name $location#url * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var url = $location.url(); * // => "/some/path?foo=bar&baz=xoxo" * ``` * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} url */ url: function(url) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1] || url === '') this.path(decodeURIComponent(match[1])); if (match[2] || match[1] || url === '') this.search(match[3] || ''); this.hash(match[5] || ''); return this; }, /** * @ngdoc method * @name $location#protocol * * @description * This method is getter only. * * Return protocol of current url. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var protocol = $location.protocol(); * // => "http" * ``` * * @return {string} protocol of current url */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name $location#host * * @description * This method is getter only. * * Return host of current url. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var host = $location.host(); * // => "example.com" * ``` * * @return {string} host of current url. */ host: locationGetter('$$host'), /** * @ngdoc method * @name $location#port * * @description * This method is getter only. * * Return port of current url. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var port = $location.port(); * // => 80 * ``` * * @return {Number} port */ port: locationGetter('$$port'), /** * @ngdoc method * @name $location#path * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var path = $location.path(); * // => "/some/path" * ``` * * @param {(string|number)=} path New path * @return {string} path */ path: locationGetterSetter('$$path', function(path) { path = path !== null ? path.toString() : ''; return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name $location#search * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * * ```js * // given url http://example.com/#/some/path?foo=bar&baz=xoxo * var searchObject = $location.search(); * // => {foo: 'bar', baz: 'xoxo'} * * // set foo to 'yipee' * $location.search('foo', 'yipee'); * // $location.search() => {foo: 'yipee', baz: 'xoxo'} * ``` * * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or * hash object. * * When called with a single argument the method acts as a setter, setting the `search` component * of `$location` to the specified value. * * If the argument is a hash object containing an array of values, these values will be encoded * as duplicate search parameters in the url. * * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue` * will override only a single search property. * * If `paramValue` is an array, it will override the property of the `search` component of * `$location` specified via the first argument. * * If `paramValue` is `null`, the property specified via the first argument will be deleted. * * If `paramValue` is `true`, the property specified via the first argument will be added with no * value nor trailing equal sign. * * @return {Object} If called with no arguments returns the parsed `search` object. If called with * one or more arguments returns `$location` object itself. */ search: function(search, paramValue) { switch (arguments.length) { case 0: return this.$$search; case 1: if (isString(search) || isNumber(search)) { search = search.toString(); this.$$search = parseKeyValue(search); } else if (isObject(search)) { search = copy(search, {}); // remove object undefined or null properties forEach(search, function(value, key) { if (value == null) delete search[key]; }); this.$$search = search; } else { throw $locationMinErr('isrcharg', 'The first argument of the `$location#search()` call must be a string or an object.'); } break; default: if (isUndefined(paramValue) || paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } this.$$compose(); return this; }, /** * @ngdoc method * @name $location#hash * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * * ```js * // given url http://example.com/some/path?foo=bar&baz=xoxo#hashValue * var hash = $location.hash(); * // => "hashValue" * ``` * * @param {(string|number)=} hash New hash fragment * @return {string} hash */ hash: locationGetterSetter('$$hash', function(hash) { return hash !== null ? hash.toString() : ''; }), /** * @ngdoc method * @name $location#replace * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) { Location.prototype = Object.create(locationPrototype); /** * @ngdoc method * @name $location#state * * @description * This method is getter / setter. * * Return the history state object when called without any parameter. * * Change the history state object when called with one parameter and return `$location`. * The state object is later passed to `pushState` or `replaceState`. * * NOTE: This method is supported only in HTML5 mode and only in browsers supporting * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support * older browsers (like IE9 or Android < 4.0), don't use this method. * * @param {object=} state State object for pushState or replaceState * @return {object} state */ Location.prototype.state = function(state) { if (!arguments.length) return this.$$state; if (Location !== LocationHtml5Url || !this.$$html5) { throw $locationMinErr('nostate', 'History API state support is available only ' + 'in HTML5 mode and only in browsers supporting HTML5 History API'); } // The user might modify `stateObject` after invoking `$location.state(stateObject)` // but we're changing the $$state reference to $browser.state() during the $digest // so the modification window is narrow. this.$$state = isUndefined(state) ? null : state; return this; }; }); function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc service * @name $location * * @requires $rootElement * * @description * The $location service parses the URL in the browser address bar (based on the * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL * available to your application. Changes to the URL in the address bar are reflected into * $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/$location Developer Guide: Using $location} */ /** * @ngdoc provider * @name $locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider() { var hashPrefix = '', html5Mode = { enabled: false, requireBase: true, rewriteLinks: true }; /** * @ngdoc method * @name $locationProvider#hashPrefix * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc method * @name $locationProvider#html5Mode * @description * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported * properties: * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not * support `pushState`. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are * true, and a base tag is not present, an error will be thrown when `$location` is injected. * See the {@link guide/$location $location guide for more information} * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled, * enables/disables url rewriting for relative links. * * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isBoolean(mode)) { html5Mode.enabled = mode; return this; } else if (isObject(mode)) { if (isBoolean(mode.enabled)) { html5Mode.enabled = mode.enabled; } if (isBoolean(mode.requireBase)) { html5Mode.requireBase = mode.requireBase; } if (isBoolean(mode.rewriteLinks)) { html5Mode.rewriteLinks = mode.rewriteLinks; } return this; } else { return html5Mode; } }; /** * @ngdoc event * @name $location#$locationChangeStart * @eventType broadcast on root scope * @description * Broadcasted before a URL will change. * * This change can be prevented by calling * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more * details about event object. Upon successful change * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired. * * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when * the browser supports the HTML5 History API. * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. * @param {string=} newState New history state object * @param {string=} oldState History state object that was before it was changed. */ /** * @ngdoc event * @name $location#$locationChangeSuccess * @eventType broadcast on root scope * @description * Broadcasted after a URL was changed. * * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when * the browser supports the HTML5 History API. * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. * @param {string=} newState New history state object * @param {string=} oldState History state object that was before it was changed. */ this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', function($rootScope, $browser, $sniffer, $rootElement) { var $location, LocationMode, baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' initialUrl = $browser.url(), appBase; if (html5Mode.enabled) { if (!baseHref && html5Mode.requireBase) { throw $locationMinErr('nobase', "$location in HTML5 mode requires a <base> tag to be present!"); } appBase = serverBase(initialUrl) + (baseHref || '/'); LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; } else { appBase = stripHash(initialUrl); LocationMode = LocationHashbangUrl; } $location = new LocationMode(appBase, '#' + hashPrefix); $location.$$parseLinkUrl(initialUrl, initialUrl); $location.$$state = $browser.state(); var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; function setBrowserUrlWithFallback(url, replace, state) { var oldUrl = $location.url(); var oldState = $location.$$state; try { $browser.url(url, replace, state); // Make sure $location.state() returns referentially identical (not just deeply equal) // state object; this makes possible quick checking if the state changed in the digest // loop. Checking deep equality would be too expensive. $location.$$state = $browser.state(); } catch (e) { // Restore old values if pushState fails $location.url(oldUrl); $location.$$state = oldState; throw e; } } $rootElement.on('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (nodeName_(elm[0]) !== 'a') { // ignore rewriting if no A tag (reached root element, or no parent - removed from document) if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } var absHref = elm.prop('href'); // get the actual href attribute - see // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx var relHref = elm.attr('href') || elm.attr('xlink:href'); if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during // an animation. absHref = urlResolve(absHref.animVal).href; } // Ignore when url is started with javascript: or mailto: if (IGNORE_URI_REGEXP.test(absHref)) return; if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { if ($location.$$parseLinkUrl(absHref, relHref)) { // We do a preventDefault for all urls that are part of the angular application, // in html5mode and also without, so that we are able to abort navigation without // getting double entries in the location history. event.preventDefault(); // update location manually if ($location.absUrl() != $browser.url()) { $rootScope.$apply(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; } } } }); // rewrite hashbang url <> html5 url if ($location.absUrl() != initialUrl) { $browser.url($location.absUrl(), true); } var initializing = true; // update $location when $browser url changes $browser.onUrlChange(function(newUrl, newState) { $rootScope.$evalAsync(function() { var oldUrl = $location.absUrl(); var oldState = $location.$$state; var defaultPrevented; $location.$$parse(newUrl); $location.$$state = newState; defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, newState, oldState).defaultPrevented; // if the location was changed by a `$locationChangeStart` handler then stop // processing this location change if ($location.absUrl() !== newUrl) return; if (defaultPrevented) { $location.$$parse(oldUrl); $location.$$state = oldState; setBrowserUrlWithFallback(oldUrl, false, oldState); } else { initializing = false; afterLocationChange(oldUrl, oldState); } }); if (!$rootScope.$$phase) $rootScope.$digest(); }); // update browser $rootScope.$watch(function $locationWatch() { var oldUrl = $browser.url(); var oldState = $browser.state(); var currentReplace = $location.$$replace; var urlOrStateChanged = oldUrl !== $location.absUrl() || ($location.$$html5 && $sniffer.history && oldState !== $location.$$state); if (initializing || urlOrStateChanged) { initializing = false; $rootScope.$evalAsync(function() { var newUrl = $location.absUrl(); var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, $location.$$state, oldState).defaultPrevented; // if the location was changed by a `$locationChangeStart` handler then stop // processing this location change if ($location.absUrl() !== newUrl) return; if (defaultPrevented) { $location.$$parse(oldUrl); $location.$$state = oldState; } else { if (urlOrStateChanged) { setBrowserUrlWithFallback(newUrl, currentReplace, oldState === $location.$$state ? null : $location.$$state); } afterLocationChange(oldUrl, oldState); } }); } $location.$$replace = false; // we don't need to return anything because $evalAsync will make the digest loop dirty when // there is a change }); return $location; function afterLocationChange(oldUrl, oldState) { $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl, $location.$$state, oldState); } }]; } /** * @ngdoc service * @name $log * @requires $window * * @description * Simple service for logging. Default implementation safely writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * The default is to log `debug` messages. You can use * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. * * @example <example module="logExample"> <file name="script.js"> angular.module('logExample', []) .controller('LogController', ['$scope', '$log', function($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; }]); </file> <file name="index.html"> <div ng-controller="LogController"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </file> </example> */ /** * @ngdoc provider * @name $logProvider * @description * Use the `$logProvider` to configure how the application logs messages */ function $LogProvider() { var debug = true, self = this; /** * @ngdoc method * @name $logProvider#debugEnabled * @description * @param {boolean=} flag enable or disable debug level messages * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.debugEnabled = function(flag) { if (isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = ['$window', function($window) { return { /** * @ngdoc method * @name $log#log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name $log#info * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name $log#warn * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name $log#error * * @description * Write an error message */ error: consoleLog('error'), /** * @ngdoc method * @name $log#debug * * @description * Write a debug message */ debug: (function() { var fn = consoleLog('debug'); return function() { if (debug) { fn.apply(self, arguments); } }; }()) }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop, hasApply = false; // Note: reading logFn.apply throws an error in IE11 in IE8 document mode. // The reason behind this is that console.log has type "object" in IE8... try { hasApply = !!logFn.apply; } catch (e) {} if (hasApply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2 == null ? '' : arg2); }; } }]; } var $parseMinErr = minErr('$parse'); // Sandboxing Angular Expressions // ------------------------------ // Angular expressions are generally considered safe because these expressions only have direct // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by // obtaining a reference to native JS functions such as the Function constructor. // // As an example, consider the following Angular expression: // // {}.toString.constructor('alert("evil JS code")') // // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits // against the expression language, but not to prevent exploits that were enabled by exposing // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good // practice and therefore we are not even trying to protect against interaction with an object // explicitly exposed in this way. // // In general, it is not possible to access a Window object from an angular expression unless a // window or some DOM object that has a reference to window is published onto a Scope. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to // native objects. // // See https://docs.angularjs.org/guide/security function ensureSafeMemberName(name, fullExpression) { if (name === "__defineGetter__" || name === "__defineSetter__" || name === "__lookupGetter__" || name === "__lookupSetter__" || name === "__proto__") { throw $parseMinErr('isecfld', 'Attempting to access a disallowed field in Angular expressions! ' + 'Expression: {0}', fullExpression); } return name; } function ensureSafeObject(obj, fullExpression) { // nifty check if obj is Function that is fast and works across iframes and other contexts if (obj) { if (obj.constructor === obj) { throw $parseMinErr('isecfn', 'Referencing Function in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (// isWindow(obj) obj.window === obj) { throw $parseMinErr('isecwindow', 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (// isElement(obj) obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { throw $parseMinErr('isecdom', 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (// block Object so that we can't get hold of dangerous Object.* methods obj === Object) { throw $parseMinErr('isecobj', 'Referencing Object in Angular expressions is disallowed! Expression: {0}', fullExpression); } } return obj; } var CALL = Function.prototype.call; var APPLY = Function.prototype.apply; var BIND = Function.prototype.bind; function ensureSafeFunction(obj, fullExpression) { if (obj) { if (obj.constructor === obj) { throw $parseMinErr('isecfn', 'Referencing Function in Angular expressions is disallowed! Expression: {0}', fullExpression); } else if (obj === CALL || obj === APPLY || obj === BIND) { throw $parseMinErr('isecff', 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}', fullExpression); } } } //Keyword constants var CONSTANTS = createMap(); forEach({ 'null': function() { return null; }, 'true': function() { return true; }, 'false': function() { return false; }, 'undefined': function() {} }, function(constantGetter, name) { constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true; CONSTANTS[name] = constantGetter; }); //Not quite a constant, but can be lex/parsed the same CONSTANTS['this'] = function(self) { return self; }; CONSTANTS['this'].sharedGetter = true; //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter var OPERATORS = extend(createMap(), { '+':function(self, locals, a, b) { a=a(self, locals); b=b(self, locals); if (isDefined(a)) { if (isDefined(b)) { return a + b; } return a; } return isDefined(b) ? b : undefined;}, '-':function(self, locals, a, b) { a=a(self, locals); b=b(self, locals); return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0); }, '*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);}, '/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);}, '%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);}, '===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);}, '!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);}, '==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);}, '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);}, '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);}, '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);}, '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);}, '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);}, '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);}, '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);}, '!':function(self, locals, a) {return !a(self, locals);}, //Tokenized as operators but parsed as assignment/filters '=':true, '|':true }); var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; ///////////////////////////////////////// /** * @constructor */ var Lexer = function(options) { this.options = options; }; Lexer.prototype = { constructor: Lexer, lex: function(text) { this.text = text; this.index = 0; this.tokens = []; while (this.index < this.text.length) { var ch = this.text.charAt(this.index); if (ch === '"' || ch === "'") { this.readString(ch); } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) { this.readNumber(); } else if (this.isIdent(ch)) { this.readIdent(); } else if (this.is(ch, '(){}[].,;:?')) { this.tokens.push({index: this.index, text: ch}); this.index++; } else if (this.isWhitespace(ch)) { this.index++; } else { var ch2 = ch + this.peek(); var ch3 = ch2 + this.peek(2); var op1 = OPERATORS[ch]; var op2 = OPERATORS[ch2]; var op3 = OPERATORS[ch3]; if (op1 || op2 || op3) { var token = op3 ? ch3 : (op2 ? ch2 : ch); this.tokens.push({index: this.index, text: token, operator: true}); this.index += token.length; } else { this.throwError('Unexpected next character ', this.index, this.index + 1); } } } return this.tokens; }, is: function(ch, chars) { return chars.indexOf(ch) !== -1; }, peek: function(i) { var num = i || 1; return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; }, isNumber: function(ch) { return ('0' <= ch && ch <= '9') && typeof ch === "string"; }, isWhitespace: function(ch) { // IE treats non-breaking space as \u00A0 return (ch === ' ' || ch === '\r' || ch === '\t' || ch === '\n' || ch === '\v' || ch === '\u00A0'); }, isIdent: function(ch) { return ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' === ch || ch === '$'); }, isExpOperator: function(ch) { return (ch === '-' || ch === '+' || this.isNumber(ch)); }, throwError: function(error, start, end) { end = end || this.index; var colStr = (isDefined(start) ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' : ' ' + end); throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', error, colStr, this.text); }, readNumber: function() { var number = ''; var start = this.index; while (this.index < this.text.length) { var ch = lowercase(this.text.charAt(this.index)); if (ch == '.' || this.isNumber(ch)) { number += ch; } else { var peekCh = this.peek(); if (ch == 'e' && this.isExpOperator(peekCh)) { number += ch; } else if (this.isExpOperator(ch) && peekCh && this.isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (this.isExpOperator(ch) && (!peekCh || !this.isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { this.throwError('Invalid exponent'); } else { break; } } this.index++; } this.tokens.push({ index: start, text: number, constant: true, value: Number(number) }); }, readIdent: function() { var start = this.index; while (this.index < this.text.length) { var ch = this.text.charAt(this.index); if (!(this.isIdent(ch) || this.isNumber(ch))) { break; } this.index++; } this.tokens.push({ index: start, text: this.text.slice(start, this.index), identifier: true }); }, readString: function(quote) { var start = this.index; this.index++; var string = ''; var rawString = quote; var escape = false; while (this.index < this.text.length) { var ch = this.text.charAt(this.index); rawString += ch; if (escape) { if (ch === 'u') { var hex = this.text.substring(this.index + 1, this.index + 5); if (!hex.match(/[\da-f]{4}/i)) this.throwError('Invalid unicode escape [\\u' + hex + ']'); this.index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; string = string + (rep || ch); } escape = false; } else if (ch === '\\') { escape = true; } else if (ch === quote) { this.index++; this.tokens.push({ index: start, text: rawString, constant: true, value: string }); return; } else { string += ch; } this.index++; } this.throwError('Unterminated quote', start); } }; function isConstant(exp) { return exp.constant; } /** * @constructor */ var Parser = function(lexer, $filter, options) { this.lexer = lexer; this.$filter = $filter; this.options = options; }; Parser.ZERO = extend(function() { return 0; }, { sharedGetter: true, constant: true }); Parser.prototype = { constructor: Parser, parse: function(text) { this.text = text; this.tokens = this.lexer.lex(text); var value = this.statements(); if (this.tokens.length !== 0) { this.throwError('is an unexpected token', this.tokens[0]); } value.literal = !!value.literal; value.constant = !!value.constant; return value; }, primary: function() { var primary; if (this.expect('(')) { primary = this.filterChain(); this.consume(')'); } else if (this.expect('[')) { primary = this.arrayDeclaration(); } else if (this.expect('{')) { primary = this.object(); } else if (this.peek().identifier) { primary = this.identifier(); } else if (this.peek().constant) { primary = this.constant(); } else { this.throwError('not a primary expression', this.peek()); } var next, context; while ((next = this.expect('(', '[', '.'))) { if (next.text === '(') { primary = this.functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = this.objectIndex(primary); } else if (next.text === '.') { context = primary; primary = this.fieldAccess(primary); } else { this.throwError('IMPOSSIBLE'); } } return primary; }, throwError: function(msg, token) { throw $parseMinErr('syntax', 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); }, peekToken: function() { if (this.tokens.length === 0) throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); return this.tokens[0]; }, peek: function(e1, e2, e3, e4) { return this.peekAhead(0, e1, e2, e3, e4); }, peekAhead: function(i, e1, e2, e3, e4) { if (this.tokens.length > i) { var token = this.tokens[i]; var t = token.text; if (t === e1 || t === e2 || t === e3 || t === e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; }, expect: function(e1, e2, e3, e4) { var token = this.peek(e1, e2, e3, e4); if (token) { this.tokens.shift(); return token; } return false; }, consume: function(e1) { if (this.tokens.length === 0) { throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); } var token = this.expect(e1); if (!token) { this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); } return token; }, unaryFn: function(op, right) { var fn = OPERATORS[op]; return extend(function $parseUnaryFn(self, locals) { return fn(self, locals, right); }, { constant:right.constant, inputs: [right] }); }, binaryFn: function(left, op, right, isBranching) { var fn = OPERATORS[op]; return extend(function $parseBinaryFn(self, locals) { return fn(self, locals, left, right); }, { constant: left.constant && right.constant, inputs: !isBranching && [left, right] }); }, identifier: function() { var id = this.consume().text; //Continue reading each `.identifier` unless it is a method invocation while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) { id += this.consume().text + this.consume().text; } return CONSTANTS[id] || getterFn(id, this.options, this.text); }, constant: function() { var value = this.consume().value; return extend(function $parseConstant() { return value; }, { constant: true, literal: true }); }, statements: function() { var statements = []; while (true) { if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) statements.push(this.filterChain()); if (!this.expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return (statements.length === 1) ? statements[0] : function $parseStatements(self, locals) { var value; for (var i = 0, ii = statements.length; i < ii; i++) { value = statements[i](self, locals); } return value; }; } } }, filterChain: function() { var left = this.expression(); var token; while ((token = this.expect('|'))) { left = this.filter(left); } return left; }, filter: function(inputFn) { var fn = this.$filter(this.consume().text); var argsFn; var args; if (this.peek(':')) { argsFn = []; args = []; // we can safely reuse the array while (this.expect(':')) { argsFn.push(this.expression()); } } var inputs = [inputFn].concat(argsFn || []); return extend(function $parseFilter(self, locals) { var input = inputFn(self, locals); if (args) { args[0] = input; var i = argsFn.length; while (i--) { args[i + 1] = argsFn[i](self, locals); } return fn.apply(undefined, args); } return fn(input); }, { constant: !fn.$stateful && inputs.every(isConstant), inputs: !fn.$stateful && inputs }); }, expression: function() { return this.assignment(); }, assignment: function() { var left = this.ternary(); var right; var token; if ((token = this.expect('='))) { if (!left.assign) { this.throwError('implies assignment but [' + this.text.substring(0, token.index) + '] can not be assigned to', token); } right = this.ternary(); return extend(function $parseAssignment(scope, locals) { return left.assign(scope, right(scope, locals), locals); }, { inputs: [left, right] }); } return left; }, ternary: function() { var left = this.logicalOR(); var middle; var token; if ((token = this.expect('?'))) { middle = this.assignment(); if (this.consume(':')) { var right = this.assignment(); return extend(function $parseTernary(self, locals) { return left(self, locals) ? middle(self, locals) : right(self, locals); }, { constant: left.constant && middle.constant && right.constant }); } } return left; }, logicalOR: function() { var left = this.logicalAND(); var token; while ((token = this.expect('||'))) { left = this.binaryFn(left, token.text, this.logicalAND(), true); } return left; }, logicalAND: function() { var left = this.equality(); var token; if ((token = this.expect('&&'))) { left = this.binaryFn(left, token.text, this.logicalAND(), true); } return left; }, equality: function() { var left = this.relational(); var token; if ((token = this.expect('==','!=','===','!=='))) { left = this.binaryFn(left, token.text, this.equality()); } return left; }, relational: function() { var left = this.additive(); var token; if ((token = this.expect('<', '>', '<=', '>='))) { left = this.binaryFn(left, token.text, this.relational()); } return left; }, additive: function() { var left = this.multiplicative(); var token; while ((token = this.expect('+','-'))) { left = this.binaryFn(left, token.text, this.multiplicative()); } return left; }, multiplicative: function() { var left = this.unary(); var token; while ((token = this.expect('*','/','%'))) { left = this.binaryFn(left, token.text, this.unary()); } return left; }, unary: function() { var token; if (this.expect('+')) { return this.primary(); } else if ((token = this.expect('-'))) { return this.binaryFn(Parser.ZERO, token.text, this.unary()); } else if ((token = this.expect('!'))) { return this.unaryFn(token.text, this.unary()); } else { return this.primary(); } }, fieldAccess: function(object) { var expression = this.text; var field = this.consume().text; var getter = getterFn(field, this.options, expression); return extend(function $parseFieldAccess(scope, locals, self) { return getter(self || object(scope, locals)); }, { assign: function(scope, value, locals) { var o = object(scope, locals); if (!o) object.assign(scope, o = {}); return setter(o, field, value, expression); } }); }, objectIndex: function(obj) { var expression = this.text; var indexFn = this.expression(); this.consume(']'); return extend(function $parseObjectIndex(self, locals) { var o = obj(self, locals), i = indexFn(self, locals), v; ensureSafeMemberName(i, expression); if (!o) return undefined; v = ensureSafeObject(o[i], expression); return v; }, { assign: function(self, value, locals) { var key = ensureSafeMemberName(indexFn(self, locals), expression); // prevent overwriting of Function.constructor which would break ensureSafeObject check var o = ensureSafeObject(obj(self, locals), expression); if (!o) obj.assign(self, o = {}); return o[key] = value; } }); }, functionCall: function(fnGetter, contextGetter) { var argsFn = []; if (this.peekToken().text !== ')') { do { argsFn.push(this.expression()); } while (this.expect(',')); } this.consume(')'); var expressionText = this.text; // we can safely reuse the array across invocations var args = argsFn.length ? [] : null; return function $parseFunctionCall(scope, locals) { var context = contextGetter ? contextGetter(scope, locals) : scope; var fn = fnGetter(scope, locals, context) || noop; if (args) { var i = argsFn.length; while (i--) { args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText); } } ensureSafeObject(context, expressionText); ensureSafeFunction(fn, expressionText); // IE stupidity! (IE doesn't have apply for some native functions) var v = fn.apply ? fn.apply(context, args) : fn(args[0], args[1], args[2], args[3], args[4]); return ensureSafeObject(v, expressionText); }; }, // This is used with json array declaration arrayDeclaration: function() { var elementFns = []; if (this.peekToken().text !== ']') { do { if (this.peek(']')) { // Support trailing commas per ES5.1. break; } elementFns.push(this.expression()); } while (this.expect(',')); } this.consume(']'); return extend(function $parseArrayLiteral(self, locals) { var array = []; for (var i = 0, ii = elementFns.length; i < ii; i++) { array.push(elementFns[i](self, locals)); } return array; }, { literal: true, constant: elementFns.every(isConstant), inputs: elementFns }); }, object: function() { var keys = [], valueFns = []; if (this.peekToken().text !== '}') { do { if (this.peek('}')) { // Support trailing commas per ES5.1. break; } var token = this.consume(); if (token.constant) { keys.push(token.value); } else if (token.identifier) { keys.push(token.text); } else { this.throwError("invalid key", token); } this.consume(':'); valueFns.push(this.expression()); } while (this.expect(',')); } this.consume('}'); return extend(function $parseObjectLiteral(self, locals) { var object = {}; for (var i = 0, ii = valueFns.length; i < ii; i++) { object[keys[i]] = valueFns[i](self, locals); } return object; }, { literal: true, constant: valueFns.every(isConstant), inputs: valueFns }); } }; ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue, fullExp) { ensureSafeObject(obj, fullExp); var element = path.split('.'), key; for (var i = 0; element.length > 1; i++) { key = ensureSafeMemberName(element.shift(), fullExp); var propertyObj = ensureSafeObject(obj[key], fullExp); if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } key = ensureSafeMemberName(element.shift(), fullExp); ensureSafeObject(obj[key], fullExp); obj[key] = setValue; return setValue; } var getterFnCacheDefault = createMap(); var getterFnCacheExpensive = createMap(); function isPossiblyDangerousMemberName(name) { return name == 'constructor'; } /** * Implementation of the "Black Hole" variant from: * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) { ensureSafeMemberName(key0, fullExp); ensureSafeMemberName(key1, fullExp); ensureSafeMemberName(key2, fullExp); ensureSafeMemberName(key3, fullExp); ensureSafeMemberName(key4, fullExp); var eso = function(o) { return ensureSafeObject(o, fullExp); }; var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity; var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity; var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity; var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity; var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity; return function cspSafeGetter(scope, locals) { var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; if (pathVal == null) return pathVal; pathVal = eso0(pathVal[key0]); if (!key1) return pathVal; if (pathVal == null) return undefined; pathVal = eso1(pathVal[key1]); if (!key2) return pathVal; if (pathVal == null) return undefined; pathVal = eso2(pathVal[key2]); if (!key3) return pathVal; if (pathVal == null) return undefined; pathVal = eso3(pathVal[key3]); if (!key4) return pathVal; if (pathVal == null) return undefined; pathVal = eso4(pathVal[key4]); return pathVal; }; } function getterFnWithEnsureSafeObject(fn, fullExpression) { return function(s, l) { return fn(s, l, ensureSafeObject, fullExpression); }; } function getterFn(path, options, fullExp) { var expensiveChecks = options.expensiveChecks; var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault); var fn = getterFnCache[path]; if (fn) return fn; var pathKeys = path.split('.'), pathKeysLength = pathKeys.length; // http://jsperf.com/angularjs-parse-getter/6 if (options.csp) { if (pathKeysLength < 6) { fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks); } else { fn = function cspSafeGetter(scope, locals) { var i = 0, val; do { val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], fullExp, expensiveChecks)(scope, locals); locals = undefined; // clear after first iteration scope = val; } while (i < pathKeysLength); return val; }; } } else { var code = ''; if (expensiveChecks) { code += 's = eso(s, fe);\nl = eso(l, fe);\n'; } var needsEnsureSafeObject = expensiveChecks; forEach(pathKeys, function(key, index) { ensureSafeMemberName(key, fullExp); var lookupJs = (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key; if (expensiveChecks || isPossiblyDangerousMemberName(key)) { lookupJs = 'eso(' + lookupJs + ', fe)'; needsEnsureSafeObject = true; } code += 'if(s == null) return undefined;\n' + 's=' + lookupJs + ';\n'; }); code += 'return s;'; /* jshint -W054 */ var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject /* jshint +W054 */ evaledFnGetter.toString = valueFn(code); if (needsEnsureSafeObject) { evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp); } fn = evaledFnGetter; } fn.sharedGetter = true; fn.assign = function(self, value) { return setter(self, path, value, path); }; getterFnCache[path] = fn; return fn; } var objectValueOf = Object.prototype.valueOf; function getValueOf(value) { return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value); } /////////////////////////////////// /** * @ngdoc service * @name $parse * @kind function * * @description * * Converts Angular {@link guide/expression expression} into a function. * * ```js * var getter = $parse('user.name'); * var setter = getter.assign; * var context = {user:{name:'angular'}}; * var locals = {user:{name:'local'}}; * * expect(getter(context)).toEqual('angular'); * setter(context, 'newValue'); * expect(context.user.name).toEqual('newValue'); * expect(getter(context, locals)).toEqual('local'); * ``` * * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. * * The returned function also has the following properties: * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript * literal. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript * constant literals. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be * set to a function to change its value on the given context. * */ /** * @ngdoc provider * @name $parseProvider * * @description * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} * service. */ function $ParseProvider() { var cacheDefault = createMap(); var cacheExpensive = createMap(); this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { var $parseOptions = { csp: $sniffer.csp, expensiveChecks: false }, $parseOptionsExpensive = { csp: $sniffer.csp, expensiveChecks: true }; function wrapSharedExpression(exp) { var wrapped = exp; if (exp.sharedGetter) { wrapped = function $parseWrapper(self, locals) { return exp(self, locals); }; wrapped.literal = exp.literal; wrapped.constant = exp.constant; wrapped.assign = exp.assign; } return wrapped; } return function $parse(exp, interceptorFn, expensiveChecks) { var parsedExpression, oneTime, cacheKey; switch (typeof exp) { case 'string': cacheKey = exp = exp.trim(); var cache = (expensiveChecks ? cacheExpensive : cacheDefault); parsedExpression = cache[cacheKey]; if (!parsedExpression) { if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { oneTime = true; exp = exp.substring(2); } var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions; var lexer = new Lexer(parseOptions); var parser = new Parser(lexer, $filter, parseOptions); parsedExpression = parser.parse(exp); if (parsedExpression.constant) { parsedExpression.$$watchDelegate = constantWatchDelegate; } else if (oneTime) { //oneTime is not part of the exp passed to the Parser so we may have to //wrap the parsedExpression before adding a $$watchDelegate parsedExpression = wrapSharedExpression(parsedExpression); parsedExpression.$$watchDelegate = parsedExpression.literal ? oneTimeLiteralWatchDelegate : oneTimeWatchDelegate; } else if (parsedExpression.inputs) { parsedExpression.$$watchDelegate = inputsWatchDelegate; } cache[cacheKey] = parsedExpression; } return addInterceptor(parsedExpression, interceptorFn); case 'function': return addInterceptor(exp, interceptorFn); default: return addInterceptor(noop, interceptorFn); } }; function collectExpressionInputs(inputs, list) { for (var i = 0, ii = inputs.length; i < ii; i++) { var input = inputs[i]; if (!input.constant) { if (input.inputs) { collectExpressionInputs(input.inputs, list); } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better? list.push(input); } } } return list; } function expressionInputDirtyCheck(newValue, oldValueOfValue) { if (newValue == null || oldValueOfValue == null) { // null/undefined return newValue === oldValueOfValue; } if (typeof newValue === 'object') { // attempt to convert the value to a primitive type // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can // be cheaply dirty-checked newValue = getValueOf(newValue); if (typeof newValue === 'object') { // objects/arrays are not supported - deep-watching them would be too expensive return false; } // fall-through to the primitive equality check } //Primitive or NaN return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue); } function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) { var inputExpressions = parsedExpression.$$inputs || (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, [])); var lastResult; if (inputExpressions.length === 1) { var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails inputExpressions = inputExpressions[0]; return scope.$watch(function expressionInputWatch(scope) { var newInputValue = inputExpressions(scope); if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) { lastResult = parsedExpression(scope); oldInputValue = newInputValue && getValueOf(newInputValue); } return lastResult; }, listener, objectEquality); } var oldInputValueOfValues = []; for (var i = 0, ii = inputExpressions.length; i < ii; i++) { oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails } return scope.$watch(function expressionInputsWatch(scope) { var changed = false; for (var i = 0, ii = inputExpressions.length; i < ii; i++) { var newInputValue = inputExpressions[i](scope); if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) { oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue); } } if (changed) { lastResult = parsedExpression(scope); } return lastResult; }, listener, objectEquality); } function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) { var unwatch, lastValue; return unwatch = scope.$watch(function oneTimeWatch(scope) { return parsedExpression(scope); }, function oneTimeListener(value, old, scope) { lastValue = value; if (isFunction(listener)) { listener.apply(this, arguments); } if (isDefined(value)) { scope.$$postDigest(function() { if (isDefined(lastValue)) { unwatch(); } }); } }, objectEquality); } function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) { var unwatch, lastValue; return unwatch = scope.$watch(function oneTimeWatch(scope) { return parsedExpression(scope); }, function oneTimeListener(value, old, scope) { lastValue = value; if (isFunction(listener)) { listener.call(this, value, old, scope); } if (isAllDefined(value)) { scope.$$postDigest(function() { if (isAllDefined(lastValue)) unwatch(); }); } }, objectEquality); function isAllDefined(value) { var allDefined = true; forEach(value, function(val) { if (!isDefined(val)) allDefined = false; }); return allDefined; } } function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { var unwatch; return unwatch = scope.$watch(function constantWatch(scope) { return parsedExpression(scope); }, function constantListener(value, old, scope) { if (isFunction(listener)) { listener.apply(this, arguments); } unwatch(); }, objectEquality); } function addInterceptor(parsedExpression, interceptorFn) { if (!interceptorFn) return parsedExpression; var watchDelegate = parsedExpression.$$watchDelegate; var regularWatch = watchDelegate !== oneTimeLiteralWatchDelegate && watchDelegate !== oneTimeWatchDelegate; var fn = regularWatch ? function regularInterceptedExpression(scope, locals) { var value = parsedExpression(scope, locals); return interceptorFn(value, scope, locals); } : function oneTimeInterceptedExpression(scope, locals) { var value = parsedExpression(scope, locals); var result = interceptorFn(value, scope, locals); // we only return the interceptor's result if the // initial value is defined (for bind-once) return isDefined(value) ? result : value; }; // Propagate $$watchDelegates other then inputsWatchDelegate if (parsedExpression.$$watchDelegate && parsedExpression.$$watchDelegate !== inputsWatchDelegate) { fn.$$watchDelegate = parsedExpression.$$watchDelegate; } else if (!interceptorFn.$stateful) { // If there is an interceptor, but no watchDelegate then treat the interceptor like // we treat filters - it is assumed to be a pure function unless flagged with $stateful fn.$$watchDelegate = inputsWatchDelegate; fn.inputs = [parsedExpression]; } return fn; } }]; } /** * @ngdoc service * @name $q * @requires $rootScope * * @description * A service that helps you run functions asynchronously, and use their return values (or exceptions) * when they are done processing. * * This is an implementation of promises/deferred objects inspired by * [Kris Kowal's Q](https://github.com/kriskowal/q). * * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred * implementations, and the other which resembles ES6 promises to some degree. * * # $q constructor * * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver` * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony, * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). * * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are * available yet. * * It can be used like so: * * ```js * // for the purpose of this example let's assume that variables `$q` and `okToGreet` * // are available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * // perform some asynchronous operation, resolve or reject the promise when appropriate. * return $q(function(resolve, reject) { * setTimeout(function() { * if (okToGreet(name)) { * resolve('Hello, ' + name + '!'); * } else { * reject('Greeting ' + name + ' is not allowed.'); * } * }, 1000); * }); * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }); * ``` * * Note: progress/notify callbacks are not currently supported via the ES6-style interface. * * However, the more traditional CommonJS-style usage is still available, and documented below. * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise APIs are to * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. * * ```js * // for the purpose of this example let's assume that variables `$q` and `okToGreet` * // are available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * deferred.notify('About to greet ' + name + '.'); * * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }, function(update) { * alert('Got notification: ' + update); * }); * ``` * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of guarantees that promise and deferred APIs make, see * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as APIs * that can be used for signaling the successful or unsuccessful completion, as well as the status * of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called * multiple times before the promise is either resolved or rejected. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously * as soon as the result is available. The callbacks are called with a single argument: the result * or rejection reason. Additionally, the notify callback may be called zero or more times to * provide a progress indication, before the promise is resolved or rejected. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback`, `errorCallback`. It also notifies via the return value of the * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback * method. * * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` * * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise, * but to do so without modifying the final value. This is useful to release resources or do some * clean-up that needs to be done whether the promise was rejected or resolved. See the [full * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for * more information. * * # Chaining promises * * Because calling the `then` method of a promise returns a new derived promise, it is easily * possible to create a chain of promises: * * ```js * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and its value * // will be the result of promiseA incremented by 1 * ``` * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful APIs like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are two main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. * * # Testing * * ```js * it('should simulate promise', inject(function($q, $rootScope) { * var deferred = $q.defer(); * var promise = deferred.promise; * var resolvedValue; * * promise.then(function(value) { resolvedValue = value; }); * expect(resolvedValue).toBeUndefined(); * * // Simulate resolving of promise * deferred.resolve(123); * // Note that the 'then' function does not get called synchronously. * // This is because we want the promise API to always be async, whether or not * // it got called synchronously or asynchronously. * expect(resolvedValue).toBeUndefined(); * * // Propagate promise resolution to 'then' functions using $apply(). * $rootScope.$apply(); * expect(resolvedValue).toEqual(123); * })); * ``` * * @param {function(function, function)} resolver Function which is responsible for resolving or * rejecting the newly created promise. The first parameter is a function which resolves the * promise, the second parameter is a function which rejects the promise. * * @returns {Promise} The newly created promise. */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } function $$QProvider() { this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) { return qFactory(function(callback) { $browser.defer(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { var $qMinErr = minErr('$q', TypeError); function callOnce(self, resolveFn, rejectFn) { var called = false; function wrap(fn) { return function(value) { if (called) return; called = true; fn.call(self, value); }; } return [wrap(resolveFn), wrap(rejectFn)]; } /** * @ngdoc method * @name ng.$q#defer * @kind function * * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { return new Deferred(); }; function Promise() { this.$$state = { status: 0 }; } Promise.prototype = { then: function(onFulfilled, onRejected, progressBack) { var result = new Deferred(); this.$$state.pending = this.$$state.pending || []; this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]); if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); return result.promise; }, "catch": function(callback) { return this.then(null, callback); }, "finally": function(callback, progressBack) { return this.then(function(value) { return handleCallback(value, true, callback); }, function(error) { return handleCallback(error, false, callback); }, progressBack); } }; //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native function simpleBind(context, fn) { return function(value) { fn.call(context, value); }; } function processQueue(state) { var fn, promise, pending; pending = state.pending; state.processScheduled = false; state.pending = undefined; for (var i = 0, ii = pending.length; i < ii; ++i) { promise = pending[i][0]; fn = pending[i][state.status]; try { if (isFunction(fn)) { promise.resolve(fn(state.value)); } else if (state.status === 1) { promise.resolve(state.value); } else { promise.reject(state.value); } } catch (e) { promise.reject(e); exceptionHandler(e); } } } function scheduleProcessQueue(state) { if (state.processScheduled || !state.pending) return; state.processScheduled = true; nextTick(function() { processQueue(state); }); } function Deferred() { this.promise = new Promise(); //Necessary to support unbound execution :/ this.resolve = simpleBind(this, this.resolve); this.reject = simpleBind(this, this.reject); this.notify = simpleBind(this, this.notify); } Deferred.prototype = { resolve: function(val) { if (this.promise.$$state.status) return; if (val === this.promise) { this.$$reject($qMinErr( 'qcycle', "Expected promise to be resolved with value other than itself '{0}'", val)); } else { this.$$resolve(val); } }, $$resolve: function(val) { var then, fns; fns = callOnce(this, this.$$resolve, this.$$reject); try { if ((isObject(val) || isFunction(val))) then = val && val.then; if (isFunction(then)) { this.promise.$$state.status = -1; then.call(val, fns[0], fns[1], this.notify); } else { this.promise.$$state.value = val; this.promise.$$state.status = 1; scheduleProcessQueue(this.promise.$$state); } } catch (e) { fns[1](e); exceptionHandler(e); } }, reject: function(reason) { if (this.promise.$$state.status) return; this.$$reject(reason); }, $$reject: function(reason) { this.promise.$$state.value = reason; this.promise.$$state.status = 2; scheduleProcessQueue(this.promise.$$state); }, notify: function(progress) { var callbacks = this.promise.$$state.pending; if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) { nextTick(function() { var callback, result; for (var i = 0, ii = callbacks.length; i < ii; i++) { result = callbacks[i][0]; callback = callbacks[i][3]; try { result.notify(isFunction(callback) ? callback(progress) : progress); } catch (e) { exceptionHandler(e); } } }); } } }; /** * @ngdoc method * @name $q#reject * @kind function * * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * ```js * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * ``` * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { var result = new Deferred(); result.reject(reason); return result.promise; }; var makePromise = function makePromise(value, resolved) { var result = new Deferred(); if (resolved) { result.resolve(value); } else { result.reject(value); } return result.promise; }; var handleCallback = function handleCallback(value, isResolved, callback) { var callbackOutput = null; try { if (isFunction(callback)) callbackOutput = callback(); } catch (e) { return makePromise(e, false); } if (isPromiseLike(callbackOutput)) { return callbackOutput.then(function() { return makePromise(value, isResolved); }, function(error) { return makePromise(error, false); }); } else { return makePromise(value, isResolved); } }; /** * @ngdoc method * @name $q#when * @kind function * * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with an object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a promise of the passed value or promise */ var when = function(value, callback, errback, progressBack) { var result = new Deferred(); result.resolve(value); return result.promise.then(callback, errback, progressBack); }; /** * @ngdoc method * @name $q#all * @kind function * * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, * each value corresponding to the promise at the same index/key in the `promises` array/hash. * If any of the promises is resolved with a rejection, this resulting promise will be rejected * with the same rejection value. */ function all(promises) { var deferred = new Deferred(), counter = 0, results = isArray(promises) ? [] : {}; forEach(promises, function(promise, key) { counter++; when(promise).then(function(value) { if (results.hasOwnProperty(key)) return; results[key] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (results.hasOwnProperty(key)) return; deferred.reject(reason); }); }); if (counter === 0) { deferred.resolve(results); } return deferred.promise; } var $Q = function Q(resolver) { if (!isFunction(resolver)) { throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver); } if (!(this instanceof Q)) { // More useful when $Q is the Promise itself. return new Q(resolver); } var deferred = new Deferred(); function resolveFn(value) { deferred.resolve(value); } function rejectFn(reason) { deferred.reject(reason); } resolver(resolveFn, rejectFn); return deferred.promise; }; $Q.defer = defer; $Q.reject = reject; $Q.when = when; $Q.all = all; return $Q; } function $$RAFProvider() { //rAF this.$get = ['$window', '$timeout', function($window, $timeout) { var requestAnimationFrame = $window.requestAnimationFrame || $window.webkitRequestAnimationFrame || $window.mozRequestAnimationFrame; var cancelAnimationFrame = $window.cancelAnimationFrame || $window.webkitCancelAnimationFrame || $window.mozCancelAnimationFrame || $window.webkitCancelRequestAnimationFrame; var rafSupported = !!requestAnimationFrame; var raf = rafSupported ? function(fn) { var id = requestAnimationFrame(fn); return function() { cancelAnimationFrame(id); }; } : function(fn) { var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 return function() { $timeout.cancel(timer); }; }; raf.supported = rafSupported; return raf; }]; } /** * DESIGN NOTES * * The design decisions behind the scope are heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive in terms of speed as well as memory: * - No closures, instead use prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the beginning (unshift) instead of at the end (push) * * Child scopes are created and removed often * - Using an array would be slow since inserts in middle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc provider * @name $rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc method * @name $rootScopeProvider#digestTtl * @description * * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * In complex applications it's possible that the dependencies between `$watch`s will result in * several digest iterations. However if an application needs more than the default 10 digest * iterations for its model to stabilize then you should investigate what is causing the model to * continuously change during the digest. * * Increasing the TTL could have performance implications, so you should not change it without * proper justification. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc service * @name $rootScope * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are descendant scopes of the root scope. Scopes provide separation * between the model and the view, via a mechanism for watching the model for changes. * They also provide an event emission/broadcast and subscription facility. See the * {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider() { var TTL = 10; var $rootScopeMinErr = minErr('$rootScope'); var lastDirtyWatch = null; var applyAsyncId = null; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', function($injector, $exceptionHandler, $parse, $browser) { /** * @ngdoc type * @name $rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link auto.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * ```html * <file src="./test/ng/rootScopeSpec.js" tag="docs1" /> * ``` * * # Inheritance * A scope can inherit from a parent scope, as in this example: * ```js var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * ``` * * When interacting with `Scope` in tests, additional helper methods are available on the * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional * details. * * * @param {Object.<string, function()>=} providers Map of service factory which need to be * provided for the current scope. Defaults to {@link ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy * when unit-testing and having the need to override a default * service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this.$root = this; this.$$destroyed = false; this.$$listeners = {}; this.$$listenerCount = {}; this.$$isolateBindings = null; } /** * @ngdoc property * @name $rootScope.Scope#$id * * @description * Unique scope ID (monotonically increasing) useful for debugging. */ /** * @ngdoc property * @name $rootScope.Scope#$parent * * @description * Reference to the parent scope. */ /** * @ngdoc property * @name $rootScope.Scope#$root * * @description * Reference to the root scope. */ Scope.prototype = { constructor: Scope, /** * @ngdoc method * @name $rootScope.Scope#$new * @kind function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is * desired for the scope and its child scopes to be permanently detached from the parent and * thus stop participating in model change detection and listener notification by invoking. * * @param {boolean} isolate If true, then the scope does not prototypically inherit from the * parent scope. The scope is isolated, as it can not see parent scope properties. * When creating widgets, it is useful for the widget to not accidentally read parent * state. * * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent` * of the newly created scope. Defaults to `this` scope if not provided. * This is used when creating a transclude scope to correctly place it * in the scope hierarchy while maintaining the correct prototypical * inheritance. * * @returns {Object} The newly created child scope. * */ $new: function(isolate, parent) { var child; parent = parent || this; if (isolate) { child = new Scope(); child.$root = this.$root; } else { // Only create a child scope class if somebody asks for one, // but cache it to allow the VM to optimize lookups. if (!this.$$ChildScope) { this.$$ChildScope = function ChildScope() { this.$$watchers = this.$$nextSibling = this.$$childHead = this.$$childTail = null; this.$$listeners = {}; this.$$listenerCount = {}; this.$id = nextUid(); this.$$ChildScope = null; }; this.$$ChildScope.prototype = this; } child = new this.$$ChildScope(); } child.$parent = parent; child.$$prevSibling = parent.$$childTail; if (parent.$$childHead) { parent.$$childTail.$$nextSibling = child; parent.$$childTail = child; } else { parent.$$childHead = parent.$$childTail = child; } // When the new scope is not isolated or we inherit from `this`, and // the parent scope is destroyed, the property `$$destroyed` is inherited // prototypically. In all other cases, this property needs to be set // when the parent scope is destroyed. // The listener needs to be added after the parent is set if (isolate || parent != this) child.$on('$destroy', destroyChild); return child; function destroyChild() { child.$$destroyed = true; } }, /** * @ngdoc method * @name $rootScope.Scope#$watch * @kind function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest * $digest()} and should return the value that will be watched. (Since * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the * `watchExpression` can execute multiple times per * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression` are not equal (with the exception of the initial run, * see below). Inequality is determined according to reference inequality, * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) * via the `!==` Javascript operator, unless `objectEquality == true` * (see next point) * - When `objectEquality == true`, inequality of the `watchExpression` is determined * according to the {@link angular.equals} function. To save the value of the object for * later comparison, the {@link angular.copy} function is used. This therefore means that * watching complex objects will have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. * This is achieved by rerunning the watchers until no changes are detected. The rerun * iteration limit is 10 to prevent an infinite loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a * change is detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * * # Example * ```js // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // the listener is always called during the first $digest loop after it was registered expect(scope.counter).toEqual(1); scope.$digest(); // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(2); // Using a function as a watchExpression var food; scope.foodCounter = 0; expect(scope.foodCounter).toEqual(0); scope.$watch( // This function returns the value being watched. It is called for each turn of the $digest loop function() { return food; }, // This is the change listener, called when the value returned from the above function changes function(newValue, oldValue) { if ( newValue !== oldValue ) { // Only increment the counter if the value changed scope.foodCounter = scope.foodCounter + 1; } } ); // No digest has been run so the counter will be zero expect(scope.foodCounter).toEqual(0); // Run the digest but since food has not changed count will still be zero scope.$digest(); expect(scope.foodCounter).toEqual(0); // Update food and run digest. Now the counter will increment food = 'cheeseburger'; scope.$digest(); expect(scope.foodCounter).toEqual(1); * ``` * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers * a call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value * of `watchExpression` changes. * * - `newVal` contains the current value of the `watchExpression` * - `oldVal` contains the previous value of the `watchExpression` * - `scope` refers to the current scope * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of * comparing for reference equality. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var get = $parse(watchExp); if (get.$$watchDelegate) { return get.$$watchDelegate(this, listener, objectEquality, get); } var scope = this, array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; lastDirtyWatch = null; if (!isFunction(listener)) { watcher.fn = noop; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function deregisterWatch() { arrayRemove(array, watcher); lastDirtyWatch = null; }; }, /** * @ngdoc method * @name $rootScope.Scope#$watchGroup * @kind function * * @description * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. * If any one expression in the collection changes the `listener` is executed. * * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every * call to $digest() to see if any items changes. * - The `listener` is called whenever any expression in the `watchExpressions` array changes. * * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually * watched using {@link ng.$rootScope.Scope#$watch $watch()} * * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any * expression in `watchExpressions` changes * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching * those of `watchExpression` * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching * those of `watchExpression` * The `scope` refers to the current scope. * @returns {function()} Returns a de-registration function for all listeners. */ $watchGroup: function(watchExpressions, listener) { var oldValues = new Array(watchExpressions.length); var newValues = new Array(watchExpressions.length); var deregisterFns = []; var self = this; var changeReactionScheduled = false; var firstRun = true; if (!watchExpressions.length) { // No expressions means we call the listener ASAP var shouldCall = true; self.$evalAsync(function() { if (shouldCall) listener(newValues, newValues, self); }); return function deregisterWatchGroup() { shouldCall = false; }; } if (watchExpressions.length === 1) { // Special case size of one return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) { newValues[0] = value; oldValues[0] = oldValue; listener(newValues, (value === oldValue) ? newValues : oldValues, scope); }); } forEach(watchExpressions, function(expr, i) { var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) { newValues[i] = value; oldValues[i] = oldValue; if (!changeReactionScheduled) { changeReactionScheduled = true; self.$evalAsync(watchGroupAction); } }); deregisterFns.push(unwatchFn); }); function watchGroupAction() { changeReactionScheduled = false; if (firstRun) { firstRun = false; listener(newValues, newValues, self); } else { listener(newValues, oldValues, self); } } return function deregisterWatchGroup() { while (deregisterFns.length) { deregisterFns.shift()(); } }; }, /** * @ngdoc method * @name $rootScope.Scope#$watchCollection * @kind function * * @description * Shallow watches the properties of an object and fires whenever any of the properties change * (for arrays, this implies watching the array items; for object maps, this implies watching * the properties). If a change is detected, the `listener` callback is fired. * * - The `obj` collection is observed via standard $watch operation and is examined on every * call to $digest() to see if any items have been added, removed, or moved. * - The `listener` is called whenever anything within the `obj` has changed. Examples include * adding, removing, and moving items belonging to an object or array. * * * # Example * ```js $scope.names = ['igor', 'matias', 'misko', 'james']; $scope.dataCount = 4; $scope.$watchCollection('names', function(newNames, oldNames) { $scope.dataCount = newNames.length; }); expect($scope.dataCount).toEqual(4); $scope.$digest(); //still at 4 ... no changes expect($scope.dataCount).toEqual(4); $scope.names.pop(); $scope.$digest(); //now there's been a change expect($scope.dataCount).toEqual(3); * ``` * * * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The * expression value should evaluate to an object or an array which is observed on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the * collection will trigger a call to the `listener`. * * @param {function(newCollection, oldCollection, scope)} listener a callback function called * when a change is detected. * - The `newCollection` object is the newly modified data obtained from the `obj` expression * - The `oldCollection` object is a copy of the former collection data. * Due to performance considerations, the`oldCollection` value is computed only if the * `listener` function declares two or more arguments. * - The `scope` argument refers to the current scope. * * @returns {function()} Returns a de-registration function for this listener. When the * de-registration function is executed, the internal watch operation is terminated. */ $watchCollection: function(obj, listener) { $watchCollectionInterceptor.$stateful = true; var self = this; // the current value, updated on each dirty-check run var newValue; // a shallow copy of the newValue from the last dirty-check run, // updated to match newValue during dirty-check run var oldValue; // a shallow copy of the newValue from when the last change happened var veryOldValue; // only track veryOldValue if the listener is asking for it var trackVeryOldValue = (listener.length > 1); var changeDetected = 0; var changeDetector = $parse(obj, $watchCollectionInterceptor); var internalArray = []; var internalObject = {}; var initRun = true; var oldLength = 0; function $watchCollectionInterceptor(_value) { newValue = _value; var newLength, key, bothNaN, newItem, oldItem; // If the new value is undefined, then return undefined as the watch may be a one-time watch if (isUndefined(newValue)) return; if (!isObject(newValue)) { // if primitive if (oldValue !== newValue) { oldValue = newValue; changeDetected++; } } else if (isArrayLike(newValue)) { if (oldValue !== internalArray) { // we are transitioning from something which was not an array into array. oldValue = internalArray; oldLength = oldValue.length = 0; changeDetected++; } newLength = newValue.length; if (oldLength !== newLength) { // if lengths do not match we need to trigger change notification changeDetected++; oldValue.length = oldLength = newLength; } // copy the items to oldValue and look for changes. for (var i = 0; i < newLength; i++) { oldItem = oldValue[i]; newItem = newValue[i]; bothNaN = (oldItem !== oldItem) && (newItem !== newItem); if (!bothNaN && (oldItem !== newItem)) { changeDetected++; oldValue[i] = newItem; } } } else { if (oldValue !== internalObject) { // we are transitioning from something which was not an object into object. oldValue = internalObject = {}; oldLength = 0; changeDetected++; } // copy the items to oldValue and look for changes. newLength = 0; for (key in newValue) { if (newValue.hasOwnProperty(key)) { newLength++; newItem = newValue[key]; oldItem = oldValue[key]; if (key in oldValue) { bothNaN = (oldItem !== oldItem) && (newItem !== newItem); if (!bothNaN && (oldItem !== newItem)) { changeDetected++; oldValue[key] = newItem; } } else { oldLength++; oldValue[key] = newItem; changeDetected++; } } } if (oldLength > newLength) { // we used to have more keys, need to find them and destroy them. changeDetected++; for (key in oldValue) { if (!newValue.hasOwnProperty(key)) { oldLength--; delete oldValue[key]; } } } } return changeDetected; } function $watchCollectionAction() { if (initRun) { initRun = false; listener(newValue, newValue, self); } else { listener(newValue, veryOldValue, self); } // make a copy for the next time a collection is changed if (trackVeryOldValue) { if (!isObject(newValue)) { //primitive veryOldValue = newValue; } else if (isArrayLike(newValue)) { veryOldValue = new Array(newValue.length); for (var i = 0; i < newValue.length; i++) { veryOldValue[i] = newValue[i]; } } else { // if object veryOldValue = {}; for (var key in newValue) { if (hasOwnProperty.call(newValue, key)) { veryOldValue[key] = newValue[key]; } } } } } return this.$watch(changeDetector, $watchCollectionAction); }, /** * @ngdoc method * @name $rootScope.Scope#$digest * @kind function * * @description * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} * until no more listeners are firing. This means that it is possible to get into an infinite * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of * iterations exceeds 10. * * Usually, you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. * * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. * * # Example * ```js var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // the listener is always called during the first $digest loop after it was registered expect(scope.counter).toEqual(1); scope.$digest(); // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(2); * ``` * */ $digest: function() { var watch, value, last, watchers, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, logMsg, asyncTask; beginPhase('$digest'); // Check for changes to browser url that happened in sync before the call to $digest $browser.$$checkUrlChange(); if (this === $rootScope && applyAsyncId !== null) { // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then // cancel the scheduled $apply and flush the queue of expressions to be evaluated. $browser.defer.cancel(applyAsyncId); flushApplyAsync(); } lastDirtyWatch = null; do { // "while dirty" loop dirty = false; current = target; while (asyncQueue.length) { try { asyncTask = asyncQueue.shift(); asyncTask.scope.$eval(asyncTask.expression); } catch (e) { $exceptionHandler(e); } lastDirtyWatch = null; } traverseScopesLoop: do { // "traverse the scopes" loop if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if (watch) { if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value === 'number' && typeof last === 'number' && isNaN(value) && isNaN(last)))) { dirty = true; lastDirtyWatch = watch; watch.last = watch.eq ? copy(value, null) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; watchLog[logIdx].push({ msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp, newVal: value, oldVal: last }); } } else if (watch === lastDirtyWatch) { // If the most recently dirty watcher is now clean, short circuit since the remaining watchers // have already been tested. dirty = false; break traverseScopesLoop; } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while (current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); // `break traverseScopesLoop;` takes us to here if ((dirty || asyncQueue.length) && !(ttl--)) { clearPhase(); throw $rootScopeMinErr('infdig', '{0} $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: {1}', TTL, watchLog); } } while (dirty || asyncQueue.length); clearPhase(); while (postDigestQueue.length) { try { postDigestQueue.shift()(); } catch (e) { $exceptionHandler(e); } } }, /** * @ngdoc event * @name $rootScope.Scope#$destroy * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. * * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to * clean up DOM bindings before an element is removed from the DOM. */ /** * @ngdoc method * @name $rootScope.Scope#$destroy * @kind function * * @description * Removes the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it a chance to * perform any necessary cleanup. * * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to * clean up DOM bindings before an element is removed from the DOM. */ $destroy: function() { // we can't destroy the root scope or a scope that has been already destroyed if (this.$$destroyed) return; var parent = this.$parent; this.$broadcast('$destroy'); this.$$destroyed = true; if (this === $rootScope) return; for (var eventName in this.$$listenerCount) { decrementListenerCount(this, this.$$listenerCount[eventName], eventName); } // sever all the references to parent scopes (after this cleanup, the current scope should // not be retained by any of our references and should be eligible for garbage collection) if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; // Disable listeners, watchers and apply/digest methods this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop; this.$on = this.$watch = this.$watchGroup = function() { return noop; }; this.$$listeners = {}; // All of the code below is bogus code that works around V8's memory leak via optimized code // and inline caches. // // see: // - https://code.google.com/p/v8/issues/detail?id=2073#c26 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = this.$root = this.$$watchers = null; }, /** * @ngdoc method * @name $rootScope.Scope#$eval * @kind function * * @description * Executes the `expression` on the current scope and returns the result. Any exceptions in * the expression are propagated (uncaught). This is useful when evaluating Angular * expressions. * * # Example * ```js var scope = ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * ``` * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @param {(object)=} locals Local variables object, useful for overriding values in scope. * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc method * @name $rootScope.Scope#$evalAsync * @kind function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only * that: * * - it will execute after the function that scheduled the evaluation (preferably before DOM * rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle * will be scheduled. However, it is encouraged to always call code that changes the model * from within an `$apply` call. That includes code evaluated via `$evalAsync`. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { // if we are outside of an $digest loop and this is the first time we are scheduling async // task also schedule async auto-flush if (!$rootScope.$$phase && !asyncQueue.length) { $browser.defer(function() { if (asyncQueue.length) { $rootScope.$digest(); } }); } asyncQueue.push({scope: this, expression: expr}); }, $$postDigest: function(fn) { postDigestQueue.push(fn); }, /** * @ngdoc method * @name $rootScope.Scope#$apply * @kind function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life * cycle of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` * ```js function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * ``` * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/expression expression} is executed using the * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } } }, /** * @ngdoc method * @name $rootScope.Scope#$applyAsync * @kind function * * @description * Schedule the invokation of $apply to occur at a later time. The actual time difference * varies across browsers, but is typically around ~10 milliseconds. * * This can be used to queue up multiple expressions which need to be evaluated in the same * digest. * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. */ $applyAsync: function(expr) { var scope = this; expr && applyAsyncQueue.push($applyAsyncExpression); scheduleApplyAsync(); function $applyAsyncExpression() { scope.$eval(expr); } }, /** * @ngdoc method * @name $rootScope.Scope#$on * @kind function * * @description * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for * discussion of event life cycle. * * The event listener function format is: `function(event, args...)`. The `event` object * passed into the listener has the following attributes: * * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or * `$broadcast`-ed. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the * event propagates through the scope hierarchy, this property is set to null. * - `name` - `{string}`: name of the event. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel * further event propagation (available only for events that were `$emit`-ed). * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag * to true. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. * * @param {string} name Event name to listen on. * @param {function(event, ...args)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); var current = this; do { if (!current.$$listenerCount[name]) { current.$$listenerCount[name] = 0; } current.$$listenerCount[name]++; } while ((current = current.$parent)); var self = this; return function() { var indexOfListener = namedListeners.indexOf(listener); if (indexOfListener !== -1) { namedListeners[indexOfListener] = null; decrementListenerCount(self, 1, name); } }; }, /** * @ngdoc method * @name $rootScope.Scope#$emit * @kind function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get * notified. Afterwards, the event traverses upwards toward the root scope and calls all * registered listeners along the way. The event will stop propagating if one of the listeners * cancels it. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i = 0, length = namedListeners.length; i < length; i++) { // if listeners were deregistered, defragment the array if (!namedListeners[i]) { namedListeners.splice(i, 1); i--; length--; continue; } try { //allow all listeners attached to the current scope to run namedListeners[i].apply(null, listenerArgs); } catch (e) { $exceptionHandler(e); } } //if any listener on the current scope stops propagation, prevent bubbling if (stopPropagation) { event.currentScope = null; return event; } //traverse upwards scope = scope.$parent; } while (scope); event.currentScope = null; return event; }, /** * @ngdoc method * @name $rootScope.Scope#$broadcast * @kind function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get * notified. Afterwards, the event propagates to all direct and indirect scopes of the current * scope and calls all registered listeners along the way. The event cannot be canceled. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to broadcast. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }; if (!target.$$listenerCount[name]) return event; var listenerArgs = concat([event], arguments, 1), listeners, i, length; //down while you can, then up and next sibling or up and next sibling until back at root while ((current = next)) { event.currentScope = current; listeners = current.$$listeners[name] || []; for (i = 0, length = listeners.length; i < length; i++) { // if listeners were deregistered, defragment the array if (!listeners[i]) { listeners.splice(i, 1); i--; length--; continue; } try { listeners[i].apply(null, listenerArgs); } catch (e) { $exceptionHandler(e); } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest // (though it differs due to having the extra check for $$listenerCount) if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || (current !== target && current.$$nextSibling)))) { while (current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } event.currentScope = null; return event; } }; var $rootScope = new Scope(); //The internal queues. Expose them on the $rootScope for debugging/testing purposes. var asyncQueue = $rootScope.$$asyncQueue = []; var postDigestQueue = $rootScope.$$postDigestQueue = []; var applyAsyncQueue = $rootScope.$$applyAsyncQueue = []; return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function decrementListenerCount(current, count, name) { do { current.$$listenerCount[name] -= count; if (current.$$listenerCount[name] === 0) { delete current.$$listenerCount[name]; } } while ((current = current.$parent)); } /** * function used as an initial value for watchers. * because it's unique we can easily tell it apart from other values */ function initWatchVal() {} function flushApplyAsync() { while (applyAsyncQueue.length) { try { applyAsyncQueue.shift()(); } catch (e) { $exceptionHandler(e); } } applyAsyncId = null; } function scheduleApplyAsync() { if (applyAsyncId === null) { applyAsyncId = $browser.defer(function() { $rootScope.$apply(flushApplyAsync); }); } } }]; } /** * @description * Private service to sanitize uris for links and images. Used by $compile and $sanitize. */ function $$SanitizeUriProvider() { var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { aHrefSanitizationWhitelist = regexp; return this; } return aHrefSanitizationWhitelist; }; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to img[src] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { imgSrcSanitizationWhitelist = regexp; return this; } return imgSrcSanitizationWhitelist; }; this.$get = function() { return function sanitizeUri(uri, isImage) { var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; var normalizedVal; normalizedVal = urlResolve(uri).href; if (normalizedVal !== '' && !normalizedVal.match(regex)) { return 'unsafe:' + normalizedVal; } return uri; }; }; } var $sceMinErr = minErr('$sce'); var SCE_CONTEXTS = { HTML: 'html', CSS: 'css', URL: 'url', // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a // url. (e.g. ng-include, script src, templateUrl) RESOURCE_URL: 'resourceUrl', JS: 'js' }; // Helper functions follow. function adjustMatcher(matcher) { if (matcher === 'self') { return matcher; } else if (isString(matcher)) { // Strings match exactly except for 2 wildcards - '*' and '**'. // '*' matches any character except those from the set ':/.?&'. // '**' matches any character (like .* in a RegExp). // More than 2 *'s raises an error as it's ill defined. if (matcher.indexOf('***') > -1) { throw $sceMinErr('iwcard', 'Illegal sequence *** in string matcher. String: {0}', matcher); } matcher = escapeForRegexp(matcher). replace('\\*\\*', '.*'). replace('\\*', '[^:/.?&;]*'); return new RegExp('^' + matcher + '$'); } else if (isRegExp(matcher)) { // The only other type of matcher allowed is a Regexp. // Match entire URL / disallow partial matches. // Flags are reset (i.e. no global, ignoreCase or multiline) return new RegExp('^' + matcher.source + '$'); } else { throw $sceMinErr('imatcher', 'Matchers may only be "self", string patterns or RegExp objects'); } } function adjustMatchers(matchers) { var adjustedMatchers = []; if (isDefined(matchers)) { forEach(matchers, function(matcher) { adjustedMatchers.push(adjustMatcher(matcher)); }); } return adjustedMatchers; } /** * @ngdoc service * @name $sceDelegate * @kind function * * @description * * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict * Contextual Escaping (SCE)} services to AngularJS. * * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things * work because `$sce` delegates to `$sceDelegate` for these operations. * * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. * * The default instance of `$sceDelegate` should work out of the box with little pain. While you * can override it completely to change the behavior of `$sce`, the common case would * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist * $sceDelegateProvider.resourceUrlWhitelist} and {@link * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} */ /** * @ngdoc provider * @name $sceDelegateProvider * @description * * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure * that the URLs used for sourcing Angular templates are safe. Refer {@link * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} * * For the general details about this service in Angular, read the main page for {@link ng.$sce * Strict Contextual Escaping (SCE)}. * * **Example**: Consider the following case. <a name="example"></a> * * - your app is hosted at url `http://myapp.example.com/` * - but some of your templates are hosted on other domains you control such as * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. * * Here is what a secure configuration for this scenario might look like: * * ``` * angular.module('myApp', []).config(function($sceDelegateProvider) { * $sceDelegateProvider.resourceUrlWhitelist([ * // Allow same origin resource loads. * 'self', * // Allow loading from our assets domain. Notice the difference between * and **. * 'http://srv*.assets.example.com/**' * ]); * * // The blacklist overrides the whitelist so the open redirect here is blocked. * $sceDelegateProvider.resourceUrlBlacklist([ * 'http://myapp.example.com/clickThru**' * ]); * }); * ``` */ function $SceDelegateProvider() { this.SCE_CONTEXTS = SCE_CONTEXTS; // Resource URLs can also be trusted by policy. var resourceUrlWhitelist = ['self'], resourceUrlBlacklist = []; /** * @ngdoc method * @name $sceDelegateProvider#resourceUrlWhitelist * @kind function * * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value * provided. This must be an array or null. A snapshot of this array is used so further * changes to the array are ignored. * * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items * allowed in this array. * * Note: **an empty whitelist array will block all URLs**! * * @return {Array} the currently set whitelist array. * * The **default value** when no whitelist has been explicitly set is `['self']` allowing only * same origin resource requests. * * @description * Sets/Gets the whitelist of trusted resource URLs. */ this.resourceUrlWhitelist = function(value) { if (arguments.length) { resourceUrlWhitelist = adjustMatchers(value); } return resourceUrlWhitelist; }; /** * @ngdoc method * @name $sceDelegateProvider#resourceUrlBlacklist * @kind function * * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value * provided. This must be an array or null. A snapshot of this array is used so further * changes to the array are ignored. * * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items * allowed in this array. * * The typical usage for the blacklist is to **block * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as * these would otherwise be trusted but actually return content from the redirected domain. * * Finally, **the blacklist overrides the whitelist** and has the final say. * * @return {Array} the currently set blacklist array. * * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there * is no blacklist.) * * @description * Sets/Gets the blacklist of trusted resource URLs. */ this.resourceUrlBlacklist = function(value) { if (arguments.length) { resourceUrlBlacklist = adjustMatchers(value); } return resourceUrlBlacklist; }; this.$get = ['$injector', function($injector) { var htmlSanitizer = function htmlSanitizer(html) { throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); }; if ($injector.has('$sanitize')) { htmlSanitizer = $injector.get('$sanitize'); } function matchUrl(matcher, parsedUrl) { if (matcher === 'self') { return urlIsSameOrigin(parsedUrl); } else { // definitely a regex. See adjustMatchers() return !!matcher.exec(parsedUrl.href); } } function isResourceUrlAllowedByPolicy(url) { var parsedUrl = urlResolve(url.toString()); var i, n, allowed = false; // Ensure that at least one item from the whitelist allows this url. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { allowed = true; break; } } if (allowed) { // Ensure that no item from the blacklist blocked this url. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { allowed = false; break; } } } return allowed; } function generateHolderType(Base) { var holderType = function TrustedValueHolderType(trustedValue) { this.$$unwrapTrustedValue = function() { return trustedValue; }; }; if (Base) { holderType.prototype = new Base(); } holderType.prototype.valueOf = function sceValueOf() { return this.$$unwrapTrustedValue(); }; holderType.prototype.toString = function sceToString() { return this.$$unwrapTrustedValue().toString(); }; return holderType; } var trustedValueHolderBase = generateHolderType(), byType = {}; byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); /** * @ngdoc method * @name $sceDelegate#trustAs * * @description * Returns an object that is trusted by angular for use in specified strict * contextual escaping contexts (such as ng-bind-html, ng-include, any src * attribute interpolation, any dom event binding attribute interpolation * such as for onclick, etc.) that uses the provided value. * See {@link ng.$sce $sce} for enabling strict contextual escaping. * * @param {string} type The kind of context in which this value is safe for use. e.g. url, * resourceUrl, html, js and css. * @param {*} value The value that that should be considered trusted/safe. * @returns {*} A value that can be used to stand in for the provided `value` in places * where Angular expects a $sce.trustAs() return value. */ function trustAs(type, trustedValue) { var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); if (!Constructor) { throw $sceMinErr('icontext', 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', type, trustedValue); } if (trustedValue === null || trustedValue === undefined || trustedValue === '') { return trustedValue; } // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting // mutable objects, we ensure here that the value passed in is actually a string. if (typeof trustedValue !== 'string') { throw $sceMinErr('itype', 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', type); } return new Constructor(trustedValue); } /** * @ngdoc method * @name $sceDelegate#valueOf * * @description * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. * * If the passed parameter is not a value that had been returned by {@link * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is. * * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} * call or anything else. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns * `value` unchanged. */ function valueOf(maybeTrusted) { if (maybeTrusted instanceof trustedValueHolderBase) { return maybeTrusted.$$unwrapTrustedValue(); } else { return maybeTrusted; } } /** * @ngdoc method * @name $sceDelegate#getTrusted * * @description * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and * returns the originally supplied value if the queried context type is a supertype of the * created type. If this condition isn't satisfied, throws an exception. * * @param {string} type The kind of context in which this value is to be used. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} call. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. */ function getTrusted(type, maybeTrusted) { if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { return maybeTrusted; } var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); if (constructor && maybeTrusted instanceof constructor) { return maybeTrusted.$$unwrapTrustedValue(); } // If we get here, then we may only take one of two actions. // 1. sanitize the value for the requested type, or // 2. throw an exception. if (type === SCE_CONTEXTS.RESOURCE_URL) { if (isResourceUrlAllowedByPolicy(maybeTrusted)) { return maybeTrusted; } else { throw $sceMinErr('insecurl', 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', maybeTrusted.toString()); } } else if (type === SCE_CONTEXTS.HTML) { return htmlSanitizer(maybeTrusted); } throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); } return { trustAs: trustAs, getTrusted: getTrusted, valueOf: valueOf }; }]; } /** * @ngdoc provider * @name $sceProvider * @description * * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. * - enable/disable Strict Contextual Escaping (SCE) in a module * - override the default implementation with a custom delegate * * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. */ /* jshint maxlen: false*/ /** * @ngdoc service * @name $sce * @kind function * * @description * * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. * * # Strict Contextual Escaping * * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain * contexts to result in a value that is marked as safe to use for that context. One example of * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer * to these contexts as privileged or SCE contexts. * * As of version 1.2, Angular ships with SCE enabled by default. * * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow * one to execute arbitrary javascript by the use of the expression() syntax. Refer * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>` * to the top of your HTML document. * * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. * * Here's an example of a binding in a privileged context: * * ``` * <input ng-model="userHtml"> * <div ng-bind-html="userHtml"></div> * ``` * * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE * disabled, this application allows the user to render arbitrary HTML into the DIV. * In a more realistic example, one may be rendering user comments, blog articles, etc. via * bindings. (HTML is just one example of a context where rendering user controlled input creates * security vulnerabilities.) * * For the case of HTML, you might use a library, either on the client side, or on the server side, * to sanitize unsafe HTML before binding to the value and rendering it in the document. * * How would you ensure that every place that used these types of bindings was bound to a value that * was sanitized by your library (or returned as safe for rendering by your server?) How can you * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some * properties/fields and forgot to update the binding to the sanitized value? * * To be secure by default, you want to ensure that any such bindings are disallowed unless you can * determine that something explicitly says it's safe to use a value for binding in that * context. You can then audit your code (a simple grep would do) to ensure that this is only done * for those values that you can easily tell are safe - because they were received from your server, * sanitized by your library, etc. You can organize your codebase to help with this - perhaps * allowing only the files in a specific directory to do this. Ensuring that the internal API * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. * * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to * obtain values that will be accepted by SCE / privileged contexts. * * * ## How does it work? * * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. * * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly * simplified): * * ``` * var ngBindHtmlDirective = ['$sce', function($sce) { * return function(scope, element, attr) { * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { * element.html(value || ''); * }); * }; * }]; * ``` * * ## Impact on loading templates * * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as * `templateUrl`'s specified by {@link guide/directive directives}. * * By default, Angular only loads templates from the same domain and protocol as the application * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. * * *Please note*: * The browser's * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) * policy apply in addition to this and may further restrict whether the template is successfully * loaded. This means that without the right CORS policy, loading templates from a different domain * won't work on all browsers. Also, loading templates from `file://` URL does not work on some * browsers. * * ## This feels like too much overhead * * It's important to remember that SCE only applies to interpolation expressions. * * If your expressions are constant literals, they're automatically trusted and you don't need to * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works. * * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. * * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load * templates in `ng-include` from your application's domain without having to even know about SCE. * It blocks loading templates from other domains or loading templates over http from an https * served document. You can change these by setting your own custom {@link * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. * * This significantly reduces the overhead. It is far easier to pay the small overhead and have an * application that's secure and can be audited to verify that with much more ease than bolting * security onto an application later. * * <a name="contexts"></a> * ## What trusted context types are supported? * * | Context | Notes | * |---------------------|----------------| * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. | * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. | * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | * * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a> * * Each element in these arrays must be one of the following: * * - **'self'** * - The special **string**, `'self'`, can be used to match against all URLs of the **same * domain** as the application document using the **same protocol**. * - **String** (except the special value `'self'`) * - The string is matched against the full *normalized / absolute URL* of the resource * being tested (substring matches are not good enough.) * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters * match themselves. * - `*`: matches zero or more occurrences of any character other than one of the following 6 * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use * in a whitelist. * - `**`: matches zero or more occurrences of *any* character. As such, it's not * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might * not have been the intention.) Its usage at the very end of the path is ok. (e.g. * http://foo.example.com/templates/**). * - **RegExp** (*see caveat below*) * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to * accidentally introduce a bug when one updates a complex expression (imho, all regexes should * have good test coverage.). For instance, the use of `.` in the regex is correct only in a * small number of cases. A `.` character in the regex used when matching the scheme or a * subdomain could be matched against a `:` or literal `.` that was likely not intended. It * is highly recommended to use the string patterns and only fall back to regular expressions * if they as a last resort. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is * matched against the **entire** *normalized / absolute URL* of the resource being tested * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags * present on the RegExp (such as multiline, global, ignoreCase) are ignored. * - If you are generating your JavaScript from some other templating engine (not * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), * remember to escape your regular expression (and be aware that you might need more than * one level of escaping depending on your templating engine and the way you interpolated * the value.) Do make use of your platform's escaping mechanism as it might be good * enough before coding your own. e.g. Ruby has * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). * Javascript lacks a similar built in function for escaping. Take a look at Google * Closure library's [goog.string.regExpEscape(s)]( * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). * * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. * * ## Show me an example using SCE. * * <example module="mySceApp" deps="angular-sanitize.js"> * <file name="index.html"> * <div ng-controller="AppController as myCtrl"> * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br> * <b>User comments</b><br> * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when * $sanitize is available. If $sanitize isn't available, this results in an error instead of an * exploit. * <div class="well"> * <div ng-repeat="userComment in myCtrl.userComments"> * <b>{{userComment.name}}</b>: * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span> * <br> * </div> * </div> * </div> * </file> * * <file name="script.js"> * angular.module('mySceApp', ['ngSanitize']) * .controller('AppController', ['$http', '$templateCache', '$sce', * function($http, $templateCache, $sce) { * var self = this; * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { * self.userComments = userComments; * }); * self.explicitlyTrustedHtml = $sce.trustAsHtml( * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' + * 'sanitization.&quot;">Hover over this text.</span>'); * }]); * </file> * * <file name="test_data.json"> * [ * { "name": "Alice", * "htmlComment": * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>" * }, * { "name": "Bob", * "htmlComment": "<i>Yes!</i> Am I the only other one?" * } * ] * </file> * * <file name="protractor.js" type="protractor"> * describe('SCE doc demo', function() { * it('should sanitize untrusted values', function() { * expect(element.all(by.css('.htmlComment')).first().getInnerHtml()) * .toBe('<span>Is <i>anyone</i> reading this?</span>'); * }); * * it('should NOT sanitize explicitly trusted values', function() { * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe( * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' + * 'sanitization.&quot;">Hover over this text.</span>'); * }); * }); * </file> * </example> * * * * ## Can I disable SCE completely? * * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits * for little coding overhead. It will be much harder to take an SCE disabled application and * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE * for cases where you have a lot of existing code that was written before SCE was introduced and * you're migrating them a module at a time. * * That said, here's how you can completely disable SCE: * * ``` * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { * // Completely disable SCE. For demonstration purposes only! * // Do not use in new projects. * $sceProvider.enabled(false); * }); * ``` * */ /* jshint maxlen: 100 */ function $SceProvider() { var enabled = true; /** * @ngdoc method * @name $sceProvider#enabled * @kind function * * @param {boolean=} value If provided, then enables/disables SCE. * @return {boolean} true if SCE is enabled, false otherwise. * * @description * Enables/disables SCE and returns the current value. */ this.enabled = function(value) { if (arguments.length) { enabled = !!value; } return enabled; }; /* Design notes on the default implementation for SCE. * * The API contract for the SCE delegate * ------------------------------------- * The SCE delegate object must provide the following 3 methods: * * - trustAs(contextEnum, value) * This method is used to tell the SCE service that the provided value is OK to use in the * contexts specified by contextEnum. It must return an object that will be accepted by * getTrusted() for a compatible contextEnum and return this value. * * - valueOf(value) * For values that were not produced by trustAs(), return them as is. For values that were * produced by trustAs(), return the corresponding input value to trustAs. Basically, if * trustAs is wrapping the given values into some type, this operation unwraps it when given * such a value. * * - getTrusted(contextEnum, value) * This function should return the a value that is safe to use in the context specified by * contextEnum or throw and exception otherwise. * * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be * opaque or wrapped in some holder object. That happens to be an implementation detail. For * instance, an implementation could maintain a registry of all trusted objects by context. In * such a case, trustAs() would return the same object that was passed in. getTrusted() would * return the same object passed in if it was found in the registry under a compatible context or * throw an exception otherwise. An implementation might only wrap values some of the time based * on some criteria. getTrusted() might return a value and not throw an exception for special * constants or objects even if not wrapped. All such implementations fulfill this contract. * * * A note on the inheritance model for SCE contexts * ------------------------------------------------ * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This * is purely an implementation details. * * The contract is simply this: * * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) * will also succeed. * * Inheritance happens to capture this in a natural way. In some future, we * may not use inheritance anymore. That is OK because no code outside of * sce.js and sceSpecs.js would need to be aware of this detail. */ this.$get = ['$parse', '$sceDelegate', function( $parse, $sceDelegate) { // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow // the "expression(javascript expression)" syntax which is insecure. if (enabled && msie < 8) { throw $sceMinErr('iequirks', 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' + 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' + 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); } var sce = shallowCopy(SCE_CONTEXTS); /** * @ngdoc method * @name $sce#isEnabled * @kind function * * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. * * @description * Returns a boolean indicating if SCE is enabled. */ sce.isEnabled = function() { return enabled; }; sce.trustAs = $sceDelegate.trustAs; sce.getTrusted = $sceDelegate.getTrusted; sce.valueOf = $sceDelegate.valueOf; if (!enabled) { sce.trustAs = sce.getTrusted = function(type, value) { return value; }; sce.valueOf = identity; } /** * @ngdoc method * @name $sce#parseAs * * @description * Converts Angular {@link guide/expression expression} into a function. This is like {@link * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, * *result*)} * * @param {string} type The kind of SCE context in which this result will be used. * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ sce.parseAs = function sceParseAs(type, expr) { var parsed = $parse(expr); if (parsed.literal && parsed.constant) { return parsed; } else { return $parse(expr, function(value) { return sce.getTrusted(type, value); }); } }; /** * @ngdoc method * @name $sce#trustAs * * @description * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, * returns an object that is trusted by angular for use in specified strict contextual * escaping contexts (such as ng-bind-html, ng-include, any src attribute * interpolation, any dom event binding attribute interpolation such as for onclick, etc.) * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual * escaping. * * @param {string} type The kind of context in which this value is safe for use. e.g. url, * resource_url, html, js and css. * @param {*} value The value that that should be considered trusted/safe. * @returns {*} A value that can be used to stand in for the provided `value` in places * where Angular expects a $sce.trustAs() return value. */ /** * @ngdoc method * @name $sce#trustAsHtml * * @description * Shorthand method. `$sce.trustAsHtml(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#trustAsUrl * * @description * Shorthand method. `$sce.trustAsUrl(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#trustAsResourceUrl * * @description * Shorthand method. `$sce.trustAsResourceUrl(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the return * value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#trustAsJs * * @description * Shorthand method. `$sce.trustAsJs(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} * * @param {*} value The value to trustAs. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives * only accept expressions that are either literal constants or are the * return value of {@link ng.$sce#trustAs $sce.trustAs}.) */ /** * @ngdoc method * @name $sce#getTrusted * * @description * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the * originally supplied value if the queried context type is a supertype of the created type. * If this condition isn't satisfied, throws an exception. * * @param {string} type The kind of context in which this value is to be used. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} * call. * @returns {*} The value the was originally provided to * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context. * Otherwise, throws an exception. */ /** * @ngdoc method * @name $sce#getTrustedHtml * * @description * Shorthand method. `$sce.getTrustedHtml(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` */ /** * @ngdoc method * @name $sce#getTrustedCss * * @description * Shorthand method. `$sce.getTrustedCss(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` */ /** * @ngdoc method * @name $sce#getTrustedUrl * * @description * Shorthand method. `$sce.getTrustedUrl(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` */ /** * @ngdoc method * @name $sce#getTrustedResourceUrl * * @description * Shorthand method. `$sce.getTrustedResourceUrl(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} * * @param {*} value The value to pass to `$sceDelegate.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` */ /** * @ngdoc method * @name $sce#getTrustedJs * * @description * Shorthand method. `$sce.getTrustedJs(value)` → * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` */ /** * @ngdoc method * @name $sce#parseAsHtml * * @description * Shorthand method. `$sce.parseAsHtml(expression string)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsCss * * @description * Shorthand method. `$sce.parseAsCss(value)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsUrl * * @description * Shorthand method. `$sce.parseAsUrl(value)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsResourceUrl * * @description * Shorthand method. `$sce.parseAsResourceUrl(value)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ /** * @ngdoc method * @name $sce#parseAsJs * * @description * Shorthand method. `$sce.parseAsJs(value)` → * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`} * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. */ // Shorthand delegations. var parse = sce.parseAs, getTrusted = sce.getTrusted, trustAs = sce.trustAs; forEach(SCE_CONTEXTS, function(enumValue, name) { var lName = lowercase(name); sce[camelCase("parse_as_" + lName)] = function(expr) { return parse(enumValue, expr); }; sce[camelCase("get_trusted_" + lName)] = function(value) { return getTrusted(enumValue, value); }; sce[camelCase("trust_as_" + lName)] = function(value) { return trustAs(enumValue, value); }; }); return sce; }]; } /** * !!! This is an undocumented "private" service !!! * * @name $sniffer * @requires $window * @requires $document * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} transitions Does the browser support CSS transition events ? * @property {boolean} animations Does the browser support CSS animation events ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', '$document', function($window, $document) { var eventSupport = {}, android = int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), boxee = /Boxee/i.test(($window.navigator || {}).userAgent), document = $document[0] || {}, vendorPrefix, vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/, bodyStyle = document.body && document.body.style, transitions = false, animations = false, match; if (bodyStyle) { for (var prop in bodyStyle) { if (match = vendorRegex.exec(prop)) { vendorPrefix = match[0]; vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); break; } } if (!vendorPrefix) { vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; } transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); if (android && (!transitions || !animations)) { transitions = isString(document.body.style.webkitTransition); animations = isString(document.body.style.webkitAnimation); } } return { // Android has history.pushState, but it does not update location correctly // so let's not use the history API at all. // http://code.google.com/p/android/issues/detail?id=17471 // https://github.com/angular/angular.js/issues/904 // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has // so let's not use the history API also // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined // jshint -W018 history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), // jshint +W018 hasEvent: function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. if (event == 'input' && msie == 9) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }, csp: csp(), vendorPrefix: vendorPrefix, transitions: transitions, animations: animations, android: android }; }]; } var $compileMinErr = minErr('$compile'); /** * @ngdoc service * @name $templateRequest * * @description * The `$templateRequest` service downloads the provided template using `$http` and, upon success, * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data * of the HTTP request is empty then a `$compile` error will be thrown (the exception can be thwarted * by setting the 2nd parameter of the function to true). * * @param {string} tpl The HTTP request template URL * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty * * @return {Promise} the HTTP Promise for the given. * * @property {number} totalPendingRequests total amount of pending template requests being downloaded. */ function $TemplateRequestProvider() { this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) { function handleRequestFn(tpl, ignoreRequestError) { var self = handleRequestFn; self.totalPendingRequests++; var transformResponse = $http.defaults && $http.defaults.transformResponse; if (isArray(transformResponse)) { var original = transformResponse; transformResponse = []; for (var i = 0; i < original.length; ++i) { var transformer = original[i]; if (transformer !== defaultHttpResponseTransform) { transformResponse.push(transformer); } } } else if (transformResponse === defaultHttpResponseTransform) { transformResponse = null; } var httpOptions = { cache: $templateCache, transformResponse: transformResponse }; return $http.get(tpl, httpOptions) .then(function(response) { var html = response.data; self.totalPendingRequests--; $templateCache.put(tpl, html); return html; }, handleError); function handleError() { self.totalPendingRequests--; if (!ignoreRequestError) { throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl); } return $q.reject(); } } handleRequestFn.totalPendingRequests = 0; return handleRequestFn; }]; } function $$TestabilityProvider() { this.$get = ['$rootScope', '$browser', '$location', function($rootScope, $browser, $location) { /** * @name $testability * * @description * The private $$testability service provides a collection of methods for use when debugging * or by automated test and debugging tools. */ var testability = {}; /** * @name $$testability#findBindings * * @description * Returns an array of elements that are bound (via ng-bind or {{}}) * to expressions matching the input. * * @param {Element} element The element root to search from. * @param {string} expression The binding expression to match. * @param {boolean} opt_exactMatch If true, only returns exact matches * for the expression. Filters and whitespace are ignored. */ testability.findBindings = function(element, expression, opt_exactMatch) { var bindings = element.getElementsByClassName('ng-binding'); var matches = []; forEach(bindings, function(binding) { var dataBinding = angular.element(binding).data('$binding'); if (dataBinding) { forEach(dataBinding, function(bindingName) { if (opt_exactMatch) { var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)'); if (matcher.test(bindingName)) { matches.push(binding); } } else { if (bindingName.indexOf(expression) != -1) { matches.push(binding); } } }); } }); return matches; }; /** * @name $$testability#findModels * * @description * Returns an array of elements that are two-way found via ng-model to * expressions matching the input. * * @param {Element} element The element root to search from. * @param {string} expression The model expression to match. * @param {boolean} opt_exactMatch If true, only returns exact matches * for the expression. */ testability.findModels = function(element, expression, opt_exactMatch) { var prefixes = ['ng-', 'data-ng-', 'ng\\:']; for (var p = 0; p < prefixes.length; ++p) { var attributeEquals = opt_exactMatch ? '=' : '*='; var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]'; var elements = element.querySelectorAll(selector); if (elements.length) { return elements; } } }; /** * @name $$testability#getLocation * * @description * Shortcut for getting the location in a browser agnostic way. Returns * the path, search, and hash. (e.g. /path?a=b#hash) */ testability.getLocation = function() { return $location.url(); }; /** * @name $$testability#setLocation * * @description * Shortcut for navigating to a location without doing a full page reload. * * @param {string} url The location url (path, search and hash, * e.g. /path?a=b#hash) to go to. */ testability.setLocation = function(url) { if (url !== $location.url()) { $location.url(url); $rootScope.$digest(); } }; /** * @name $$testability#whenStable * * @description * Calls the callback when $timeout and $http requests are completed. * * @param {function} callback */ testability.whenStable = function(callback) { $browser.notifyWhenNoOutstandingRequests(callback); }; return testability; }]; } function $TimeoutProvider() { this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', function($rootScope, $browser, $q, $$q, $exceptionHandler) { var deferreds = {}; /** * @ngdoc service * @name $timeout * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch * block and delegates any exceptions to * {@link ng.$exceptionHandler $exceptionHandler} service. * * The return value of registering a timeout function is a promise, which will be resolved when * the timeout is reached and the timeout function is executed. * * To cancel a timeout request, call `$timeout.cancel(promise)`. * * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to * synchronously flush the queue of deferred functions. * * @param {function()} fn A function, whose execution should be delayed. * @param {number=} [delay=0] Delay in milliseconds. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. * */ function timeout(fn, delay, invokeApply) { var skipApply = (isDefined(invokeApply) && !invokeApply), deferred = (skipApply ? $$q : $q).defer(), promise = deferred.promise, timeoutId; timeoutId = $browser.defer(function() { try { deferred.resolve(fn()); } catch (e) { deferred.reject(e); $exceptionHandler(e); } finally { delete deferreds[promise.$$timeoutId]; } if (!skipApply) $rootScope.$apply(); }, delay); promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; return promise; } /** * @ngdoc method * @name $timeout#cancel * * @description * Cancels a task associated with the `promise`. As a result of this, the promise will be * resolved with a rejection. * * @param {Promise=} promise Promise returned by the `$timeout` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ timeout.cancel = function(promise) { if (promise && promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); delete deferreds[promise.$$timeoutId]; return $browser.defer.cancel(promise.$$timeoutId); } return false; }; return timeout; }]; } // NOTE: The usage of window and document instead of $window and $document here is // deliberate. This service depends on the specific behavior of anchor nodes created by the // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and // cause us to break tests. In addition, when the browser resolves a URL for XHR, it // doesn't know about mocked locations and resolves URLs to the real document - which is // exactly the behavior needed here. There is little value is mocking these out for this // service. var urlParsingNode = document.createElement("a"); var originUrl = urlResolve(window.location.href); /** * * Implementation Notes for non-IE browsers * ---------------------------------------- * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, * results both in the normalizing and parsing of the URL. Normalizing means that a relative * URL will be resolved into an absolute URL in the context of the application document. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related * properties are all populated to reflect the normalized URL. This approach has wide * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html * * Implementation Notes for IE * --------------------------- * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other * browsers. However, the parsed components will not be set if the URL assigned did not specify * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We * work around that by performing the parsing in a 2nd step by taking a previously normalized * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the * properties such as protocol, hostname, port, etc. * * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one * uses the inner HTML approach to assign the URL as part of an HTML snippet - * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that * method and IE < 8 is unsupported. * * References: * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html * http://url.spec.whatwg.org/#urlutils * https://github.com/angular/angular.js/pull/2902 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ * * @kind function * @param {string} url The URL to be parsed. * @description Normalizes and parses a URL. * @returns {object} Returns the normalized URL as a dictionary. * * | member name | Description | * |---------------|----------------| * | href | A normalized version of the provided URL if it was not an absolute URL | * | protocol | The protocol including the trailing colon | * | host | The host and port (if the port is non-default) of the normalizedUrl | * | search | The search params, minus the question mark | * | hash | The hash string, minus the hash symbol * | hostname | The hostname * | port | The port, without ":" * | pathname | The pathname, beginning with "/" * */ function urlResolve(url) { var href = url; if (msie) { // Normalize before parse. Refer Implementation Notes on why this is // done in two steps on IE. urlParsingNode.setAttribute("href", href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } /** * Parse a request URL and determine whether this is a same-origin request as the application document. * * @param {string|object} requestUrl The url of the request as a string that will be resolved * or a parsed URL object. * @returns {boolean} Whether the request is for the same origin as the application document. */ function urlIsSameOrigin(requestUrl) { var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; return (parsed.protocol === originUrl.protocol && parsed.host === originUrl.host); } /** * @ngdoc service * @name $window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overridden, removed or mocked for testing. * * Expressions, like the one defined for the `ngClick` directive in the example * below, are evaluated with respect to the current scope. Therefore, there is * no risk of inadvertently coding in a dependency on a global value in such an * expression. * * @example <example module="windowExample"> <file name="index.html"> <script> angular.module('windowExample', []) .controller('ExampleController', ['$scope', '$window', function($scope, $window) { $scope.greeting = 'Hello, World!'; $scope.doGreeting = function(greeting) { $window.alert(greeting); }; }]); </script> <div ng-controller="ExampleController"> <input type="text" ng-model="greeting" /> <button ng-click="doGreeting(greeting)">ALERT</button> </div> </file> <file name="protractor.js" type="protractor"> it('should display the greeting in the input box', function() { element(by.model('greeting')).sendKeys('Hello, E2E Tests'); // If we click the button it will block the test runner // element(':button').click(); }); </file> </example> */ function $WindowProvider() { this.$get = valueFn(window); } /* global currencyFilter: true, dateFilter: true, filterFilter: true, jsonFilter: true, limitToFilter: true, lowercaseFilter: true, numberFilter: true, orderByFilter: true, uppercaseFilter: true, */ /** * @ngdoc provider * @name $filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be * Dependency Injected. To achieve this a filter definition consists of a factory function which is * annotated with dependencies and is responsible for creating a filter function. * * ```js * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }); * } * ``` * * The filter function is registered with the `$injector` under the filter name suffix with * `Filter`. * * ```js * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * ``` * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/filter Filters} in the Angular Developer Guide. */ /** * @ngdoc service * @name $filter * @kind function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression [| filter_name[:parameter_value] ... ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function * @example <example name="$filter" module="filterExample"> <file name="index.html"> <div ng-controller="MainCtrl"> <h3>{{ originalText }}</h3> <h3>{{ filteredText }}</h3> </div> </file> <file name="script.js"> angular.module('filterExample', []) .controller('MainCtrl', function($scope, $filter) { $scope.originalText = 'hello'; $scope.filteredText = $filter('uppercase')($scope.originalText); }); </file> </example> */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; /** * @ngdoc method * @name $filterProvider#register * @param {string|Object} name Name of the filter function, or an object map of filters where * the keys are the filter names and the values are the filter factories. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map * of the registered filter instances. */ function register(name, factory) { if (isObject(name)) { var filters = {}; forEach(name, function(filter, key) { filters[key] = register(key, filter); }); return filters; } else { return $provide.factory(name + suffix, factory); } } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); }; }]; //////////////////////////////////////// /* global currencyFilter: false, dateFilter: false, filterFilter: false, jsonFilter: false, limitToFilter: false, lowercaseFilter: false, numberFilter: false, orderByFilter: false, uppercaseFilter: false, */ register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name filter * @kind function * * @description * Selects a subset of items from `array` and returns it as a new array. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against * the contents of the `array`. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. The predicate can be negated by prefixing the string with `!`. * For Example `{name: "!M"}` predicate will return an array of items which have property `name` * not containing "M". * * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The * function is called for each element of `array`. The final result is an array of those * elements that the predicate returned true for. * * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in * determining if the expected value (from the filter expression) and actual value (from * the object in the array) should be considered a match. * * Can be one of: * * - `function(actual, expected)`: * The function will be given the object value and the predicate value to compare and * should return true if the item should be included in filtered result. * * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`. * this is essentially strict comparison of expected and actual. * * - `false|undefined`: A short hand for a function which will look for a substring match in case * insensitive way. * * @example <example> <file name="index.html"> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}, {name:'Juliette', phone:'555-5678'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> </tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"><br> Equality <input type="checkbox" ng-model="strict"><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friendObj in friends | filter:search:strict"> <td>{{friendObj.name}}</td> <td>{{friendObj.phone}}</td> </tr> </table> </file> <file name="protractor.js" type="protractor"> var expectFriendNames = function(expectedNames, key) { element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { arr.forEach(function(wd, i) { expect(wd.getText()).toMatch(expectedNames[i]); }); }); }; it('should search across all fields when filtering with a string', function() { var searchText = element(by.model('searchText')); searchText.clear(); searchText.sendKeys('m'); expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); searchText.clear(); searchText.sendKeys('76'); expectFriendNames(['John', 'Julie'], 'friend'); }); it('should search in specific fields when filtering with a predicate object', function() { var searchAny = element(by.model('search.$')); searchAny.clear(); searchAny.sendKeys('i'); expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); }); it('should use a equal comparison when comparator is true', function() { var searchName = element(by.model('search.name')); var strict = element(by.model('strict')); searchName.clear(); searchName.sendKeys('Julie'); strict.click(); expectFriendNames(['Julie'], 'friendObj'); }); </file> </example> */ function filterFilter() { return function(array, expression, comparator) { if (!isArray(array)) return array; var comparatorType = typeof(comparator), predicates = []; predicates.check = function(value, index) { for (var j = 0; j < predicates.length; j++) { if (!predicates[j](value, index)) { return false; } } return true; }; if (comparatorType !== 'function') { if (comparatorType === 'boolean' && comparator) { comparator = function(obj, text) { return angular.equals(obj, text); }; } else { comparator = function(obj, text) { if (obj && text && typeof obj === 'object' && typeof text === 'object') { for (var objKey in obj) { if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) && comparator(obj[objKey], text[objKey])) { return true; } } return false; } text = ('' + text).toLowerCase(); return ('' + obj).toLowerCase().indexOf(text) > -1; }; } } var search = function(obj, text) { if (typeof text === 'string' && text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case 'boolean': case 'number': case 'string': return comparator(obj, text); case 'object': switch (typeof text) { case 'object': return comparator(obj, text); default: for (var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } break; } return false; case 'array': for (var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case 'boolean': case 'number': case 'string': // Set up expression object and fall through expression = {$:expression}; // jshint -W086 case 'object': // jshint +W086 for (var key in expression) { (function(path) { if (typeof expression[path] === 'undefined') return; predicates.push(function(value) { return search(path == '$' ? value : (value && value[path]), expression[path]); }); })(key); } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for (var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value, j)) { filtered.push(value); } } return filtered; }; } /** * @ngdoc filter * @name currency * @kind function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale * @returns {string} Formatted number. * * * @example <example module="currencyExample"> <file name="index.html"> <script> angular.module('currencyExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.amount = 1234.56; }]); </script> <div ng-controller="ExampleController"> <input type="number" ng-model="amount"> <br> default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br> custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span> no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span> </div> </file> <file name="protractor.js" type="protractor"> it('should init with 1234.56', function() { expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56'); expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235'); }); it('should update', function() { if (browser.params.browser == 'safari') { // Safari does not understand the minus key. See // https://github.com/angular/protractor/issues/481 return; } element(by.model('amount')).clear(); element(by.model('amount')).sendKeys('-1234'); expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)'); expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)'); expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)'); }); </file> </example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol, fractionSize) { if (isUndefined(currencySymbol)) { currencySymbol = formats.CURRENCY_SYM; } if (isUndefined(fractionSize)) { fractionSize = formats.PATTERNS[1].maxFrac; } // if null or undefined pass it through return (amount == null) ? amount : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name number * @kind function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} fractionSize Number of decimal places to round the number to. * If this is not provided then the fraction size is computed from the current locale's number * formatting pattern. In the case of the default locale, it will be 3. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <example module="numberFilterExample"> <file name="index.html"> <script> angular.module('numberFilterExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.val = 1234.56789; }]); </script> <div ng-controller="ExampleController"> Enter number: <input ng-model='val'><br> Default formatting: <span id='number-default'>{{val | number}}</span><br> No fractions: <span>{{val | number:0}}</span><br> Negative number: <span>{{-val | number:4}}</span> </div> </file> <file name="protractor.js" type="protractor"> it('should format numbers', function() { expect(element(by.id('number-default')).getText()).toBe('1,234.568'); expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); }); it('should update', function() { element(by.model('val')).clear(); element(by.model('val')).sendKeys('3374.333'); expect(element(by.id('number-default')).getText()).toBe('3,374.333'); expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); }); </file> </example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { // if null or undefined pass it through return (number == null) ? number : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (!isFinite(number) || isObject(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; var hasExponent = false; if (numStr.indexOf('e') !== -1) { var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); if (match && match[2] == '-' && match[3] > fractionSize + 1) { numStr = '0'; number = 0; } else { formatedText = numStr; hasExponent = true; } } if (!hasExponent) { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } // safely round numbers in JS without hitting imprecisions of floating-point arithmetics // inspired by: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize); if (number === 0) { isNegative = false; } var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var i, pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (i = 0; i < pos; i++) { if ((pos - i) % group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i) % lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while (fraction.length < fractionSize) { fraction += '0'; } if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); } else { if (fractionSize > 0 && number > -1 && number < 1) { formatedText = number.toFixed(fractionSize); } } parts.push(isNegative ? pattern.negPre : pattern.posPre, formatedText, isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while (num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { offset = offset || 0; return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var zone = -1 * date.getTimezoneOffset(); var paddedZone = (zone >= 0) ? "+" : ""; paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2); return paddedZone; } function getFirstThursdayOfYear(year) { // 0 = index of January var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay(); // 4 = index of Thursday (+1 to account for 1st = 5) // 11 = index of *next* Thursday (+1 account for 1st = 12) return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst); } function getThursdayThisWeek(datetime) { return new Date(datetime.getFullYear(), datetime.getMonth(), // 4 = index of Thursday datetime.getDate() + (4 - datetime.getDay())); } function weekGetter(size) { return function(date) { var firstThurs = getFirstThursdayOfYear(date.getFullYear()), thisThurs = getThursdayThisWeek(date); var diff = +thisThurs - +firstThurs, result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week return padNumber(result, size); }; } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), // while ISO 8601 requires fractions to be prefixed with `.` or `,` // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions sss: dateGetter('Milliseconds', 3), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter, ww: weekGetter(2), w: weekGetter(1) }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/, NUMBER_STRING = /^\-?\d+$/; /** * @ngdoc filter * @name date * @kind function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in AM/PM, padded (01-12) * * `'h'`: Hour in AM/PM, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) * * `'a'`: AM/PM marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) * * `'ww'`: ISO-8601 week of year (00-53) * * `'w'`: ISO-8601 week of year (0-53) * * `format` string can also be one of the following predefined * {@link guide/i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 PM) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM) * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM) * * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence * (e.g. `"h 'o''clock'"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is * specified in the string input, the time is considered to be in the local timezone. * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported. * If not specified, the timezone of the browser will be used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <example> <file name="index.html"> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: <span>{{1288323623006 | date:'medium'}}</span><br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br> <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>: <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br> </file> <file name="protractor.js" type="protractor"> it('should format date', function() { expect(element(by.binding("1288323623006 | date:'medium'")).getText()). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()). toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/); }); </file> </example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; // 1 2 3 4 5 6 7 8 9 10 11 function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0, dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, timeSetter = match[8] ? date.setUTCHours : date.setHours; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); var h = int(match[4] || 0) - tzHour; var m = int(match[5] || 0) - tzMin; var s = int(match[6] || 0); var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000); timeSetter.call(date, h, m, s, ms); return date; } return string; } return function(date, format, timezone) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date); } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while (format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } if (timezone && timezone === 'UTC') { date = new Date(date.getTime()); date.setMinutes(date.getMinutes() + date.getTimezoneOffset()); } forEach(parts, function(value) { fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name json * @kind function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * * @example <example> <file name="index.html"> <pre>{{ {'name':'value'} | json }}</pre> </file> <file name="protractor.js" type="protractor"> it('should jsonify filtered objects', function() { expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/); }); </file> </example> * */ function jsonFilter() { return function(object) { return toJson(object, true); }; } /** * @ngdoc filter * @name lowercase * @kind function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name uppercase * @kind function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc filter * @name limitTo * @kind function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array, string or number, as specified by * the value and sign (positive or negative) of `limit`. If a number is used as input, it is * converted to a string. * * @param {Array|string|number} input Source array, string or number to be limited. * @param {string|number} limit The length of the returned array or string. If the `limit` number * is positive, `limit` number of items from the beginning of the source array/string are copied. * If the number is negative, `limit` number of items from the end of the source array/string * are copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array * had less than `limit` elements. * * @example <example module="limitToExample"> <file name="index.html"> <script> angular.module('limitToExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.letters = "abcdefghi"; $scope.longNumber = 2345432342; $scope.numLimit = 3; $scope.letterLimit = 3; $scope.longNumberLimit = 3; }]); </script> <div ng-controller="ExampleController"> Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit"> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit"> <p>Output letters: {{ letters | limitTo:letterLimit }}</p> Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit"> <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p> </div> </file> <file name="protractor.js" type="protractor"> var numLimitInput = element(by.model('numLimit')); var letterLimitInput = element(by.model('letterLimit')); var longNumberLimitInput = element(by.model('longNumberLimit')); var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit')); it('should limit the number array to first three items', function() { expect(numLimitInput.getAttribute('value')).toBe('3'); expect(letterLimitInput.getAttribute('value')).toBe('3'); expect(longNumberLimitInput.getAttribute('value')).toBe('3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); expect(limitedLetters.getText()).toEqual('Output letters: abc'); expect(limitedLongNumber.getText()).toEqual('Output long number: 234'); }); // There is a bug in safari and protractor that doesn't like the minus key // it('should update the output when -3 is entered', function() { // numLimitInput.clear(); // numLimitInput.sendKeys('-3'); // letterLimitInput.clear(); // letterLimitInput.sendKeys('-3'); // longNumberLimitInput.clear(); // longNumberLimitInput.sendKeys('-3'); // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); // expect(limitedLetters.getText()).toEqual('Output letters: ghi'); // expect(limitedLongNumber.getText()).toEqual('Output long number: 342'); // }); it('should not exceed the maximum size of input array', function() { numLimitInput.clear(); numLimitInput.sendKeys('100'); letterLimitInput.clear(); letterLimitInput.sendKeys('100'); longNumberLimitInput.clear(); longNumberLimitInput.sendKeys('100'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342'); }); </file> </example> */ function limitToFilter() { return function(input, limit) { if (isNumber(input)) input = input.toString(); if (!isArray(input) && !isString(input)) return input; if (Math.abs(Number(limit)) === Infinity) { limit = Number(limit); } else { limit = int(limit); } if (isString(input)) { //NaN check on limit if (limit) { return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); } else { return ""; } } var out = [], i, n; // if abs(limit) exceeds maximum length, trim it if (limit > input.length) limit = input.length; else if (limit < -input.length) limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { i = input.length + limit; n = input.length; } for (; i < n; i++) { out.push(input[i]); } return out; }; } /** * @ngdoc filter * @name orderBy * @kind function * * @description * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically * for strings and numerically for numbers. Note: if you notice numbers are not being sorted * correctly, make sure they are actually being saved as numbers and not strings. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression. The result of this expression is used to compare elements * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by * 3 first characters of a property called `name`). The result of a constant expression * is interpreted as a property name to be used in comparisons (for example `"special name"` * to sort object by the value of their `special name` property). An expression can be * optionally prefixed with `+` or `-` to control ascending or descending sort order * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array * element itself is used to compare where sorting. * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * If the predicate is missing or empty then it defaults to `'+'`. * * @param {boolean=} reverse Reverse the order of the array. * @returns {Array} Sorted copy of the source array. * * @example <example module="orderByExample"> <file name="index.html"> <script> angular.module('orderByExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}]; $scope.predicate = '-age'; }]); </script> <div ng-controller="ExampleController"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> </tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </file> </example> * * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the * desired parameters. * * Example: * * @example <example module="orderByExample"> <file name="index.html"> <div ng-controller="ExampleController"> <table class="friend"> <tr> <th><a href="" ng-click="reverse=false;order('name', false)">Name</a> (<a href="" ng-click="order('-name',false)">^</a>)</th> <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th> <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th> </tr> <tr ng-repeat="friend in friends"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </file> <file name="script.js"> angular.module('orderByExample', []) .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) { var orderBy = $filter('orderBy'); $scope.friends = [ { name: 'John', phone: '555-1212', age: 10 }, { name: 'Mary', phone: '555-9876', age: 19 }, { name: 'Mike', phone: '555-4321', age: 21 }, { name: 'Adam', phone: '555-5678', age: 35 }, { name: 'Julie', phone: '555-8765', age: 29 } ]; $scope.order = function(predicate, reverse) { $scope.friends = orderBy($scope.friends, predicate, reverse); }; $scope.order('-age',false); }]); </file> </example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse) { return function(array, sortPredicate, reverseOrder) { if (!(isArrayLike(array))) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate]; if (sortPredicate.length === 0) { sortPredicate = ['+']; } sortPredicate = sortPredicate.map(function(predicate) { var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } if (predicate === '') { // Effectively no predicate was passed so we compare identity return reverseComparator(function(a, b) { return compare(a, b); }, descending); } get = $parse(predicate); if (get.constant) { var key = get(); return reverseComparator(function(a, b) { return compare(a[key], b[key]); }, descending); } } return reverseComparator(function(a, b) { return compare(get(a),get(b)); }, descending); }); return slice.call(array).sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2) { for (var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return descending ? function(a, b) {return comp(b,a);} : comp; } function compare(v1, v2) { var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (isDate(v1) && isDate(v2)) { v1 = v1.valueOf(); v2 = v2.valueOf(); } if (t1 == "string") { v1 = v1.toLowerCase(); v2 = v2.toLowerCase(); } if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } }; } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive }; } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /** * @ngdoc directive * @name a * @restrict E * * @description * Modifies the default behavior of the html A tag so that the default action is prevented when * the href attribute is empty. * * This change permits the easy creation of action links with the `ngClick` directive * without changing the location or causing page reloads, e.g.: * `<a href="" ng-click="list.addItem()">Add Item</a>` */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { if (!attr.href && !attr.xlinkHref && !attr.name) { return function(scope, element) { // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? 'xlink:href' : 'href'; element.on('click', function(event) { // if we have no href url, then don't navigate anywhere. if (!element.attr(href)) { event.preventDefault(); } }); }; } } }); /** * @ngdoc directive * @name ngHref * @restrict A * @priority 99 * * @description * Using Angular markup like `{{hash}}` in an href attribute will * make the link go to the wrong URL if the user clicks it before * Angular has a chance to replace the `{{hash}}` markup with its * value. Until Angular replaces the markup the link will be broken * and will most likely return a 404 error. * * The `ngHref` directive solves this problem. * * The wrong way to write it: * ```html * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a> * ``` * * The correct way to write it: * ```html * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a> * ``` * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes * in links and their different behaviors: <example> <file name="index.html"> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </file> <file name="protractor.js" type="protractor"> it('should execute ng-click but not reload when href without value', function() { element(by.id('link-1')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('1'); expect(element(by.id('link-1')).getAttribute('href')).toBe(''); }); it('should execute ng-click but not reload when href empty string', function() { element(by.id('link-2')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('2'); expect(element(by.id('link-2')).getAttribute('href')).toBe(''); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); element(by.id('link-3')).click(); // At this point, we navigate away from an Angular page, so we need // to use browser.driver to get the base webdriver. browser.wait(function() { return browser.driver.getCurrentUrl().then(function(url) { return url.match(/\/123$/); }); }, 5000, 'page should navigate to /123'); }); xit('should execute ng-click but not reload when href empty string and name specified', function() { element(by.id('link-4')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('4'); expect(element(by.id('link-4')).getAttribute('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element(by.id('link-5')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('5'); expect(element(by.id('link-5')).getAttribute('href')).toBe(null); }); it('should only change url when only ng-href', function() { element(by.model('value')).clear(); element(by.model('value')).sendKeys('6'); expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); element(by.id('link-6')).click(); // At this point, we navigate away from an Angular page, so we need // to use browser.driver to get the base webdriver. browser.wait(function() { return browser.driver.getCurrentUrl().then(function(url) { return url.match(/\/6$/); }); }, 5000, 'page should navigate to /6'); }); </file> </example> */ /** * @ngdoc directive * @name ngSrc * @restrict A * @priority 99 * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * ```html * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * ``` * * The correct way to write it: * ```html * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * ``` * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ngSrcset * @restrict A * @priority 99 * * @description * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrcset` directive solves this problem. * * The buggy way to write it: * ```html * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * ``` * * The correct way to write it: * ```html * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * ``` * * @element IMG * @param {template} ngSrcset any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ngDisabled * @restrict A * @priority 100 * * @description * * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * ```html * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * ``` * * The HTML specification does not require browsers to preserve the values of boolean attributes * such as disabled. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngDisabled` directive solves this problem for the `disabled` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * * @example <example> <file name="index.html"> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </file> <file name="protractor.js" type="protractor"> it('should toggle button', function() { expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); element(by.model('checked')).click(); expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); }); </file> </example> * * @element INPUT * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, * then special attribute "disabled" will be set on the element */ /** * @ngdoc directive * @name ngChecked * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as checked. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngChecked` directive solves this problem for the `checked` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * @example <example> <file name="index.html"> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </file> <file name="protractor.js" type="protractor"> it('should check both checkBoxes', function() { expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); element(by.model('master')).click(); expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); }); </file> </example> * * @element INPUT * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, * then special attribute "checked" will be set on the element */ /** * @ngdoc directive * @name ngReadonly * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as readonly. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngReadonly` directive solves this problem for the `readonly` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * @example <example> <file name="index.html"> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </file> <file name="protractor.js" type="protractor"> it('should toggle readonly attr', function() { expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); element(by.model('checked')).click(); expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); }); </file> </example> * * @element INPUT * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, * then special attribute "readonly" will be set on the element */ /** * @ngdoc directive * @name ngSelected * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as selected. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngSelected` directive solves this problem for the `selected` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * * @example <example> <file name="index.html"> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </file> <file name="protractor.js" type="protractor"> it('should select Greetings!', function() { expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); element(by.model('selected')).click(); expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); }); </file> </example> * * @element OPTION * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, * then special attribute "selected" will be set on the element */ /** * @ngdoc directive * @name ngOpen * @restrict A * @priority 100 * * @description * The HTML specification does not require browsers to preserve the values of boolean attributes * such as open. (Their presence means true and their absence means false.) * If we put an Angular interpolation expression into such an attribute then the * binding information would be lost when the browser removes the attribute. * The `ngOpen` directive solves this problem for the `open` attribute. * This complementary directive is not removed by the browser and so provides * a permanent reliable place to store the binding information. * @example <example> <file name="index.html"> Check me check multiple: <input type="checkbox" ng-model="open"><br/> <details id="details" ng-open="open"> <summary>Show/Hide me</summary> </details> </file> <file name="protractor.js" type="protractor"> it('should toggle open', function() { expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); element(by.model('open')).click(); expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); }); </file> </example> * * @element DETAILS * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, * then special attribute "open" will be set on the element */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { // binding to multiple is not supported if (propName == "multiple") return; var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { restrict: 'A', priority: 100, link: function(scope, element, attr) { scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { attr.$set(attrName, !!value); }); } }; }; }); // aliased input attrs are evaluated forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { ngAttributeAliasDirectives[ngAttr] = function() { return { priority: 100, link: function(scope, element, attr) { //special case ngPattern when a literal regular expression value //is used as the expression (this way we don't have to watch anything). if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") { var match = attr.ngPattern.match(REGEX_STRING_REGEXP); if (match) { attr.$set("ngPattern", new RegExp(match[1], match[2])); return; } } scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { attr.$set(ngAttr, value); }); } }; }; }); // ng-src, ng-srcset, ng-href are interpolated forEach(['src', 'srcset', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { var propName = attrName, name = attrName; if (attrName === 'href' && toString.call(element.prop('href')) === '[object SVGAnimatedString]') { name = 'xlinkHref'; attr.$attr[name] = 'xlink:href'; propName = null; } attr.$observe(normalized, function(value) { if (!value) { if (attrName === 'href') { attr.$set(name, null); } return; } attr.$set(name, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect. // we use attr[attrName] value since $set can sanitize the url. if (msie && propName) element.prop(propName, attr[name]); }); } }; }; }); /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true */ var nullFormCtrl = { $addControl: noop, $$renameControl: nullFormRenameControl, $removeControl: noop, $setValidity: noop, $setDirty: noop, $setPristine: noop, $setSubmitted: noop }, SUBMITTED_CLASS = 'ng-submitted'; function nullFormRenameControl(control, name) { control.$name = name; } /** * @ngdoc type * @name form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containing forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * @property {boolean} $submitted True if user has submitted the form even if its invalid. * * @property {Object} $error Is an object hash, containing references to controls or * forms with failing validators, where: * * - keys are validation tokens (error names), * - values are arrays of controls or forms that have a failing validator for given error name. * * Built-in validation tokens: * * - `email` * - `max` * - `maxlength` * - `min` * - `minlength` * - `number` * - `pattern` * - `required` * - `url` * - `date` * - `datetimelocal` * - `time` * - `week` * - `month` * * @description * `FormController` keeps track of all its controls and nested forms as well as the state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; function FormController(element, attrs, $scope, $animate, $interpolate) { var form = this, controls = []; var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl; // init state form.$error = {}; form.$$success = {}; form.$pending = undefined; form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope); form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; form.$submitted = false; parentForm.$addControl(form); /** * @ngdoc method * @name form.FormController#$rollbackViewValue * * @description * Rollback all form controls pending updates to the `$modelValue`. * * Updates may be pending by a debounced event or because the input is waiting for a some future * event defined in `ng-model-options`. This method is typically needed by the reset button of * a form that uses `ng-model-options` to pend updates. */ form.$rollbackViewValue = function() { forEach(controls, function(control) { control.$rollbackViewValue(); }); }; /** * @ngdoc method * @name form.FormController#$commitViewValue * * @description * Commit all form controls pending updates to the `$modelValue`. * * Updates may be pending by a debounced event or because the input is waiting for a some future * event defined in `ng-model-options`. This method is rarely needed as `NgModelController` * usually handles calling this in response to input events. */ form.$commitViewValue = function() { forEach(controls, function(control) { control.$commitViewValue(); }); }; /** * @ngdoc method * @name form.FormController#$addControl * * @description * Register a control with the form. * * Input elements using ngModelController do this automatically when they are linked. */ form.$addControl = function(control) { // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored // and not added to the scope. Now we throw an error. assertNotHasOwnProperty(control.$name, 'input'); controls.push(control); if (control.$name) { form[control.$name] = control; } }; // Private API: rename a form control form.$$renameControl = function(control, newName) { var oldName = control.$name; if (form[oldName] === control) { delete form[oldName]; } form[newName] = control; control.$name = newName; }; /** * @ngdoc method * @name form.FormController#$removeControl * * @description * Deregister a control from the form. * * Input elements using ngModelController do this automatically when they are destroyed. */ form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(form.$pending, function(value, name) { form.$setValidity(name, null, control); }); forEach(form.$error, function(value, name) { form.$setValidity(name, null, control); }); arrayRemove(controls, control); }; /** * @ngdoc method * @name form.FormController#$setValidity * * @description * Sets the validity of a form control. * * This method will also propagate to parent forms. */ addSetValidityMethod({ ctrl: this, $element: element, set: function(object, property, control) { var list = object[property]; if (!list) { object[property] = [control]; } else { var index = list.indexOf(control); if (index === -1) { list.push(control); } } }, unset: function(object, property, control) { var list = object[property]; if (!list) { return; } arrayRemove(list, control); if (list.length === 0) { delete object[property]; } }, parentForm: parentForm, $animate: $animate }); /** * @ngdoc method * @name form.FormController#$setDirty * * @description * Sets the form to a dirty state. * * This method can be called to add the 'ng-dirty' class and set the form to a dirty * state (ng-dirty class). This method will also propagate to parent forms. */ form.$setDirty = function() { $animate.removeClass(element, PRISTINE_CLASS); $animate.addClass(element, DIRTY_CLASS); form.$dirty = true; form.$pristine = false; parentForm.$setDirty(); }; /** * @ngdoc method * @name form.FormController#$setPristine * * @description * Sets the form to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the form to its pristine * state (ng-pristine class). This method will also propagate to all the controls contained * in this form. * * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after * saving or resetting it. */ form.$setPristine = function() { $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); form.$dirty = false; form.$pristine = true; form.$submitted = false; forEach(controls, function(control) { control.$setPristine(); }); }; /** * @ngdoc method * @name form.FormController#$setUntouched * * @description * Sets the form to its untouched state. * * This method can be called to remove the 'ng-touched' class and set the form controls to their * untouched state (ng-untouched class). * * Setting a form controls back to their untouched state is often useful when setting the form * back to its pristine state. */ form.$setUntouched = function() { forEach(controls, function(control) { control.$setUntouched(); }); }; /** * @ngdoc method * @name form.FormController#$setSubmitted * * @description * Sets the form to its submitted state. */ form.$setSubmitted = function() { $animate.addClass(element, SUBMITTED_CLASS); form.$submitted = true; parentForm.$setSubmitted(); }; } /** * @ngdoc directive * @name ngForm * @restrict EAC * * @description * Nestable alias of {@link ng.directive:form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * Note: the purpose of `ngForm` is to group controls, * but not to be a replacement for the `<form>` tag with all of its capabilities * (e.g. posting to the server, ...). * * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name form * @restrict E * * @description * Directive that instantiates * {@link form.FormController FormController}. * * If the `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link ng.directive:ngForm `ngForm`} * * In Angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to * `<form>` but can be nested. This allows you to have nested forms, which is very useful when * using Angular validation directives in forms that are dynamically generated using the * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name` * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an * `ngForm` directive and nest these in an outer `form` element. * * * # CSS classes * - `ng-valid` is set if the form is valid. * - `ng-invalid` is set if the form is invalid. * - `ng-pristine` is set if the form is pristine. * - `ng-dirty` is set if the form is dirty. * - `ng-submitted` is set if the form was submitted. * * Keep in mind that ngAnimate can detect each of these classes when added and removed. * * * # Submitting a form and preventing the default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in an application-specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element * - {@link ng.directive:ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} * or {@link ng.directive:ngClick ngClick} directives. * This is because of the following form submission rules in the HTML specification: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` * to have access to the updated model. * * ## Animation Hooks * * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any * other validations that are performed within the form. Animations in ngForm are similar to how * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well * as JS animations. * * The following example shows a simple way to utilize CSS transitions to style a form element * that has been rendered as invalid after it has been validated: * * <pre> * //be sure to include ngAnimate as a module to hook into more * //advanced animations * .my-form { * transition:0.5s linear all; * background: white; * } * .my-form.ng-invalid { * background: red; * color:white; * } * </pre> * * @example <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample"> <file name="index.html"> <script> angular.module('formExample', []) .controller('FormController', ['$scope', function($scope) { $scope.userType = 'guest'; }]); </script> <style> .my-form { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; background: transparent; } .my-form.ng-invalid { background: red; } </style> <form name="myForm" ng-controller="FormController" class="my-form"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.required">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> </form> </file> <file name="protractor.js" type="protractor"> it('should initialize to model', function() { var userType = element(by.binding('userType')); var valid = element(by.binding('myForm.input.$valid')); expect(userType.getText()).toContain('guest'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { var userType = element(by.binding('userType')); var valid = element(by.binding('myForm.input.$valid')); var userInput = element(by.model('userType')); userInput.clear(); userInput.sendKeys(''); expect(userType.getText()).toEqual('userType ='); expect(valid.getText()).toContain('false'); }); </file> </example> * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. */ var formDirectiveFactory = function(isNgForm) { return ['$timeout', function($timeout) { var formDirective = { name: 'form', restrict: isNgForm ? 'EAC' : 'E', controller: FormController, compile: function ngFormCompile(formElement) { // Setup initial state of the control formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); return { pre: function ngFormPreLink(scope, formElement, attr, controller) { // if `action` attr is not present on the form, prevent the default action (submission) if (!('action' in attr)) { // we can't use jq events because if a form is destroyed during submission the default // action is not prevented. see #1238 // // IE 9 is not affected because it doesn't fire a submit event and try to do a full // page reload if the form was destroyed by submission of the form via a click handler // on a button in the form. Looks like an IE9 specific bug. var handleFormSubmission = function(event) { scope.$apply(function() { controller.$commitViewValue(); controller.$setSubmitted(); }); event.preventDefault(); }; addEventListenerFn(formElement[0], 'submit', handleFormSubmission); // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. formElement.on('$destroy', function() { $timeout(function() { removeEventListenerFn(formElement[0], 'submit', handleFormSubmission); }, 0, false); }); } var parentFormCtrl = controller.$$parentForm, alias = controller.$name; if (alias) { setter(scope, alias, controller, alias); attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) { if (alias === newValue) return; setter(scope, alias, undefined, alias); alias = newValue; setter(scope, alias, controller, alias); parentFormCtrl.$$renameControl(controller, alias); }); } formElement.on('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { setter(scope, alias, undefined, alias); } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } }; } }; return formDirective; }]; }; var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); /* global VALID_CLASS: true, INVALID_CLASS: true, PRISTINE_CLASS: true, DIRTY_CLASS: true, UNTOUCHED_CLASS: true, TOUCHED_CLASS: true, */ // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231 var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/; var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/; var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/; var MONTH_REGEXP = /^(\d{4})-(\d\d)$/; var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; var $ngModelMinErr = new minErr('ngModel'); var inputType = { /** * @ngdoc input * @name input[text] * * @description * Standard HTML text input with angular data binding, inherited by most of the `input` elements. * * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Adds `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of * any length. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string * that contains the regular expression body that will be converted to a regular expression * as in the ngPattern directive. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match * a RegExp found by evaluating the Angular expression given in the attribute value. * If the expression evaluates to a RegExp object then this is used directly. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$` * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. * This parameter is ignored for input[type=password] controls, which will never trim the * input. * * @example <example name="text-input-directive" module="textInputExample"> <file name="index.html"> <script> angular.module('textInputExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.text = 'guest'; $scope.word = /^\s*\w*\s*$/; }]); </script> <form name="myForm" ng-controller="ExampleController"> Single word: <input type="text" name="input" ng-model="text" ng-pattern="word" required ng-trim="false"> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var text = element(by.binding('text')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('text')); it('should initialize to model', function() { expect(text.getText()).toContain('guest'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if multi word', function() { input.clear(); input.sendKeys('hello world'); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'text': textInputType, /** * @ngdoc input * @name input[date] * * @description * Input with date validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many * modern browsers do not yet support this input type, it is important to provide cues to users on the * expected input format via a placeholder or label. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO date string (yyyy-MM-dd). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be * a valid ISO date string (yyyy-MM-dd). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="date-input-directive" module="dateInputExample"> <file name="index.html"> <script> angular.module('dateInputExample', []) .controller('DateController', ['$scope', function($scope) { $scope.value = new Date(2013, 9, 22); }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a date in 2013: <input type="date" id="exampleInput" name="input" ng-model="value" placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.date"> Not a valid date!</span> <tt>value = {{value | date: "yyyy-MM-dd"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "yyyy-MM-dd"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (see https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2013-10-22'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-01-01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'date': createDateInputType('date', DATE_REGEXP, createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']), 'yyyy-MM-dd'), /** * @ngdoc input * @name input[datetime-local] * * @description * Input with datetime validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="datetimelocal-input-directive" module="dateExample"> <file name="index.html"> <script> angular.module('dateExample', []) .controller('DateController', ['$scope', function($scope) { $scope.value = new Date(2010, 11, 28, 14, 57); }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a date between in 2013: <input type="datetime-local" id="exampleInput" name="input" ng-model="value" placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.datetimelocal"> Not a valid date!</span> <tt>value = {{value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm:ss"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2010-12-28T14:57:00'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-01-01T23:59:00'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP, createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']), 'yyyy-MM-ddTHH:mm:ss.sss'), /** * @ngdoc input * @name input[time] * * @description * Input with time validation and transformation. In browsers that do not yet support * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO time format (HH:mm:ss). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a * valid ISO time format (HH:mm:ss). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="time-input-directive" module="timeExample"> <file name="index.html"> <script> angular.module('timeExample', []) .controller('DateController', ['$scope', function($scope) { $scope.value = new Date(1970, 0, 1, 14, 57, 0); }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a between 8am and 5pm: <input type="time" id="exampleInput" name="input" ng-model="value" placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.time"> Not a valid date!</span> <tt>value = {{value | date: "HH:mm:ss"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "HH:mm:ss"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('14:57:00'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('23:59:00'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'time': createDateInputType('time', TIME_REGEXP, createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']), 'HH:mm:ss.sss'), /** * @ngdoc input * @name input[week] * * @description * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * week format (yyyy-W##), for example: `2013-W02`. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a * valid ISO week format (yyyy-W##). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be * a valid ISO week format (yyyy-W##). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="week-input-directive" module="weekExample"> <file name="index.html"> <script> angular.module('weekExample', []) .controller('DateController', ['$scope', function($scope) { $scope.value = new Date(2013, 0, 3); }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a date between in 2013: <input id="exampleInput" type="week" name="input" ng-model="value" placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.week"> Not a valid date!</span> <tt>value = {{value | date: "yyyy-Www"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "yyyy-Www"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2013-W01'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-W01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'), /** * @ngdoc input * @name input[month] * * @description * Input with month validation and transformation. In browsers that do not yet support * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 * month format (yyyy-MM), for example: `2009-01`. * * The model must always be a Date object, otherwise Angular will throw an error. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. * If the model is not set to the first of the month, the next view to model update will set it * to the first of the month. * * The timezone to be used to read/write the `Date` instance in the model can be defined using * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be * a valid ISO month format (yyyy-MM). * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must * be a valid ISO month format (yyyy-MM). * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="month-input-directive" module="monthExample"> <file name="index.html"> <script> angular.module('monthExample', []) .controller('DateController', ['$scope', function($scope) { $scope.value = new Date(2013, 9, 1); }]); </script> <form name="myForm" ng-controller="DateController as dateCtrl"> Pick a month int 2013: <input id="exampleInput" type="month" name="input" ng-model="value" placeholder="yyyy-MM" min="2013-01" max="2013-12" required /> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.month"> Not a valid month!</span> <tt>value = {{value | date: "yyyy-MM"}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value | date: "yyyy-MM"')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); // currently protractor/webdriver does not support // sending keys to all known HTML5 input controls // for various browsers (https://github.com/angular/protractor/issues/562). function setInput(val) { // set the value of the element and force validation. var scr = "var ipt = document.getElementById('exampleInput'); " + "ipt.value = '" + val + "';" + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; browser.executeScript(scr); } it('should initialize to model', function() { expect(value.getText()).toContain('2013-10'); expect(valid.getText()).toContain('myForm.input.$valid = true'); }); it('should be invalid if empty', function() { setInput(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); it('should be invalid if over max', function() { setInput('2015-01'); expect(value.getText()).toContain(''); expect(valid.getText()).toContain('myForm.input.$valid = false'); }); </file> </example> */ 'month': createDateInputType('month', MONTH_REGEXP, createDateParser(MONTH_REGEXP, ['yyyy', 'MM']), 'yyyy-MM'), /** * @ngdoc input * @name input[number] * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * The model must always be a number, otherwise Angular will throw an error. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of * any length. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string * that contains the regular expression body that will be converted to a regular expression * as in the ngPattern directive. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match * a RegExp found by evaluating the Angular expression given in the attribute value. * If the expression evaluates to a RegExp object then this is used directly. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$` * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="number-input-directive" module="numberExample"> <file name="index.html"> <script> angular.module('numberExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.value = 12; }]); </script> <form name="myForm" ng-controller="ExampleController"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var value = element(by.binding('value')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('value')); it('should initialize to model', function() { expect(value.getText()).toContain('12'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if over max', function() { input.clear(); input.sendKeys('123'); expect(value.getText()).toEqual('value ='); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'number': numberInputType, /** * @ngdoc input * @name input[url] * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * <div class="alert alert-warning"> * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify * the built-in validators (see the {@link guide/forms Forms guide}) * </div> * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of * any length. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string * that contains the regular expression body that will be converted to a regular expression * as in the ngPattern directive. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match * a RegExp found by evaluating the Angular expression given in the attribute value. * If the expression evaluates to a RegExp object then this is used directly. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$` * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="url-input-directive" module="urlExample"> <file name="index.html"> <script> angular.module('urlExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.text = 'http://google.com'; }]); </script> <form name="myForm" ng-controller="ExampleController"> URL: <input type="url" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var text = element(by.binding('text')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('text')); it('should initialize to model', function() { expect(text.getText()).toContain('http://google.com'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if not url', function() { input.clear(); input.sendKeys('box'); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'url': urlInputType, /** * @ngdoc input * @name input[email] * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * <div class="alert alert-warning"> * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide}) * </div> * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of * any length. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string * that contains the regular expression body that will be converted to a regular expression * as in the ngPattern directive. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match * a RegExp found by evaluating the Angular expression given in the attribute value. * If the expression evaluates to a RegExp object then this is used directly. * If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$` * characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="email-input-directive" module="emailExample"> <file name="index.html"> <script> angular.module('emailExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.text = 'me@example.com'; }]); </script> <form name="myForm" ng-controller="ExampleController"> Email: <input type="email" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> var text = element(by.binding('text')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('text')); it('should initialize to model', function() { expect(text.getText()).toContain('me@example.com'); expect(valid.getText()).toContain('true'); }); it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(text.getText()).toEqual('text ='); expect(valid.getText()).toContain('false'); }); it('should be invalid if not email', function() { input.clear(); input.sendKeys('xxx'); expect(valid.getText()).toContain('false'); }); </file> </example> */ 'email': emailInputType, /** * @ngdoc input * @name input[radio] * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {string} ngValue Angular expression which sets the value to which the expression should * be set when selected. * * @example <example name="radio-input-directive" module="radioExample"> <file name="index.html"> <script> angular.module('radioExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.color = 'blue'; $scope.specialValue = { "id": "12345", "value": "green" }; }]); </script> <form name="myForm" ng-controller="ExampleController"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> <tt>color = {{color | json}}</tt><br/> </form> Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. </file> <file name="protractor.js" type="protractor"> it('should change state', function() { var color = element(by.binding('color')); expect(color.getText()).toContain('blue'); element.all(by.model('color')).get(0).click(); expect(color.getText()).toContain('red'); }); </file> </example> */ 'radio': radioInputType, /** * @ngdoc input * @name input[checkbox] * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {expression=} ngTrueValue The value to which the expression should be set when selected. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <example name="checkbox-input-directive" module="checkboxExample"> <file name="index.html"> <script> angular.module('checkboxExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.value1 = true; $scope.value2 = 'YES' }]); </script> <form name="myForm" ng-controller="ExampleController"> Value1: <input type="checkbox" ng-model="value1"> <br/> Value2: <input type="checkbox" ng-model="value2" ng-true-value="'YES'" ng-false-value="'NO'"> <br/> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </form> </file> <file name="protractor.js" type="protractor"> it('should change state', function() { var value1 = element(by.binding('value1')); var value2 = element(by.binding('value2')); expect(value1.getText()).toContain('true'); expect(value2.getText()).toContain('YES'); element(by.model('value1')).click(); element(by.model('value2')).click(); expect(value1.getText()).toContain('false'); expect(value2.getText()).toContain('NO'); }); </file> </example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop, 'file': noop }; function stringBasedInputType(ctrl) { ctrl.$formatters.push(function(value) { return ctrl.$isEmpty(value) ? value : value.toString(); }); } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { baseInputType(scope, element, attr, ctrl, $sniffer, $browser); stringBasedInputType(ctrl); } function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) { var placeholder = element[0].placeholder, noevent = {}; var type = lowercase(element[0].type); // In composition mode, users are still inputing intermediate text buffer, // hold the listener until composition is done. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent if (!$sniffer.android) { var composing = false; element.on('compositionstart', function(data) { composing = true; }); element.on('compositionend', function() { composing = false; listener(); }); } var listener = function(ev) { if (composing) return; var value = element.val(), event = ev && ev.type; // IE (11 and under) seem to emit an 'input' event if the placeholder value changes. // We don't want to dirty the value when this happens, so we abort here. Unfortunately, // IE also sends input events for other non-input-related things, (such as focusing on a // form control), so this change is not entirely enough to solve this. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) { placeholder = element[0].placeholder; return; } // By default we will trim the value // If the attribute ng-trim exists we will avoid trimming // If input type is 'password', the value is never trimmed if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) { value = trim(value); } // If a control is suffering from bad input (due to native validators), browsers discard its // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the // control's value is the same empty value twice in a row. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) { ctrl.$setViewValue(value, event); } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { element.on('input', listener); } else { var timeout; var deferListener = function(ev) { if (!timeout) { timeout = $browser.defer(function() { listener(ev); timeout = null; }); } }; element.on('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; deferListener(event); }); // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it if ($sniffer.hasEvent('paste')) { element.on('paste cut', deferListener); } } // if user paste into input using mouse on older browser // or form autocomplete on newer browser, we need "change" event to catch it element.on('change', listener); ctrl.$render = function() { element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; } function weekParser(isoWeek, existingDate) { if (isDate(isoWeek)) { return isoWeek; } if (isString(isoWeek)) { WEEK_REGEXP.lastIndex = 0; var parts = WEEK_REGEXP.exec(isoWeek); if (parts) { var year = +parts[1], week = +parts[2], hours = 0, minutes = 0, seconds = 0, milliseconds = 0, firstThurs = getFirstThursdayOfYear(year), addDays = (week - 1) * 7; if (existingDate) { hours = existingDate.getHours(); minutes = existingDate.getMinutes(); seconds = existingDate.getSeconds(); milliseconds = existingDate.getMilliseconds(); } return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds); } } return NaN; } function createDateParser(regexp, mapping) { return function(iso, date) { var parts, map; if (isDate(iso)) { return iso; } if (isString(iso)) { // When a date is JSON'ified to wraps itself inside of an extra // set of double quotes. This makes the date parsing code unable // to match the date string and parse it as a date. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') { iso = iso.substring(1, iso.length - 1); } if (ISO_DATE_REGEXP.test(iso)) { return new Date(iso); } regexp.lastIndex = 0; parts = regexp.exec(iso); if (parts) { parts.shift(); if (date) { map = { yyyy: date.getFullYear(), MM: date.getMonth() + 1, dd: date.getDate(), HH: date.getHours(), mm: date.getMinutes(), ss: date.getSeconds(), sss: date.getMilliseconds() / 1000 }; } else { map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 }; } forEach(parts, function(part, index) { if (index < mapping.length) { map[mapping[index]] = +part; } }); return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0); } } return NaN; }; } function createDateInputType(type, regexp, parseDate, format) { return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) { badInputChecker(scope, element, attr, ctrl); baseInputType(scope, element, attr, ctrl, $sniffer, $browser); var timezone = ctrl && ctrl.$options && ctrl.$options.timezone; var previousDate; ctrl.$$parserName = type; ctrl.$parsers.push(function(value) { if (ctrl.$isEmpty(value)) return null; if (regexp.test(value)) { // Note: We cannot read ctrl.$modelValue, as there might be a different // parser/formatter in the processing chain so that the model // contains some different data format! var parsedDate = parseDate(value, previousDate); if (timezone === 'UTC') { parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset()); } return parsedDate; } return undefined; }); ctrl.$formatters.push(function(value) { if (value && !isDate(value)) { throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value); } if (isValidDate(value)) { previousDate = value; if (previousDate && timezone === 'UTC') { var timezoneOffset = 60000 * previousDate.getTimezoneOffset(); previousDate = new Date(previousDate.getTime() + timezoneOffset); } return $filter('date')(value, format, timezone); } else { previousDate = null; return ''; } }); if (isDefined(attr.min) || attr.ngMin) { var minVal; ctrl.$validators.min = function(value) { return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal; }; attr.$observe('min', function(val) { minVal = parseObservedDateValue(val); ctrl.$validate(); }); } if (isDefined(attr.max) || attr.ngMax) { var maxVal; ctrl.$validators.max = function(value) { return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal; }; attr.$observe('max', function(val) { maxVal = parseObservedDateValue(val); ctrl.$validate(); }); } function isValidDate(value) { // Invalid Date: getTime() returns NaN return value && !(value.getTime && value.getTime() !== value.getTime()); } function parseObservedDateValue(val) { return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined; } }; } function badInputChecker(scope, element, attr, ctrl) { var node = element[0]; var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity); if (nativeValidation) { ctrl.$parsers.push(function(value) { var validity = element.prop(VALIDITY_STATE_PROPERTY) || {}; // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430): // - also sets validity.badInput (should only be validity.typeMismatch). // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email) // - can ignore this case as we can still read out the erroneous email... return validity.badInput && !validity.typeMismatch ? undefined : value; }); } } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { badInputChecker(scope, element, attr, ctrl); baseInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$$parserName = 'number'; ctrl.$parsers.push(function(value) { if (ctrl.$isEmpty(value)) return null; if (NUMBER_REGEXP.test(value)) return parseFloat(value); return undefined; }); ctrl.$formatters.push(function(value) { if (!ctrl.$isEmpty(value)) { if (!isNumber(value)) { throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value); } value = value.toString(); } return value; }); if (attr.min || attr.ngMin) { var minVal; ctrl.$validators.min = function(value) { return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal; }; attr.$observe('min', function(val) { if (isDefined(val) && !isNumber(val)) { val = parseFloat(val, 10); } minVal = isNumber(val) && !isNaN(val) ? val : undefined; // TODO(matsko): implement validateLater to reduce number of validations ctrl.$validate(); }); } if (attr.max || attr.ngMax) { var maxVal; ctrl.$validators.max = function(value) { return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal; }; attr.$observe('max', function(val) { if (isDefined(val) && !isNumber(val)) { val = parseFloat(val, 10); } maxVal = isNumber(val) && !isNaN(val) ? val : undefined; // TODO(matsko): implement validateLater to reduce number of validations ctrl.$validate(); }); } } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { // Note: no badInputChecker here by purpose as `url` is only a validation // in browsers, i.e. we can always read out input.value even if it is not valid! baseInputType(scope, element, attr, ctrl, $sniffer, $browser); stringBasedInputType(ctrl); ctrl.$$parserName = 'url'; ctrl.$validators.url = function(modelValue, viewValue) { var value = modelValue || viewValue; return ctrl.$isEmpty(value) || URL_REGEXP.test(value); }; } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { // Note: no badInputChecker here by purpose as `url` is only a validation // in browsers, i.e. we can always read out input.value even if it is not valid! baseInputType(scope, element, attr, ctrl, $sniffer, $browser); stringBasedInputType(ctrl); ctrl.$$parserName = 'email'; ctrl.$validators.email = function(modelValue, viewValue) { var value = modelValue || viewValue; return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); }; } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } var listener = function(ev) { if (element[0].checked) { ctrl.$setViewValue(attr.value, ev && ev.type); } }; element.on('click', listener); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function parseConstantExpr($parse, context, name, expression, fallback) { var parseFn; if (isDefined(expression)) { parseFn = $parse(expression); if (!parseFn.constant) { throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' + '`{1}`.', name, expression); } return parseFn(context); } return fallback; } function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true); var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false); var listener = function(ev) { ctrl.$setViewValue(element[0].checked, ev && ev.type); }; element.on('click', listener); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false` // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert // it to a boolean. ctrl.$isEmpty = function(value) { return value === false; }; ctrl.$formatters.push(function(value) { return equals(value, trueValue); }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name textarea * @restrict E * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link ng.directive:input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any * length. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. */ /** * @ngdoc directive * @name input * @restrict E * * @description * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding, * input state control, and validation. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers. * * <div class="alert alert-warning"> * **Note:** Not every feature offered is available for all input types. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`. * </div> * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {boolean=} ngRequired Sets `required` attribute if set to true * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any * length. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. * This parameter is ignored for input[type=password] controls, which will never trim the * input. * * @example <example name="input-directive" module="inputExample"> <file name="index.html"> <script> angular.module('inputExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.user = {name: 'guest', last: 'visitor'}; }]); </script> <div ng-controller="ExampleController"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </file> <file name="protractor.js" type="protractor"> var user = element(by.exactBinding('user')); var userNameValid = element(by.binding('myForm.userName.$valid')); var lastNameValid = element(by.binding('myForm.lastName.$valid')); var lastNameError = element(by.binding('myForm.lastName.$error')); var formValid = element(by.binding('myForm.$valid')); var userNameInput = element(by.model('user.name')); var userLastInput = element(by.model('user.last')); it('should initialize to model', function() { expect(user.getText()).toContain('{"name":"guest","last":"visitor"}'); expect(userNameValid.getText()).toContain('true'); expect(formValid.getText()).toContain('true'); }); it('should be invalid if empty when required', function() { userNameInput.clear(); userNameInput.sendKeys(''); expect(user.getText()).toContain('{"last":"visitor"}'); expect(userNameValid.getText()).toContain('false'); expect(formValid.getText()).toContain('false'); }); it('should be valid if empty when min length is set', function() { userLastInput.clear(); userLastInput.sendKeys(''); expect(user.getText()).toContain('{"name":"guest","last":""}'); expect(lastNameValid.getText()).toContain('true'); expect(formValid.getText()).toContain('true'); }); it('should be invalid if less than required min length', function() { userLastInput.clear(); userLastInput.sendKeys('xx'); expect(user.getText()).toContain('{"name":"guest"}'); expect(lastNameValid.getText()).toContain('false'); expect(lastNameError.getText()).toContain('minlength'); expect(formValid.getText()).toContain('false'); }); it('should be invalid if longer than max length', function() { userLastInput.clear(); userLastInput.sendKeys('some ridiculously long name'); expect(user.getText()).toContain('{"name":"guest"}'); expect(lastNameValid.getText()).toContain('false'); expect(lastNameError.getText()).toContain('maxlength'); expect(formValid.getText()).toContain('false'); }); </file> </example> */ var inputDirective = ['$browser', '$sniffer', '$filter', '$parse', function($browser, $sniffer, $filter, $parse) { return { restrict: 'E', require: ['?ngModel'], link: { pre: function(scope, element, attr, ctrls) { if (ctrls[0]) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, $browser, $filter, $parse); } } } }; }]; var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty', UNTOUCHED_CLASS = 'ng-untouched', TOUCHED_CLASS = 'ng-touched', PENDING_CLASS = 'ng-pending'; /** * @ngdoc type * @name ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model that the control is bound to. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. The functions are called in array order, each passing its return value through to the next. The last return value is forwarded to the {@link ngModel.NgModelController#$validators `$validators`} collection. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue `$viewValue`}. Returning `undefined` from a parser means a parse error occurred. In that case, no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel` will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is set to `true`. The parse error is stored in `ngModel.$error.parse`. * * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever the model value changes. The functions are called in reverse array order, each passing the value through to the next. The last return value is used as the actual DOM value. Used to format / convert values for display in the control. * ```js * function formatter(value) { * if (value) { * return value.toUpperCase(); * } * } * ngModel.$formatters.push(formatter); * ``` * * @property {Object.<string, function>} $validators A collection of validators that are applied * whenever the model value changes. The key value within the object refers to the name of the * validator while the function refers to the validation operation. The validation operation is * provided with the model value as an argument and must return a true or false value depending * on the response of that validation. * * ```js * ngModel.$validators.validCharacters = function(modelValue, viewValue) { * var value = modelValue || viewValue; * return /[0-9]+/.test(value) && * /[a-z]+/.test(value) && * /[A-Z]+/.test(value) && * /\W+/.test(value); * }; * ``` * * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided * is expected to return a promise when it is run during the model validation process. Once the promise * is delivered then the validation status will be set to true when fulfilled and false when rejected. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators * will only run once all synchronous validators have passed. * * Please note that if $http is used then it is important that the server returns a success HTTP response code * in order to fulfill the validation and a status level of `4xx` in order to reject the validation. * * ```js * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { * var value = modelValue || viewValue; * * // Lookup user by username * return $http.get('/api/users/' + value). * then(function resolved() { * //username exists, this means validation fails * return $q.reject('exists'); * }, function rejected() { * //username does not exist, therefore this validation passes * return true; * }); * }; * ``` * * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the * view value has changed. It is called with no arguments, and its return value is ignored. * This can be used in place of additional $watches against the model value. * * @property {Object} $error An object hash with all failing validator ids as keys. * @property {Object} $pending An object hash with all pending validator ids as keys. * * @property {boolean} $untouched True if control has not lost focus yet. * @property {boolean} $touched True if control has lost focus. * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * @property {string} $name The name attribute of the control. * * @description * * `NgModelController` provides API for the {@link ngModel `ngModel`} directive. * The controller contains services for data-binding, validation, CSS updates, and value formatting * and parsing. It purposefully does not contain any logic which deals with DOM rendering or * listening to DOM events. * Such DOM related logic should be provided by other directives which make use of * `NgModelController` for data-binding to control elements. * Angular provides this DOM logic for most {@link input `input`} elements. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example * custom control example} that uses `ngModelController` to bind to `contenteditable` elements. * * @example * ### Custom Control Example * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) * collaborate together to achieve the desired result. * * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element * contents be edited in place by the user. This will not work on older browsers. * * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`). * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks * that content using the `$sce` service. * * <example name="NgModelController" module="customControl" deps="angular-sanitize.js"> <file name="style.css"> [contenteditable] { border: 1px solid black; background-color: white; min-height: 20px; } .ng-invalid { border: 1px solid red; } </file> <file name="script.js"> angular.module('customControl', ['ngSanitize']). directive('contenteditable', ['$sce', function($sce) { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if (!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); }; // Listen for change events to enable binding element.on('blur keyup change', function() { scope.$evalAsync(read); }); read(); // initialize // Write data to the model function read() { var html = element.html(); // When we clear the content editable the browser leaves a <br> behind // If strip-br attribute is provided then we strip this out if ( attrs.stripBr && html == '<br>' ) { html = ''; } ngModel.$setViewValue(html); } } }; }]); </file> <file name="index.html"> <form name="myForm"> <div contenteditable name="myWidget" ng-model="userContent" strip-br="true" required>Change me!</div> <span ng-show="myForm.myWidget.$error.required">Required!</span> <hr> <textarea ng-model="userContent"></textarea> </form> </file> <file name="protractor.js" type="protractor"> it('should data-bind and become invalid', function() { if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') { // SafariDriver can't handle contenteditable // and Firefox driver can't clear contenteditables very well return; } var contentEditable = element(by.css('[contenteditable]')); var content = 'Change me!'; expect(contentEditable.getText()).toEqual(content); contentEditable.clear(); contentEditable.sendKeys(protractor.Key.BACK_SPACE); expect(contentEditable.getText()).toEqual(''); expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); }); </file> * </example> * * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate', function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity. this.$validators = {}; this.$asyncValidators = {}; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$untouched = true; this.$touched = false; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$error = {}; // keep invalid keys here this.$$success = {}; // keep valid keys here this.$pending = undefined; // keep pending keys here this.$name = $interpolate($attr.name || '', false)($scope); var parsedNgModel = $parse($attr.ngModel), parsedNgModelAssign = parsedNgModel.assign, ngModelGet = parsedNgModel, ngModelSet = parsedNgModelAssign, pendingDebounce = null, ctrl = this; this.$$setOptions = function(options) { ctrl.$options = options; if (options && options.getterSetter) { var invokeModelGetter = $parse($attr.ngModel + '()'), invokeModelSetter = $parse($attr.ngModel + '($$$p)'); ngModelGet = function($scope) { var modelValue = parsedNgModel($scope); if (isFunction(modelValue)) { modelValue = invokeModelGetter($scope); } return modelValue; }; ngModelSet = function($scope, newValue) { if (isFunction(parsedNgModel($scope))) { invokeModelSetter($scope, {$$$p: ctrl.$modelValue}); } else { parsedNgModelAssign($scope, ctrl.$modelValue); } }; } else if (!parsedNgModel.assign) { throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}", $attr.ngModel, startingTag($element)); } }; /** * @ngdoc method * @name ngModel.NgModelController#$render * * @description * Called when the view needs to be updated. It is expected that the user of the ng-model * directive will implement this method. * * The `$render()` method is invoked in the following situations: * * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last * committed value then `$render()` is called to update the input control. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and * the `$viewValue` are different to last time. * * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue` * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be * invoked if you only change a property on the objects. */ this.$render = noop; /** * @ngdoc method * @name ngModel.NgModelController#$isEmpty * * @description * This is called when we need to determine if the value of an input is empty. * * For instance, the required directive does this to work out if the input has data or not. * * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. * * You can override this for input directives whose concept of being empty is different to the * default. The `checkboxInputType` directive does this because in its case a value of `false` * implies empty. * * @param {*} value The value of the input to check for emptiness. * @returns {boolean} True if `value` is "empty". */ this.$isEmpty = function(value) { return isUndefined(value) || value === '' || value === null || value !== value; }; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, currentValidationRunId = 0; /** * @ngdoc method * @name ngModel.NgModelController#$setValidity * * @description * Change the validity state, and notify the form. * * This method can be called within $parsers/$formatters or a custom validation implementation. * However, in most cases it should be sufficient to use the `ngModel.$validators` and * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically. * * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` * (for unfulfilled `$asyncValidators`), so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined), * or skipped (null). Pending is used for unfulfilled `$asyncValidators`. * Skipped is used by Angular when validators do not run because of parse errors and * when `$asyncValidators` do not run because any of the `$validators` failed. */ addSetValidityMethod({ ctrl: this, $element: $element, set: function(object, property) { object[property] = true; }, unset: function(object, property) { delete object[property]; }, parentForm: parentForm, $animate: $animate }); /** * @ngdoc method * @name ngModel.NgModelController#$setPristine * * @description * Sets the control to its pristine state. * * This method can be called to remove the `ng-dirty` class and set the control to its pristine * state (`ng-pristine` class). A model is considered to be pristine when the control * has not been changed from when first compiled. */ this.$setPristine = function() { ctrl.$dirty = false; ctrl.$pristine = true; $animate.removeClass($element, DIRTY_CLASS); $animate.addClass($element, PRISTINE_CLASS); }; /** * @ngdoc method * @name ngModel.NgModelController#$setDirty * * @description * Sets the control to its dirty state. * * This method can be called to remove the `ng-pristine` class and set the control to its dirty * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed * from when first compiled. */ this.$setDirty = function() { ctrl.$dirty = true; ctrl.$pristine = false; $animate.removeClass($element, PRISTINE_CLASS); $animate.addClass($element, DIRTY_CLASS); parentForm.$setDirty(); }; /** * @ngdoc method * @name ngModel.NgModelController#$setUntouched * * @description * Sets the control to its untouched state. * * This method can be called to remove the `ng-touched` class and set the control to its * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched * by default, however this function can be used to restore that state if the model has * already been touched by the user. */ this.$setUntouched = function() { ctrl.$touched = false; ctrl.$untouched = true; $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS); }; /** * @ngdoc method * @name ngModel.NgModelController#$setTouched * * @description * Sets the control to its touched state. * * This method can be called to remove the `ng-untouched` class and set the control to its * touched state (`ng-touched` class). A model is considered to be touched when the user has * first focused the control element and then shifted focus away from the control (blur event). */ this.$setTouched = function() { ctrl.$touched = true; ctrl.$untouched = false; $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS); }; /** * @ngdoc method * @name ngModel.NgModelController#$rollbackViewValue * * @description * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`, * which may be caused by a pending debounced event or because the input is waiting for a some * future event. * * If you have an input that uses `ng-model-options` to set up debounced events or events such * as blur you can have a situation where there is a period when the `$viewValue` * is out of synch with the ngModel's `$modelValue`. * * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue` * programmatically before these debounced/future events have resolved/occurred, because Angular's * dirty checking mechanism is not able to tell whether the model has actually changed or not. * * The `$rollbackViewValue()` method should be called before programmatically changing the model of an * input which may have such events pending. This is important in order to make sure that the * input field will be updated with the new model value and any pending operations are cancelled. * * <example name="ng-model-cancel-update" module="cancel-update-example"> * <file name="app.js"> * angular.module('cancel-update-example', []) * * .controller('CancelUpdateController', ['$scope', function($scope) { * $scope.resetWithCancel = function(e) { * if (e.keyCode == 27) { * $scope.myForm.myInput1.$rollbackViewValue(); * $scope.myValue = ''; * } * }; * $scope.resetWithoutCancel = function(e) { * if (e.keyCode == 27) { * $scope.myValue = ''; * } * }; * }]); * </file> * <file name="index.html"> * <div ng-controller="CancelUpdateController"> * <p>Try typing something in each input. See that the model only updates when you * blur off the input. * </p> * <p>Now see what happens if you start typing then press the Escape key</p> * * <form name="myForm" ng-model-options="{ updateOn: 'blur' }"> * <p>With $rollbackViewValue()</p> * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/> * myValue: "{{ myValue }}" * * <p>Without $rollbackViewValue()</p> * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/> * myValue: "{{ myValue }}" * </form> * </div> * </file> * </example> */ this.$rollbackViewValue = function() { $timeout.cancel(pendingDebounce); ctrl.$viewValue = ctrl.$$lastCommittedViewValue; ctrl.$render(); }; /** * @ngdoc method * @name ngModel.NgModelController#$validate * * @description * Runs each of the registered validators (first synchronous validators and then * asynchronous validators). * If the validity changes to invalid, the model will be set to `undefined`, * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`. * If the validity changes to valid, it will set the model to the last available valid * modelValue, i.e. either the last parsed value or the last value set from the scope. */ this.$validate = function() { // ignore $validate before model is initialized if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) { return; } var viewValue = ctrl.$$lastCommittedViewValue; // Note: we use the $$rawModelValue as $modelValue might have been // set to undefined during a view -> model update that found validation // errors. We can't parse the view here, since that could change // the model although neither viewValue nor the model on the scope changed var modelValue = ctrl.$$rawModelValue; // Check if the there's a parse error, so we don't unset it accidentially var parserName = ctrl.$$parserName || 'parse'; var parserValid = ctrl.$error[parserName] ? false : undefined; var prevValid = ctrl.$valid; var prevModelValue = ctrl.$modelValue; var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid; ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) { // If there was no change in validity, don't update the model // This prevents changing an invalid modelValue to undefined if (!allowInvalid && prevValid !== allValid) { // Note: Don't check ctrl.$valid here, as we could have // external validators (e.g. calculated on the server), // that just call $setValidity and need the model value // to calculate their validity. ctrl.$modelValue = allValid ? modelValue : undefined; if (ctrl.$modelValue !== prevModelValue) { ctrl.$$writeModelToScope(); } } }); }; this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) { currentValidationRunId++; var localValidationRunId = currentValidationRunId; // check parser error if (!processParseErrors(parseValid)) { validationDone(false); return; } if (!processSyncValidators()) { validationDone(false); return; } processAsyncValidators(); function processParseErrors(parseValid) { var errorKey = ctrl.$$parserName || 'parse'; if (parseValid === undefined) { setValidity(errorKey, null); } else { setValidity(errorKey, parseValid); if (!parseValid) { forEach(ctrl.$validators, function(v, name) { setValidity(name, null); }); forEach(ctrl.$asyncValidators, function(v, name) { setValidity(name, null); }); return false; } } return true; } function processSyncValidators() { var syncValidatorsValid = true; forEach(ctrl.$validators, function(validator, name) { var result = validator(modelValue, viewValue); syncValidatorsValid = syncValidatorsValid && result; setValidity(name, result); }); if (!syncValidatorsValid) { forEach(ctrl.$asyncValidators, function(v, name) { setValidity(name, null); }); return false; } return true; } function processAsyncValidators() { var validatorPromises = []; var allValid = true; forEach(ctrl.$asyncValidators, function(validator, name) { var promise = validator(modelValue, viewValue); if (!isPromiseLike(promise)) { throw $ngModelMinErr("$asyncValidators", "Expected asynchronous validator to return a promise but got '{0}' instead.", promise); } setValidity(name, undefined); validatorPromises.push(promise.then(function() { setValidity(name, true); }, function(error) { allValid = false; setValidity(name, false); })); }); if (!validatorPromises.length) { validationDone(true); } else { $q.all(validatorPromises).then(function() { validationDone(allValid); }, noop); } } function setValidity(name, isValid) { if (localValidationRunId === currentValidationRunId) { ctrl.$setValidity(name, isValid); } } function validationDone(allValid) { if (localValidationRunId === currentValidationRunId) { doneCallback(allValid); } } }; /** * @ngdoc method * @name ngModel.NgModelController#$commitViewValue * * @description * Commit a pending update to the `$modelValue`. * * Updates may be pending by a debounced event or because the input is waiting for a some future * event defined in `ng-model-options`. this method is rarely needed as `NgModelController` * usually handles calling this in response to input events. */ this.$commitViewValue = function() { var viewValue = ctrl.$viewValue; $timeout.cancel(pendingDebounce); // If the view value has not changed then we should just exit, except in the case where there is // a native validator on the element. In this case the validation state may have changed even though // the viewValue has stayed empty. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) { return; } ctrl.$$lastCommittedViewValue = viewValue; // change to dirty if (ctrl.$pristine) { this.$setDirty(); } this.$$parseAndValidate(); }; this.$$parseAndValidate = function() { var viewValue = ctrl.$$lastCommittedViewValue; var modelValue = viewValue; var parserValid = isUndefined(modelValue) ? undefined : true; if (parserValid) { for (var i = 0; i < ctrl.$parsers.length; i++) { modelValue = ctrl.$parsers[i](modelValue); if (isUndefined(modelValue)) { parserValid = false; break; } } } if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) { // ctrl.$modelValue has not been touched yet... ctrl.$modelValue = ngModelGet($scope); } var prevModelValue = ctrl.$modelValue; var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid; ctrl.$$rawModelValue = modelValue; if (allowInvalid) { ctrl.$modelValue = modelValue; writeToModelIfNeeded(); } ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) { if (!allowInvalid) { // Note: Don't check ctrl.$valid here, as we could have // external validators (e.g. calculated on the server), // that just call $setValidity and need the model value // to calculate their validity. ctrl.$modelValue = allValid ? modelValue : undefined; writeToModelIfNeeded(); } }); function writeToModelIfNeeded() { if (ctrl.$modelValue !== prevModelValue) { ctrl.$$writeModelToScope(); } } }; this.$$writeModelToScope = function() { ngModelSet($scope, ctrl.$modelValue); forEach(ctrl.$viewChangeListeners, function(listener) { try { listener(); } catch (e) { $exceptionHandler(e); } }); }; /** * @ngdoc method * @name ngModel.NgModelController#$setViewValue * * @description * Update the view value. * * This method should be called when an input directive want to change the view value; typically, * this is done from within a DOM event handler. * * For example {@link ng.directive:input input} calls it when the value of the input changes and * {@link ng.directive:select select} calls it when an option is selected. * * If the new `value` is an object (rather than a string or a number), we should make a copy of the * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep * watch of objects, it only looks for a change of identity. If you only change the property of * the object then ngModel will not realise that the object has changed and will not invoke the * `$parsers` and `$validators` pipelines. * * For this reason, you should not change properties of the copy once it has been passed to * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly. * * When this method is called, the new `value` will be staged for committing through the `$parsers` * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged * value sent directly for processing, finally to be applied to `$modelValue` and then the * **expression** specified in the `ng-model` attribute. * * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. * * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn` * and the `default` trigger is not listed, all those actions will remain pending until one of the * `updateOn` events is triggered on the DOM element. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions} * directive is used with a custom debounce for this particular event. * * Note that calling this function does not trigger a `$digest`. * * @param {string} value Value from the view. * @param {string} trigger Event that triggered the update. */ this.$setViewValue = function(value, trigger) { ctrl.$viewValue = value; if (!ctrl.$options || ctrl.$options.updateOnDefault) { ctrl.$$debounceViewValueCommit(trigger); } }; this.$$debounceViewValueCommit = function(trigger) { var debounceDelay = 0, options = ctrl.$options, debounce; if (options && isDefined(options.debounce)) { debounce = options.debounce; if (isNumber(debounce)) { debounceDelay = debounce; } else if (isNumber(debounce[trigger])) { debounceDelay = debounce[trigger]; } else if (isNumber(debounce['default'])) { debounceDelay = debounce['default']; } } $timeout.cancel(pendingDebounce); if (debounceDelay) { pendingDebounce = $timeout(function() { ctrl.$commitViewValue(); }, debounceDelay); } else if ($rootScope.$$phase) { ctrl.$commitViewValue(); } else { $scope.$apply(function() { ctrl.$commitViewValue(); }); } }; // model -> value // Note: we cannot use a normal scope.$watch as we want to detect the following: // 1. scope value is 'a' // 2. user enters 'b' // 3. ng-change kicks in and reverts scope value to 'a' // -> scope value did not change since the last digest as // ng-change executes in apply phase // 4. view should be changed back to 'a' $scope.$watch(function ngModelWatch() { var modelValue = ngModelGet($scope); // if scope model value and ngModel value are out of sync // TODO(perf): why not move this to the action fn? if (modelValue !== ctrl.$modelValue) { ctrl.$modelValue = ctrl.$$rawModelValue = modelValue; var formatters = ctrl.$formatters, idx = formatters.length; var viewValue = modelValue; while (idx--) { viewValue = formatters[idx](viewValue); } if (ctrl.$viewValue !== viewValue) { ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue; ctrl.$render(); ctrl.$$runValidators(undefined, modelValue, viewValue, noop); } } return modelValue; }); }]; /** * @ngdoc directive * @name ngModel * * @element input * @priority 1 * * @description * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a * property on the scope using {@link ngModel.NgModelController NgModelController}, * which is created and exposed by this directive. * * `ngModel` is responsible for: * * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` * require. * - Providing validation behavior (i.e. required, number, email, url). * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations. * - Registering the control with its parent {@link ng.directive:form form}. * * Note: `ngModel` will try to bind to the property given by evaluating the expression on the * current scope. If the property doesn't already exist on this scope, it will be created * implicitly and added to the scope. * * For best practices on using `ngModel`, see: * * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes) * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} * - {@link input[text] text} * - {@link input[checkbox] checkbox} * - {@link input[radio] radio} * - {@link input[number] number} * - {@link input[email] email} * - {@link input[url] url} * - {@link input[date] date} * - {@link input[datetime-local] datetime-local} * - {@link input[time] time} * - {@link input[month] month} * - {@link input[week] week} * - {@link ng.directive:select select} * - {@link ng.directive:textarea textarea} * * # CSS classes * The following CSS classes are added and removed on the associated input/select/textarea element * depending on the validity of the model. * * - `ng-valid`: the model is valid * - `ng-invalid`: the model is invalid * - `ng-valid-[key]`: for each valid key added by `$setValidity` * - `ng-invalid-[key]`: for each invalid key added by `$setValidity` * - `ng-pristine`: the control hasn't been interacted with yet * - `ng-dirty`: the control has been interacted with * - `ng-touched`: the control has been blurred * - `ng-untouched`: the control hasn't been blurred * - `ng-pending`: any `$asyncValidators` are unfulfilled * * Keep in mind that ngAnimate can detect each of these classes when added and removed. * * ## Animation Hooks * * Animations within models are triggered when any of the associated CSS classes are added and removed * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`, * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. * The animations that are triggered within ngModel are similar to how they work in ngClass and * animations can be hooked into using CSS transitions, keyframes as well as JS animations. * * The following example shows a simple way to utilize CSS transitions to style an input element * that has been rendered as invalid after it has been validated: * * <pre> * //be sure to include ngAnimate as a module to hook into more * //advanced animations * .my-input { * transition:0.5s linear all; * background: white; * } * .my-input.ng-invalid { * background: red; * color:white; * } * </pre> * * @example * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample"> <file name="index.html"> <script> angular.module('inputExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.val = '1'; }]); </script> <style> .my-input { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; background: transparent; } .my-input.ng-invalid { color:white; background: red; } </style> Update input to see transitions when valid/invalid. Integer is a valid value. <form name="testForm" ng-controller="ExampleController"> <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" /> </form> </file> * </example> * * ## Binding to a getter/setter * * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a * function that returns a representation of the model when called with zero arguments, and sets * the internal state of a model when called with an argument. It's sometimes useful to use this * for models that have an internal representation that's different than what the model exposes * to the view. * * <div class="alert alert-success"> * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more * frequently than other parts of your code. * </div> * * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to * a `<form>`, which will enable this behavior for all `<input>`s within it. See * {@link ng.directive:ngModelOptions `ngModelOptions`} for more. * * The following example shows how to use `ngModel` with a getter/setter: * * @example * <example name="ngModel-getter-setter" module="getterSetterExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ getterSetter: true }" /> </form> <pre>user.name = <span ng-bind="user.name()"></span></pre> </div> </file> <file name="app.js"> angular.module('getterSetterExample', []) .controller('ExampleController', ['$scope', function($scope) { var _name = 'Brian'; $scope.user = { name: function(newName) { if (angular.isDefined(newName)) { _name = newName; } return _name; } }; }]); </file> * </example> */ var ngModelDirective = ['$rootScope', function($rootScope) { return { restrict: 'A', require: ['ngModel', '^?form', '^?ngModelOptions'], controller: NgModelController, // Prelink needs to run before any input directive // so that we can set the NgModelOptions in NgModelController // before anyone else uses it. priority: 1, compile: function ngModelCompile(element) { // Setup initial state of the control element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS); return { pre: function ngModelPreLink(scope, element, attr, ctrls) { var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options); // notify others, especially parent forms formCtrl.$addControl(modelCtrl); attr.$observe('name', function(newValue) { if (modelCtrl.$name !== newValue) { formCtrl.$$renameControl(modelCtrl, newValue); } }); scope.$on('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); }, post: function ngModelPostLink(scope, element, attr, ctrls) { var modelCtrl = ctrls[0]; if (modelCtrl.$options && modelCtrl.$options.updateOn) { element.on(modelCtrl.$options.updateOn, function(ev) { modelCtrl.$$debounceViewValueCommit(ev && ev.type); }); } element.on('blur', function(ev) { if (modelCtrl.$touched) return; if ($rootScope.$$phase) { scope.$evalAsync(modelCtrl.$setTouched); } else { scope.$apply(modelCtrl.$setTouched); } }); } }; } }; }]; /** * @ngdoc directive * @name ngChange * * @description * Evaluate the given expression when the user changes the input. * The expression is evaluated immediately, unlike the JavaScript onchange event * which only triggers at the end of a change (usually, when the user leaves the * form element or presses the return key). * * The `ngChange` expression is only evaluated when a change in the input value causes * a new value to be committed to the model. * * It will not be evaluated: * * if the value returned from the `$parsers` transformation pipeline has not changed * * if the input has continued to be invalid since the model will stay `null` * * if the model is changed programmatically and not by a change to the input value * * * Note, this directive requires `ngModel` to be present. * * @element input * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change * in input value. * * @example * <example name="ngChange-directive" module="changeExample"> * <file name="index.html"> * <script> * angular.module('changeExample', []) * .controller('ExampleController', ['$scope', function($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * }]); * </script> * <div ng-controller="ExampleController"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * <tt>debug = {{confirmed}}</tt><br/> * <tt>counter = {{counter}}</tt><br/> * </div> * </file> * <file name="protractor.js" type="protractor"> * var counter = element(by.binding('counter')); * var debug = element(by.binding('confirmed')); * * it('should evaluate the expression if changing from view', function() { * expect(counter.getText()).toContain('0'); * * element(by.id('ng-change-example1')).click(); * * expect(counter.getText()).toContain('1'); * expect(debug.getText()).toContain('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element(by.id('ng-change-example2')).click(); * expect(counter.getText()).toContain('0'); * expect(debug.getText()).toContain('true'); * }); * </file> * </example> */ var ngChangeDirective = valueFn({ restrict: 'A', require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); var requiredDirective = function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.required = true; // force truthy in case we are on non input element ctrl.$validators.required = function(modelValue, viewValue) { return !attr.required || !ctrl.$isEmpty(viewValue); }; attr.$observe('required', function() { ctrl.$validate(); }); } }; }; var patternDirective = function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var regexp, patternExp = attr.ngPattern || attr.pattern; attr.$observe('pattern', function(regex) { if (isString(regex) && regex.length > 0) { regex = new RegExp('^' + regex + '$'); } if (regex && !regex.test) { throw minErr('ngPattern')('noregexp', 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp, regex, startingTag(elm)); } regexp = regex || undefined; ctrl.$validate(); }); ctrl.$validators.pattern = function(value) { return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value); }; } }; }; var maxlengthDirective = function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var maxlength = -1; attr.$observe('maxlength', function(value) { var intVal = int(value); maxlength = isNaN(intVal) ? -1 : intVal; ctrl.$validate(); }); ctrl.$validators.maxlength = function(modelValue, viewValue) { return (maxlength < 0) || ctrl.$isEmpty(modelValue) || (viewValue.length <= maxlength); }; } }; }; var minlengthDirective = function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; var minlength = 0; attr.$observe('minlength', function(value) { minlength = int(value) || 0; ctrl.$validate(); }); ctrl.$validators.minlength = function(modelValue, viewValue) { return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength; }; } }; }; /** * @ngdoc directive * @name ngList * * @description * Text input that converts between a delimited string and an array of strings. The default * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`. * * The behaviour of the directive is affected by the use of the `ngTrim` attribute. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each * list item is respected. This implies that the user of the directive is responsible for * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a * tab or newline character. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected * when joining the list items back together) and whitespace around each list item is stripped * before it is added to the model. * * ### Example with Validation * * <example name="ngList-directive" module="listExample"> * <file name="app.js"> * angular.module('listExample', []) * .controller('ExampleController', ['$scope', function($scope) { * $scope.names = ['morpheus', 'neo', 'trinity']; * }]); * </file> * <file name="index.html"> * <form name="myForm" ng-controller="ExampleController"> * List: <input name="namesInput" ng-model="names" ng-list required> * <span class="error" ng-show="myForm.namesInput.$error.required"> * Required!</span> * <br> * <tt>names = {{names}}</tt><br/> * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> * </form> * </file> * <file name="protractor.js" type="protractor"> * var listInput = element(by.model('names')); * var names = element(by.exactBinding('names')); * var valid = element(by.binding('myForm.namesInput.$valid')); * var error = element(by.css('span.error')); * * it('should initialize to model', function() { * expect(names.getText()).toContain('["morpheus","neo","trinity"]'); * expect(valid.getText()).toContain('true'); * expect(error.getCssValue('display')).toBe('none'); * }); * * it('should be invalid if empty', function() { * listInput.clear(); * listInput.sendKeys(''); * * expect(names.getText()).toContain(''); * expect(valid.getText()).toContain('false'); * expect(error.getCssValue('display')).not.toBe('none'); * }); * </file> * </example> * * ### Example - splitting on whitespace * <example name="ngList-directive-newlines"> * <file name="index.html"> * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea> * <pre>{{ list | json }}</pre> * </file> * <file name="protractor.js" type="protractor"> * it("should split the text by newlines", function() { * var listInput = element(by.model('list')); * var output = element(by.binding('list | json')); * listInput.sendKeys('abc\ndef\nghi'); * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]'); * }); * </file> * </example> * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. */ var ngListDirective = function() { return { restrict: 'A', priority: 100, require: 'ngModel', link: function(scope, element, attr, ctrl) { // We want to control whitespace trimming so we use this convoluted approach // to access the ngList attribute, which doesn't pre-trim the attribute var ngList = element.attr(attr.$attr.ngList) || ', '; var trimValues = attr.ngTrim !== 'false'; var separator = trimValues ? trim(ngList) : ngList; var parse = function(viewValue) { // If the viewValue is invalid (say required but empty) it will be `undefined` if (isUndefined(viewValue)) return; var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trimValues ? trim(value) : value); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value)) { return value.join(ngList); } return undefined; }); // Override the standard $isEmpty because an empty array means the input is empty. ctrl.$isEmpty = function(value) { return !value || !value.length; }; } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; /** * @ngdoc directive * @name ngValue * * @description * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`}, * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to * the bound value. * * `ngValue` is useful when dynamically generating lists of radio buttons using * {@link ngRepeat `ngRepeat`}, as shown below. * * Likewise, `ngValue` can be used to generate `<option>` elements for * the {@link select `select`} element. In that case however, only strings are supported * for the `value `attribute, so the resulting `ngModel` will always be a string. * Support for `select` models with non-string values is available via `ngOptions`. * * @element input * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute * of the `input` element * * @example <example name="ngValue-directive" module="valueExample"> <file name="index.html"> <script> angular.module('valueExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.names = ['pizza', 'unicorns', 'robots']; $scope.my = { favorite: 'unicorns' }; }]); </script> <form ng-controller="ExampleController"> <h2>Which is your favorite?</h2> <label ng-repeat="name in names" for="{{name}}"> {{name}} <input type="radio" ng-model="my.favorite" ng-value="name" id="{{name}}" name="favorite"> </label> <div>You chose {{my.favorite}}</div> </form> </file> <file name="protractor.js" type="protractor"> var favorite = element(by.binding('my.favorite')); it('should initialize to model', function() { expect(favorite.getText()).toContain('unicorns'); }); it('should bind the values to the inputs', function() { element.all(by.model('my.favorite')).get(0).click(); expect(favorite.getText()).toContain('pizza'); }); </file> </example> */ var ngValueDirective = function() { return { restrict: 'A', priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function ngValueConstantLink(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function ngValueLink(scope, elm, attr) { scope.$watch(attr.ngValue, function valueWatchAction(value) { attr.$set('value', value); }); }; } } }; }; /** * @ngdoc directive * @name ngModelOptions * * @description * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of * events that will trigger a model update and/or a debouncing delay so that the actual update only * takes place when a timer expires; this timer will be reset after another change takes place. * * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might * be different than the value in the actual model. This means that if you update the model you * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in * order to make sure it is synchronized with the model and that any debounced action is canceled. * * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`} * method is by making sure the input is placed inside a form that has a `name` attribute. This is * important because `form` controllers are published to the related scope under the name in their * `name` attribute. * * Any pending changes will take place immediately when an enclosing form is submitted via the * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` * to have access to the updated model. * * `ngModelOptions` has an effect on the element it's declared on and its descendants. * * @param {Object} ngModelOptions options to apply to the current model. Valid keys are: * - `updateOn`: string specifying which event should the input be bound to. You can set several * events using an space delimited list. There is a special event called `default` that * matches the default events belonging of the control. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a * custom value for each event. For example: * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"` * - `allowInvalid`: boolean value which indicates that the model can be set with values that did * not validate correctly instead of the default behavior of setting the model to undefined. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to `ngModel` as getters/setters. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for * `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`, * otherwise the default timezone of the browser will be used. * * @example The following example shows how to override immediate updates. Changes on the inputs within the form will update the model only when the control loses focus (blur event). If `escape` key is pressed while the input field is focused, the value is reset to the value in the current model. <example name="ngModelOptions-directive-blur" module="optionsExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ updateOn: 'blur' }" ng-keyup="cancel($event)" /><br /> Other data: <input type="text" ng-model="user.data" /><br /> </form> <pre>user.name = <span ng-bind="user.name"></span></pre> </div> </file> <file name="app.js"> angular.module('optionsExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.user = { name: 'say', data: '' }; $scope.cancel = function(e) { if (e.keyCode == 27) { $scope.userForm.userName.$rollbackViewValue(); } }; }]); </file> <file name="protractor.js" type="protractor"> var model = element(by.binding('user.name')); var input = element(by.model('user.name')); var other = element(by.model('user.data')); it('should allow custom events', function() { input.sendKeys(' hello'); input.click(); expect(model.getText()).toEqual('say'); other.click(); expect(model.getText()).toEqual('say hello'); }); it('should $rollbackViewValue when model changes', function() { input.sendKeys(' hello'); expect(input.getAttribute('value')).toEqual('say hello'); input.sendKeys(protractor.Key.ESCAPE); expect(input.getAttribute('value')).toEqual('say'); other.click(); expect(model.getText()).toEqual('say'); }); </file> </example> This one shows how to debounce model changes. Model will be updated only 1 sec after last change. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. <example name="ngModelOptions-directive-debounce" module="optionsExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ debounce: 1000 }" /> <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br /> </form> <pre>user.name = <span ng-bind="user.name"></span></pre> </div> </file> <file name="app.js"> angular.module('optionsExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.user = { name: 'say' }; }]); </file> </example> This one shows how to bind to getter/setters: <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample"> <file name="index.html"> <div ng-controller="ExampleController"> <form name="userForm"> Name: <input type="text" name="userName" ng-model="user.name" ng-model-options="{ getterSetter: true }" /> </form> <pre>user.name = <span ng-bind="user.name()"></span></pre> </div> </file> <file name="app.js"> angular.module('getterSetterExample', []) .controller('ExampleController', ['$scope', function($scope) { var _name = 'Brian'; $scope.user = { name: function(newName) { return angular.isDefined(newName) ? (_name = newName) : _name; } }; }]); </file> </example> */ var ngModelOptionsDirective = function() { return { restrict: 'A', controller: ['$scope', '$attrs', function($scope, $attrs) { var that = this; this.$options = $scope.$eval($attrs.ngModelOptions); // Allow adding/overriding bound events if (this.$options.updateOn !== undefined) { this.$options.updateOnDefault = false; // extract "default" pseudo-event from list of events that can trigger a model update this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() { that.$options.updateOnDefault = true; return ' '; })); } else { this.$options.updateOnDefault = true; } }] }; }; // helper methods function addSetValidityMethod(context) { var ctrl = context.ctrl, $element = context.$element, classCache = {}, set = context.set, unset = context.unset, parentForm = context.parentForm, $animate = context.$animate; classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS)); ctrl.$setValidity = setValidity; function setValidity(validationErrorKey, state, options) { if (state === undefined) { createAndSet('$pending', validationErrorKey, options); } else { unsetAndCleanup('$pending', validationErrorKey, options); } if (!isBoolean(state)) { unset(ctrl.$error, validationErrorKey, options); unset(ctrl.$$success, validationErrorKey, options); } else { if (state) { unset(ctrl.$error, validationErrorKey, options); set(ctrl.$$success, validationErrorKey, options); } else { set(ctrl.$error, validationErrorKey, options); unset(ctrl.$$success, validationErrorKey, options); } } if (ctrl.$pending) { cachedToggleClass(PENDING_CLASS, true); ctrl.$valid = ctrl.$invalid = undefined; toggleValidationCss('', null); } else { cachedToggleClass(PENDING_CLASS, false); ctrl.$valid = isObjectEmpty(ctrl.$error); ctrl.$invalid = !ctrl.$valid; toggleValidationCss('', ctrl.$valid); } // re-read the state as the set/unset methods could have // combined state in ctrl.$error[validationError] (used for forms), // where setting/unsetting only increments/decrements the value, // and does not replace it. var combinedState; if (ctrl.$pending && ctrl.$pending[validationErrorKey]) { combinedState = undefined; } else if (ctrl.$error[validationErrorKey]) { combinedState = false; } else if (ctrl.$$success[validationErrorKey]) { combinedState = true; } else { combinedState = null; } toggleValidationCss(validationErrorKey, combinedState); parentForm.$setValidity(validationErrorKey, combinedState, ctrl); } function createAndSet(name, value, options) { if (!ctrl[name]) { ctrl[name] = {}; } set(ctrl[name], value, options); } function unsetAndCleanup(name, value, options) { if (ctrl[name]) { unset(ctrl[name], value, options); } if (isObjectEmpty(ctrl[name])) { ctrl[name] = undefined; } } function cachedToggleClass(className, switchValue) { if (switchValue && !classCache[className]) { $animate.addClass($element, className); classCache[className] = true; } else if (!switchValue && classCache[className]) { $animate.removeClass($element, className); classCache[className] = false; } } function toggleValidationCss(validationErrorKey, isValid) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true); cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false); } } function isObjectEmpty(obj) { if (obj) { for (var prop in obj) { return false; } } return true; } /** * @ngdoc directive * @name ngBind * @restrict AC * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an * element attribute, it makes the bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/expression Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <example module="bindExample"> <file name="index.html"> <script> angular.module('bindExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.name = 'Whirled'; }]); </script> <div ng-controller="ExampleController"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </file> <file name="protractor.js" type="protractor"> it('should check ng-bind', function() { var nameInput = element(by.model('name')); expect(element(by.binding('name')).getText()).toBe('Whirled'); nameInput.clear(); nameInput.sendKeys('world'); expect(element(by.binding('name')).getText()).toBe('world'); }); </file> </example> */ var ngBindDirective = ['$compile', function($compile) { return { restrict: 'AC', compile: function ngBindCompile(templateElement) { $compile.$$addBindingClass(templateElement); return function ngBindLink(scope, element, attr) { $compile.$$addBindingInfo(element, attr.ngBind); element = element[0]; scope.$watch(attr.ngBind, function ngBindWatchAction(value) { element.textContent = value === undefined ? '' : value; }); }; } }; }]; /** * @ngdoc directive * @name ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text content should be replaced with the interpolation of the template * in the `ngBindTemplate` attribute. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` * expressions. This directive is needed since some HTML elements * (such as TITLE and OPTION) cannot contain SPAN elements. * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <example module="bindExample"> <file name="index.html"> <script> angular.module('bindExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; }]); </script> <div ng-controller="ExampleController"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </file> <file name="protractor.js" type="protractor"> it('should check ng-bind', function() { var salutationElem = element(by.binding('salutation')); var salutationInput = element(by.model('salutation')); var nameInput = element(by.model('name')); expect(salutationElem.getText()).toBe('Hello World!'); salutationInput.clear(); salutationInput.sendKeys('Greetings'); nameInput.clear(); nameInput.sendKeys('user'); expect(salutationElem.getText()).toBe('Greetings user!'); }); </file> </example> */ var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) { return { compile: function ngBindTemplateCompile(templateElement) { $compile.$$addBindingClass(templateElement); return function ngBindTemplateLink(scope, element, attr) { var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); $compile.$$addBindingInfo(element, interpolateFn.expressions); element = element[0]; attr.$observe('ngBindTemplate', function(value) { element.textContent = value === undefined ? '' : value; }); }; } }; }]; /** * @ngdoc directive * @name ngBindHtml * * @description * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize} * in your module's dependencies, you need to include "angular-sanitize.js" in your application. * * You may also bypass sanitization for values you know are safe. To do so, bind to * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}. * * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you * will have an exception (instead of an exploit.) * * @element ANY * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. * * @example <example module="bindHtmlExample" deps="angular-sanitize.js"> <file name="index.html"> <div ng-controller="ExampleController"> <p ng-bind-html="myHTML"></p> </div> </file> <file name="script.js"> angular.module('bindHtmlExample', ['ngSanitize']) .controller('ExampleController', ['$scope', function($scope) { $scope.myHTML = 'I am an <code>HTML</code>string with ' + '<a href="#">links!</a> and other <em>stuff</em>'; }]); </file> <file name="protractor.js" type="protractor"> it('should check ng-bind-html', function() { expect(element(by.binding('myHTML')).getText()).toBe( 'I am an HTMLstring with links! and other stuff'); }); </file> </example> */ var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) { return { restrict: 'A', compile: function ngBindHtmlCompile(tElement, tAttrs) { var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml); var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) { return (value || '').toString(); }); $compile.$$addBindingClass(tElement); return function ngBindHtmlLink(scope, element, attr) { $compile.$$addBindingInfo(element, attr.ngBindHtml); scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() { // we re-evaluate the expr because we want a TrustedValueHolderType // for $sce, not a string element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || ''); }); }; } }; }]; function classDirective(name, selector) { name = 'ngClass' + name; return ['$animate', function($animate) { return { restrict: 'AC', link: function(scope, element, attr) { var oldVal; scope.$watch(attr[name], ngClassWatchAction, true); attr.$observe('class', function(value) { ngClassWatchAction(scope.$eval(attr[name])); }); if (name !== 'ngClass') { scope.$watch('$index', function($index, old$index) { // jshint bitwise: false var mod = $index & 1; if (mod !== (old$index & 1)) { var classes = arrayClasses(scope.$eval(attr[name])); mod === selector ? addClasses(classes) : removeClasses(classes); } }); } function addClasses(classes) { var newClasses = digestClassCounts(classes, 1); attr.$addClass(newClasses); } function removeClasses(classes) { var newClasses = digestClassCounts(classes, -1); attr.$removeClass(newClasses); } function digestClassCounts(classes, count) { var classCounts = element.data('$classCounts') || {}; var classesToUpdate = []; forEach(classes, function(className) { if (count > 0 || classCounts[className]) { classCounts[className] = (classCounts[className] || 0) + count; if (classCounts[className] === +(count > 0)) { classesToUpdate.push(className); } } }); element.data('$classCounts', classCounts); return classesToUpdate.join(' '); } function updateClasses(oldClasses, newClasses) { var toAdd = arrayDifference(newClasses, oldClasses); var toRemove = arrayDifference(oldClasses, newClasses); toAdd = digestClassCounts(toAdd, 1); toRemove = digestClassCounts(toRemove, -1); if (toAdd && toAdd.length) { $animate.addClass(element, toAdd); } if (toRemove && toRemove.length) { $animate.removeClass(element, toRemove); } } function ngClassWatchAction(newVal) { if (selector === true || scope.$index % 2 === selector) { var newClasses = arrayClasses(newVal || []); if (!oldVal) { addClasses(newClasses); } else if (!equals(newVal,oldVal)) { var oldClasses = arrayClasses(oldVal); updateClasses(oldClasses, newClasses); } } oldVal = shallowCopy(newVal); } } }; function arrayDifference(tokens1, tokens2) { var values = []; outer: for (var i = 0; i < tokens1.length; i++) { var token = tokens1[i]; for (var j = 0; j < tokens2.length; j++) { if (token == tokens2[j]) continue outer; } values.push(token); } return values; } function arrayClasses(classVal) { if (isArray(classVal)) { return classVal; } else if (isString(classVal)) { return classVal.split(' '); } else if (isObject(classVal)) { var classes = []; forEach(classVal, function(v, k) { if (v) { classes = classes.concat(k.split(' ')); } }); return classes; } return classVal; } }]; } /** * @ngdoc directive * @name ngClass * @restrict AC * * @description * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding * an expression that represents all classes to be added. * * The directive operates in three different ways, depending on which of three types the expression * evaluates to: * * 1. If the expression evaluates to a string, the string should be one or more space-delimited class * names. * * 2. If the expression evaluates to an array, each element of the array should be a string that is * one or more space-delimited class names. * * 3. If the expression evaluates to an object, then for each key-value pair of the * object with a truthy value the corresponding key is used as a class name. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the * new classes are added. * * @animations * add - happens just before the class is applied to the element * remove - happens just before the class is removed from the element * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. In the case of a map, the * names of the properties whose values are truthy will be added as css classes to the * element. * * @example Example that demonstrates basic bindings via ngClass directive. <example> <file name="index.html"> <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p> <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br> <input type="checkbox" ng-model="important"> important (apply "bold" class)<br> <input type="checkbox" ng-model="error"> error (apply "red" class) <hr> <p ng-class="style">Using String Syntax</p> <input type="text" ng-model="style" placeholder="Type: bold strike red"> <hr> <p ng-class="[style1, style2, style3]">Using Array Syntax</p> <input ng-model="style1" placeholder="Type: bold, strike or red"><br> <input ng-model="style2" placeholder="Type: bold, strike or red"><br> <input ng-model="style3" placeholder="Type: bold, strike or red"><br> </file> <file name="style.css"> .strike { text-decoration: line-through; } .bold { font-weight: bold; } .red { color: red; } </file> <file name="protractor.js" type="protractor"> var ps = element.all(by.css('p')); it('should let you toggle the class', function() { expect(ps.first().getAttribute('class')).not.toMatch(/bold/); expect(ps.first().getAttribute('class')).not.toMatch(/red/); element(by.model('important')).click(); expect(ps.first().getAttribute('class')).toMatch(/bold/); element(by.model('error')).click(); expect(ps.first().getAttribute('class')).toMatch(/red/); }); it('should let you toggle string example', function() { expect(ps.get(1).getAttribute('class')).toBe(''); element(by.model('style')).clear(); element(by.model('style')).sendKeys('red'); expect(ps.get(1).getAttribute('class')).toBe('red'); }); it('array example should have 3 classes', function() { expect(ps.last().getAttribute('class')).toBe(''); element(by.model('style1')).sendKeys('bold'); element(by.model('style2')).sendKeys('strike'); element(by.model('style3')).sendKeys('red'); expect(ps.last().getAttribute('class')).toBe('bold strike red'); }); </file> </example> ## Animations The example below demonstrates how to perform animations using ngClass. <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'"> <input id="clearbtn" type="button" value="clear" ng-click="myVar=''"> <br> <span class="base-class" ng-class="myVar">Sample Text</span> </file> <file name="style.css"> .base-class { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } .base-class.my-class { color: red; font-size:3em; } </file> <file name="protractor.js" type="protractor"> it('should check ng-class', function() { expect(element(by.css('.base-class')).getAttribute('class')).not. toMatch(/my-class/); element(by.id('setbtn')).click(); expect(element(by.css('.base-class')).getAttribute('class')). toMatch(/my-class/); element(by.id('clearbtn')).click(); expect(element(by.css('.base-class')).getAttribute('class')).not. toMatch(/my-class/); }); </file> </example> ## ngClass and pre-existing CSS3 Transitions/Animations The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and {@link ng.$animate#removeClass $animate.removeClass}. */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name ngClassOdd * @restrict AC * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except they work in * conjunction with `ngRepeat` and take effect only on odd (even) rows. * * This directive can be applied only within the scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="protractor.js" type="protractor"> it('should check ng-class-odd and ng-class-even', function() { expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); </file> </example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name ngClassEven * @restrict AC * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except they work in * conjunction with `ngRepeat` and take effect only on odd (even) rows. * * This directive can be applied only within the scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="protractor.js" type="protractor"> it('should check ng-class-odd and ng-class-even', function() { expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); </file> </example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name ngCloak * @restrict AC * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but the preferred usage is to apply * multiple `ngCloak` directives to small portions of the page to permit progressive rendering * of the browser view. * * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and * `angular.min.js`. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * * ```css * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { * display: none !important; * } * ``` * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive * during the compilation of the template it deletes the `ngCloak` element attribute, making * the compiled element visible. * * For the best result, the `angular.js` script must be loaded in the head section of the html * document; alternatively, the css rule above must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. * * @element ANY * * @example <example> <file name="index.html"> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </file> <file name="protractor.js" type="protractor"> it('should remove the template directive and css class', function() { expect($('#template1').getAttribute('ng-cloak')). toBeNull(); expect($('#template2').getAttribute('ng-cloak')). toBeNull(); }); </file> </example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name ngController * * @description * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties * are accessed through bindings. * * View — The template (HTML with data bindings) that is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class contains business * logic behind the application to decorate the scope with functions and values * * Note that you can also attach controllers to the DOM by declaring it in a route definition * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller * again using `ng-controller` in the template itself. This will cause the controller to be attached * and executed twice. * * @element ANY * @scope * @priority 500 * @param {expression} ngController Name of a constructor function registered with the current * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression} * that on the current scope evaluates to a constructor function. * * The controller instance can be published into a scope property by specifying * `ng-controller="as propertyName"`. * * If the current `$controllerProvider` is configured to use globals (via * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may * also be the name of a globally accessible constructor function (not recommended). * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Any changes to the data are automatically reflected * in the View without the need for a manual update. * * Two different declaration styles are included below: * * * one binds methods and properties directly onto the controller using `this`: * `ng-controller="SettingsController1 as settings"` * * one injects `$scope` into the controller: * `ng-controller="SettingsController2"` * * The second option is more common in the Angular community, and is generally used in boilerplates * and in this guide. However, there are advantages to binding properties directly to the controller * and avoiding scope. * * * Using `controller as` makes it obvious which controller you are accessing in the template when * multiple controllers apply to an element. * * If you are writing your controllers as classes you have easier access to the properties and * methods, which will appear on the scope, from inside the controller code. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal * inheritance masking primitives. * * This example demonstrates the `controller as` syntax. * * <example name="ngControllerAs" module="controllerAsExample"> * <file name="index.html"> * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings"> * Name: <input type="text" ng-model="settings.name"/> * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/> * Contact: * <ul> * <li ng-repeat="contact in settings.contacts"> * <select ng-model="contact.type"> * <option>phone</option> * <option>email</option> * </select> * <input type="text" ng-model="contact.value"/> * [ <a href="" ng-click="settings.clearContact(contact)">clear</a> * | <a href="" ng-click="settings.removeContact(contact)">X</a> ] * </li> * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li> * </ul> * </div> * </file> * <file name="app.js"> * angular.module('controllerAsExample', []) * .controller('SettingsController1', SettingsController1); * * function SettingsController1() { * this.name = "John Smith"; * this.contacts = [ * {type: 'phone', value: '408 555 1212'}, * {type: 'email', value: 'john.smith@example.org'} ]; * } * * SettingsController1.prototype.greet = function() { * alert(this.name); * }; * * SettingsController1.prototype.addContact = function() { * this.contacts.push({type: 'email', value: 'yourname@example.org'}); * }; * * SettingsController1.prototype.removeContact = function(contactToRemove) { * var index = this.contacts.indexOf(contactToRemove); * this.contacts.splice(index, 1); * }; * * SettingsController1.prototype.clearContact = function(contact) { * contact.type = 'phone'; * contact.value = ''; * }; * </file> * <file name="protractor.js" type="protractor"> * it('should check controller as', function() { * var container = element(by.id('ctrl-as-exmpl')); * expect(container.element(by.model('settings.name')) * .getAttribute('value')).toBe('John Smith'); * * var firstRepeat = * container.element(by.repeater('contact in settings.contacts').row(0)); * var secondRepeat = * container.element(by.repeater('contact in settings.contacts').row(1)); * * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe('408 555 1212'); * * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe('john.smith@example.org'); * * firstRepeat.element(by.linkText('clear')).click(); * * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe(''); * * container.element(by.linkText('add')).click(); * * expect(container.element(by.repeater('contact in settings.contacts').row(2)) * .element(by.model('contact.value')) * .getAttribute('value')) * .toBe('yourname@example.org'); * }); * </file> * </example> * * This example demonstrates the "attach to `$scope`" style of controller. * * <example name="ngController" module="controllerExample"> * <file name="index.html"> * <div id="ctrl-exmpl" ng-controller="SettingsController2"> * Name: <input type="text" ng-model="name"/> * [ <a href="" ng-click="greet()">greet</a> ]<br/> * Contact: * <ul> * <li ng-repeat="contact in contacts"> * <select ng-model="contact.type"> * <option>phone</option> * <option>email</option> * </select> * <input type="text" ng-model="contact.value"/> * [ <a href="" ng-click="clearContact(contact)">clear</a> * | <a href="" ng-click="removeContact(contact)">X</a> ] * </li> * <li>[ <a href="" ng-click="addContact()">add</a> ]</li> * </ul> * </div> * </file> * <file name="app.js"> * angular.module('controllerExample', []) * .controller('SettingsController2', ['$scope', SettingsController2]); * * function SettingsController2($scope) { * $scope.name = "John Smith"; * $scope.contacts = [ * {type:'phone', value:'408 555 1212'}, * {type:'email', value:'john.smith@example.org'} ]; * * $scope.greet = function() { * alert($scope.name); * }; * * $scope.addContact = function() { * $scope.contacts.push({type:'email', value:'yourname@example.org'}); * }; * * $scope.removeContact = function(contactToRemove) { * var index = $scope.contacts.indexOf(contactToRemove); * $scope.contacts.splice(index, 1); * }; * * $scope.clearContact = function(contact) { * contact.type = 'phone'; * contact.value = ''; * }; * } * </file> * <file name="protractor.js" type="protractor"> * it('should check controller', function() { * var container = element(by.id('ctrl-exmpl')); * * expect(container.element(by.model('name')) * .getAttribute('value')).toBe('John Smith'); * * var firstRepeat = * container.element(by.repeater('contact in contacts').row(0)); * var secondRepeat = * container.element(by.repeater('contact in contacts').row(1)); * * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe('408 555 1212'); * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe('john.smith@example.org'); * * firstRepeat.element(by.linkText('clear')).click(); * * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) * .toBe(''); * * container.element(by.linkText('add')).click(); * * expect(container.element(by.repeater('contact in contacts').row(2)) * .element(by.model('contact.value')) * .getAttribute('value')) * .toBe('yourname@example.org'); * }); * </file> *</example> */ var ngControllerDirective = [function() { return { restrict: 'A', scope: true, controller: '@', priority: 500 }; }]; /** * @ngdoc directive * @name ngCsp * * @element html * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. * * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps. * * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). * For Angular to be CSP compatible there are only two things that we need to do differently: * * - don't use `Function` constructor to generate optimized value getters * - don't inject custom stylesheet into the document * * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will * be raised. * * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). * To make those directives work in CSP mode, include the `angular-csp.css` manually. * * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This * autodetection however triggers a CSP error to be logged in the console: * * ``` * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of * script in the following Content Security Policy directive: "default-src 'self'". Note that * 'script-src' was not explicitly set, so 'default-src' is used as a fallback. * ``` * * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp` * directive on the root element of the application or on the `angular.js` script tag, whichever * appears first in the html document. * * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* * * @example * This example shows how to apply the `ngCsp` directive to the `html` tag. ```html <!doctype html> <html ng-app ng-csp> ... ... </html> ``` * @example // Note: the suffix `.csp` in the example name triggers // csp mode in our http server! <example name="example.csp" module="cspExample" ng-csp="true"> <file name="index.html"> <div ng-controller="MainController as ctrl"> <div> <button ng-click="ctrl.inc()" id="inc">Increment</button> <span id="counter"> {{ctrl.counter}} </span> </div> <div> <button ng-click="ctrl.evil()" id="evil">Evil</button> <span id="evilError"> {{ctrl.evilError}} </span> </div> </div> </file> <file name="script.js"> angular.module('cspExample', []) .controller('MainController', function() { this.counter = 0; this.inc = function() { this.counter++; }; this.evil = function() { // jshint evil:true try { eval('1+2'); } catch (e) { this.evilError = e.message; } }; }); </file> <file name="protractor.js" type="protractor"> var util, webdriver; var incBtn = element(by.id('inc')); var counter = element(by.id('counter')); var evilBtn = element(by.id('evil')); var evilError = element(by.id('evilError')); function getAndClearSevereErrors() { return browser.manage().logs().get('browser').then(function(browserLog) { return browserLog.filter(function(logEntry) { return logEntry.level.value > webdriver.logging.Level.WARNING.value; }); }); } function clearErrors() { getAndClearSevereErrors(); } function expectNoErrors() { getAndClearSevereErrors().then(function(filteredLog) { expect(filteredLog.length).toEqual(0); if (filteredLog.length) { console.log('browser console errors: ' + util.inspect(filteredLog)); } }); } function expectError(regex) { getAndClearSevereErrors().then(function(filteredLog) { var found = false; filteredLog.forEach(function(log) { if (log.message.match(regex)) { found = true; } }); if (!found) { throw new Error('expected an error that matches ' + regex); } }); } beforeEach(function() { util = require('util'); webdriver = require('protractor/node_modules/selenium-webdriver'); }); // For now, we only test on Chrome, // as Safari does not load the page with Protractor's injected scripts, // and Firefox webdriver always disables content security policy (#6358) if (browser.params.browser !== 'chrome') { return; } it('should not report errors when the page is loaded', function() { // clear errors so we are not dependent on previous tests clearErrors(); // Need to reload the page as the page is already loaded when // we come here browser.driver.getCurrentUrl().then(function(url) { browser.get(url); }); expectNoErrors(); }); it('should evaluate expressions', function() { expect(counter.getText()).toEqual('0'); incBtn.click(); expect(counter.getText()).toEqual('1'); expectNoErrors(); }); it('should throw and report an error when using "eval"', function() { evilBtn.click(); expect(evilError.getText()).toMatch(/Content Security Policy/); expectError(/Content Security Policy/); }); </file> </example> */ // ngCsp is not implemented as a proper directive any more, because we need it be processed while we // bootstrap the system (before $parse is instantiated), for this reason we just have // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc /** * @ngdoc directive * @name ngClick * * @description * The ngClick directive allows you to specify custom behavior when * an element is clicked. * * @element ANY * @priority 0 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon * click. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> <span> count: {{count}} </span> </file> <file name="protractor.js" type="protractor"> it('should check ng-click', function() { expect(element(by.binding('count')).getText()).toMatch('0'); element(by.css('button')).click(); expect(element(by.binding('count')).getText()).toMatch('1'); }); </file> </example> */ /* * A collection of directives that allows creation of custom event handlers that are defined as * angular expressions and are compiled and executed within the current scope. */ var ngEventDirectives = {}; // For events that might fire synchronously during DOM manipulation // we need to execute their event handlers asynchronously using $evalAsync, // so that they are not executed in an inconsistent state. var forceAsyncEvents = { 'blur': true, 'focus': true }; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), function(eventName) { var directiveName = directiveNormalize('ng-' + eventName); ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) { return { restrict: 'A', compile: function($element, attr) { // We expose the powerful $event object on the scope that provides access to the Window, // etc. that isn't protected by the fast paths in $parse. We explicitly request better // checks at the cost of speed since event handler expressions are not executed as // frequently as regular change detection. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true); return function ngEventHandler(scope, element) { element.on(eventName, function(event) { var callback = function() { fn(scope, {$event:event}); }; if (forceAsyncEvents[eventName] && $rootScope.$$phase) { scope.$evalAsync(callback); } else { scope.$apply(callback); } }); }; } }; }]; } ); /** * @ngdoc directive * @name ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. * * @element ANY * @priority 0 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon * a dblclick. (The Event object is available as `$event`) * * @example <example> <file name="index.html"> <button ng-dblclick="count = count + 1" ng-init="count=0"> Increment (on double click) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @priority 0 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mousedown="count = count + 1" ng-init="count=0"> Increment (on mouse down) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @priority 0 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseup="count = count + 1" ng-init="count=0"> Increment (on mouse up) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @priority 0 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseover="count = count + 1" ng-init="count=0"> Increment (when mouse is over) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @priority 0 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseenter="count = count + 1" ng-init="count=0"> Increment (when mouse enters) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @priority 0 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mouseleave="count = count + 1" ng-init="count=0"> Increment (when mouse leaves) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @priority 0 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <button ng-mousemove="count = count + 1" ng-init="count=0"> Increment (when mouse moves) </button> count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngKeydown * * @description * Specify custom behavior on keydown event. * * @element ANY * @priority 0 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example <example> <file name="index.html"> <input ng-keydown="count = count + 1" ng-init="count=0"> key down count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngKeyup * * @description * Specify custom behavior on keyup event. * * @element ANY * @priority 0 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example <example> <file name="index.html"> <p>Typing in the input box below updates the key count</p> <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}} <p>Typing in the input box below updates the keycode</p> <input ng-keyup="event=$event"> <p>event keyCode: {{ event.keyCode }}</p> <p>event altKey: {{ event.altKey }}</p> </file> </example> */ /** * @ngdoc directive * @name ngKeypress * * @description * Specify custom behavior on keypress event. * * @element ANY * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon * keypress. ({@link guide/expression#-event- Event object is available as `$event`} * and can be interrogated for keyCode, altKey, etc.) * * @example <example> <file name="index.html"> <input ng-keypress="count = count + 1" ng-init="count=0"> key press count: {{count}} </file> </example> */ /** * @ngdoc directive * @name ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page), but only if the form does not contain `action`, * `data-action`, or `x-action` attributes. * * <div class="alert alert-warning"> * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and * `ngSubmit` handlers together. See the * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} * for a detailed discussion of when `ngSubmit` may be triggered. * </div> * * @element form * @priority 0 * @param {expression} ngSubmit {@link guide/expression Expression} to eval. * ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example module="submitExample"> <file name="index.html"> <script> angular.module('submitExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if ($scope.text) { $scope.list.push(this.text); $scope.text = ''; } }; }]); </script> <form ng-submit="submit()" ng-controller="ExampleController"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </file> <file name="protractor.js" type="protractor"> it('should check ng-submit', function() { expect(element(by.binding('list')).getText()).toBe('list=[]'); element(by.css('#submit')).click(); expect(element(by.binding('list')).getText()).toContain('hello'); expect(element(by.model('text')).getAttribute('value')).toBe(''); }); it('should ignore empty strings', function() { expect(element(by.binding('list')).getText()).toBe('list=[]'); element(by.css('#submit')).click(); element(by.css('#submit')).click(); expect(element(by.binding('list')).getText()).toContain('hello'); }); </file> </example> */ /** * @ngdoc directive * @name ngFocus * * @description * Specify custom behavior on focus event. * * Note: As the `focus` event is executed synchronously when calling `input.focus()` * AngularJS executes the expression using `scope.$evalAsync` if the event is fired * during an `$apply` to ensure a consistent state. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon * focus. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ngBlur * * @description * Specify custom behavior on blur event. * * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when * an element has lost focus. * * Note: As the `blur` event is executed synchronously also during DOM manipulations * (e.g. removing a focussed input), * AngularJS executes the expression using `scope.$evalAsync` if the event is fired * during an `$apply` to ensure a consistent state. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon * blur. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ngCopy * * @description * Specify custom behavior on copy event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon * copy. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value"> copied: {{copied}} </file> </example> */ /** * @ngdoc directive * @name ngCut * * @description * Specify custom behavior on cut event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon * cut. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value"> cut: {{cut}} </file> </example> */ /** * @ngdoc directive * @name ngPaste * * @description * Specify custom behavior on paste event. * * @element window, input, select, textarea, a * @priority 0 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon * paste. ({@link guide/expression#-event- Event object is available as `$event`}) * * @example <example> <file name="index.html"> <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'> pasted: {{paste}} </file> </example> */ /** * @ngdoc directive * @name ngIf * @restrict A * * @description * The `ngIf` directive removes or recreates a portion of the DOM tree based on an * {expression}. If the expression assigned to `ngIf` evaluates to a false * value then the element is removed from the DOM, otherwise a clone of the * element is reinserted into the DOM. * * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the * element in the DOM rather than changing its visibility via the `display` css property. A common * case when this difference is significant is when using css selectors that rely on an element's * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. * * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope * is created when the element is restored. The scope created within `ngIf` inherits from * its parent scope using * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance). * An important implication of this is if `ngModel` is used within `ngIf` to bind to * a javascript primitive defined in the parent scope. In this case any modifications made to the * variable within the child scope will override (hide) the value in the parent scope. * * Also, `ngIf` recreates elements using their compiled state. An example of this behavior * is if an element's class attribute is directly modified after it's compiled, using something like * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element * the added class will be lost because the original compiled state is used to regenerate the element. * * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` * and `leave` effects. * * @animations * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container * leave - happens just before the `ngIf` contents are removed from the DOM * * @element ANY * @scope * @priority 600 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then * the element is removed from the DOM tree. If it is truthy a copy of the compiled * element is added to the DOM tree. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/> Show when checked: <span ng-if="checked" class="animate-if"> This is removed when the checkbox is unchecked. </span> </file> <file name="animations.css"> .animate-if { background:white; border:1px solid black; padding:10px; } .animate-if.ng-enter, .animate-if.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } .animate-if.ng-enter, .animate-if.ng-leave.ng-leave-active { opacity:0; } .animate-if.ng-leave, .animate-if.ng-enter.ng-enter-active { opacity:1; } </file> </example> */ var ngIfDirective = ['$animate', function($animate) { return { multiElement: true, transclude: 'element', priority: 600, terminal: true, restrict: 'A', $$tlb: true, link: function($scope, $element, $attr, ctrl, $transclude) { var block, childScope, previousElements; $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { if (value) { if (!childScope) { $transclude(function(clone, newScope) { childScope = newScope; clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); // Note: We only need the first/last node of the cloned nodes. // However, we need to keep the reference to the jqlite wrapper as it might be changed later // by a directive with templateUrl when its template arrives. block = { clone: clone }; $animate.enter(clone, $element.parent(), $element); }); } } else { if (previousElements) { previousElements.remove(); previousElements = null; } if (childScope) { childScope.$destroy(); childScope = null; } if (block) { previousElements = getBlockNodes(block.clone); $animate.leave(previousElements).then(function() { previousElements = null; }); block = null; } } }); } }; }]; /** * @ngdoc directive * @name ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * By default, the template URL is restricted to the same domain and protocol as the * application document. This is done by calling {@link $sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link * ng.$sce Strict Contextual Escaping}. * * In addition, the browser's * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) * policy may further restrict whether the template is successfully loaded. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` * access on some browsers. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <example module="includeExample" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-controller="ExampleController"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> <hr/> <div class="slide-animate-container"> <div class="slide-animate" ng-include="template.url"></div> </div> </div> </file> <file name="script.js"> angular.module('includeExample', ['ngAnimate']) .controller('ExampleController', ['$scope', function($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'}, { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; }]); </file> <file name="template1.html"> Content of template1.html </file> <file name="template2.html"> Content of template2.html </file> <file name="animations.css"> .slide-animate-container { position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .slide-animate { padding:10px; } .slide-animate.ng-enter, .slide-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; display:block; padding:10px; } .slide-animate.ng-enter { top:-50px; } .slide-animate.ng-enter.ng-enter-active { top:0; } .slide-animate.ng-leave { top:0; } .slide-animate.ng-leave.ng-leave-active { top:50px; } </file> <file name="protractor.js" type="protractor"> var templateSelect = element(by.model('template')); var includeElem = element(by.css('[ng-include]')); it('should load template1.html', function() { expect(includeElem.getText()).toMatch(/Content of template1.html/); }); it('should load template2.html', function() { if (browser.params.browser == 'firefox') { // Firefox can't handle using selects // See https://github.com/angular/protractor/issues/480 return; } templateSelect.click(); templateSelect.all(by.css('option')).get(2).click(); expect(includeElem.getText()).toMatch(/Content of template2.html/); }); it('should change to blank', function() { if (browser.params.browser == 'firefox') { // Firefox can't handle using selects return; } templateSelect.click(); templateSelect.all(by.css('option')).get(0).click(); expect(includeElem.isPresent()).toBe(false); }); </file> </example> */ /** * @ngdoc event * @name ngInclude#$includeContentRequested * @eventType emit on the scope ngInclude was declared in * @description * Emitted every time the ngInclude content is requested. * * @param {Object} angularEvent Synthetic event object. * @param {String} src URL of content to load. */ /** * @ngdoc event * @name ngInclude#$includeContentLoaded * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. * * @param {Object} angularEvent Synthetic event object. * @param {String} src URL of content to load. */ /** * @ngdoc event * @name ngInclude#$includeContentError * @eventType emit on the scope ngInclude was declared in * @description * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299) * * @param {Object} angularEvent Synthetic event object. * @param {String} src URL of content to load. */ var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce', function($templateRequest, $anchorScroll, $animate, $sce) { return { restrict: 'ECA', priority: 400, terminal: true, transclude: 'element', controller: angular.noop, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, $element, $attr, ctrl, $transclude) { var changeCounter = 0, currentScope, previousElement, currentElement; var cleanupLastIncludeContent = function() { if (previousElement) { previousElement.remove(); previousElement = null; } if (currentScope) { currentScope.$destroy(); currentScope = null; } if (currentElement) { $animate.leave(currentElement).then(function() { previousElement = null; }); previousElement = currentElement; currentElement = null; } }; scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { var afterAnimation = function() { if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }; var thisChangeId = ++changeCounter; if (src) { //set the 2nd param to true to ignore the template request error so that the inner //contents and scope can be cleaned up. $templateRequest(src, true).then(function(response) { if (thisChangeId !== changeCounter) return; var newScope = scope.$new(); ctrl.template = response; // Note: This will also link all children of ng-include that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-include on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { cleanupLastIncludeContent(); $animate.enter(clone, null, $element).then(afterAnimation); }); currentScope = newScope; currentElement = clone; currentScope.$emit('$includeContentLoaded', src); scope.$eval(onloadExp); }, function() { if (thisChangeId === changeCounter) { cleanupLastIncludeContent(); scope.$emit('$includeContentError', src); } }); scope.$emit('$includeContentRequested', src); } else { cleanupLastIncludeContent(); ctrl.template = null; } }); }; } }; }]; // This directive is called during the $transclude call of the first `ngInclude` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngInclude // is called. var ngIncludeFillContentDirective = ['$compile', function($compile) { return { restrict: 'ECA', priority: -400, require: 'ngInclude', link: function(scope, $element, $attr, ctrl) { if (/SVG/.test($element[0].toString())) { // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not // support innerHTML, so detect this here and try to generate the contents // specially. $element.empty(); $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope, function namespaceAdaptedClone(clone) { $element.append(clone); }, {futureParentElement: $element}); return; } $element.html(ctrl.template); $compile($element.contents())(scope); } }; }]; /** * @ngdoc directive * @name ngInit * @restrict AC * * @description * The `ngInit` directive allows you to evaluate an expression in the * current scope. * * <div class="alert alert-error"> * The only appropriate use of `ngInit` is for aliasing special properties of * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you * should use {@link guide/controller controllers} rather than `ngInit` * to initialize values on a scope. * </div> * <div class="alert alert-warning"> * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make * sure you have parenthesis for correct precedence: * <pre class="prettyprint"> * <div ng-init="test1 = (data | orderBy:'name')"></div> * </pre> * </div> * * @priority 450 * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example <example module="initExample"> <file name="index.html"> <script> angular.module('initExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.list = [['a', 'b'], ['c', 'd']]; }]); </script> <div ng-controller="ExampleController"> <div ng-repeat="innerList in list" ng-init="outerIndex = $index"> <div ng-repeat="value in innerList" ng-init="innerIndex = $index"> <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span> </div> </div> </div> </file> <file name="protractor.js" type="protractor"> it('should alias index positions', function() { var elements = element.all(by.css('.example-init')); expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); }); </file> </example> */ var ngInitDirective = ngDirective({ priority: 450, compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } }; } }); /** * @ngdoc directive * @name ngNonBindable * @restrict AC * @priority 1000 * * @description * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current * DOM element. This is useful if the element contains what appears to be Angular directives and * bindings but which should be ignored by Angular. This could be the case if you have a site that * displays snippets of code, for instance. * * @element ANY * * @example * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, * but the one wrapped in `ngNonBindable` is left alone. * * @example <example> <file name="index.html"> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </file> <file name="protractor.js" type="protractor"> it('should check ng-non-bindable', function() { expect(element(by.binding('1 + 2')).getText()).toContain('3'); expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); }); </file> </example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name ngPluralize * @restrict EA * * @description * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js, but can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) * and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) * in Angular's default en-US locale: "one" and "other". * * While a plural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. There are examples of plural categories * and explicit number rules throughout the rest of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/expression * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object. * * The following example shows how to configure ngPluralize: * * ```html * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *``` * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * ```html * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * ``` * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bound to. * @param {string} when The mapping between plural category to its corresponding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <example module="pluralizeExample"> <file name="index.html"> <script> angular.module('pluralizeExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; }]); </script> <div ng-controller="ExampleController"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </file> <file name="protractor.js" type="protractor"> it('should show correct pluralized string', function() { var withoutOffset = element.all(by.css('ng-pluralize')).get(0); var withOffset = element.all(by.css('ng-pluralize')).get(1); var countInput = element(by.model('personCount')); expect(withoutOffset.getText()).toEqual('1 person is viewing.'); expect(withOffset.getText()).toEqual('Igor is viewing.'); countInput.clear(); countInput.sendKeys('0'); expect(withoutOffset.getText()).toEqual('Nobody is viewing.'); expect(withOffset.getText()).toEqual('Nobody is viewing.'); countInput.clear(); countInput.sendKeys('2'); expect(withoutOffset.getText()).toEqual('2 people are viewing.'); expect(withOffset.getText()).toEqual('Igor and Misko are viewing.'); countInput.clear(); countInput.sendKeys('3'); expect(withoutOffset.getText()).toEqual('3 people are viewing.'); expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.'); countInput.clear(); countInput.sendKeys('4'); expect(withoutOffset.getText()).toEqual('4 people are viewing.'); expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.'); }); it('should show data-bound names', function() { var withOffset = element.all(by.css('ng-pluralize')).get(1); var personCount = element(by.model('personCount')); var person1 = element(by.model('person1')); var person2 = element(by.model('person2')); personCount.clear(); personCount.sendKeys('4'); person1.clear(); person1.sendKeys('Di'); person2.clear(); person2.sendKeys('Vojta'); expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.'); }); </file> </example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g, IS_WHEN = /^when(Minus)?(.+)$/; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp) || {}, whensExpFns = {}, startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol, watchRemover = angular.noop, lastCount; forEach(attr, function(expression, attributeName) { var tmpMatch = IS_WHEN.exec(attributeName); if (tmpMatch) { var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]); whens[whenKey] = element.attr(attr.$attr[attributeName]); } }); forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement)); }); scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) { var count = parseFloat(newVal); var countIsNaN = isNaN(count); if (!countIsNaN && !(count in whens)) { // If an explicit number rule such as 1, 2, 3... is defined, just use it. // Otherwise, check it against pluralization rules in $locale service. count = $locale.pluralCat(count - offset); } // If both `count` and `lastCount` are NaN, we don't need to re-register a watch. // In JS `NaN !== NaN`, so we have to exlicitly check. if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) { watchRemover(); watchRemover = scope.$watch(whensExpFns[count], updateElementText); lastCount = count; } }); function updateElementText(newText) { element.text(newText || ''); } } }; }]; /** * @ngdoc directive * @name ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * | Variable | Type | Details | * |-----------|-----------------|-----------------------------------------------------------------------------| * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | * * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. * This may be useful when, for instance, nesting ngRepeats. * * # Special repeat start and end points * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) * up to and including the ending HTML tag where **ng-repeat-end** is placed. * * The example below makes use of this feature: * ```html * <header ng-repeat-start="item in items"> * Header {{ item }} * </header> * <div class="body"> * Body {{ item }} * </div> * <footer ng-repeat-end> * Footer {{ item }} * </footer> * ``` * * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: * ```html * <header> * Header A * </header> * <div class="body"> * Body A * </div> * <footer> * Footer A * </footer> * <header> * Header B * </header> * <div class="body"> * Body B * </div> * <footer> * Footer B * </footer> * ``` * * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). * * @animations * **.enter** - when a new item is added to the list or when an item is revealed after a filter * * **.leave** - when an item is removed from the list or when an item is filtered out * * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `album in artist.albums`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function * which can be used to associate the objects in the collection with the DOM elements. If no tracking function * is specified the ng-repeat associates elements by identity in the collection. It is an error to have * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, * before specifying a tracking expression. * * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements * will be associated by item identity in the array. * * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements * with the corresponding item in the array by identity. Moving the same object in array would move the DOM * element in the same way in the DOM. * * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this * case the object identity does not matter. Two objects are considered equivalent as long as their `id` * property is same. * * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter * to items in conjunction with a tracking expression. * * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message * when a filter is active on the repeater, but the filtered result set is empty. * * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after * the items have been processed through the filter. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-init="friends = [ {name:'John', age:25, gender:'boy'}, {name:'Jessie', age:30, gender:'girl'}, {name:'Johanna', age:28, gender:'girl'}, {name:'Joy', age:15, gender:'girl'}, {name:'Mary', age:28, gender:'girl'}, {name:'Peter', age:95, gender:'boy'}, {name:'Sebastian', age:50, gender:'boy'}, {name:'Erika', age:27, gender:'girl'}, {name:'Patrick', age:40, gender:'boy'}, {name:'Samantha', age:60, gender:'girl'} ]"> I have {{friends.length}} friends. They are: <input type="search" ng-model="q" placeholder="filter friends..." /> <ul class="example-animate-container"> <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> <li class="animate-repeat" ng-if="results.length == 0"> <strong>No results found...</strong> </li> </ul> </div> </file> <file name="animations.css"> .example-animate-container { background:white; border:1px solid black; list-style:none; margin:0; padding:0 10px; } .animate-repeat { line-height:40px; list-style:none; box-sizing:border-box; } .animate-repeat.ng-move, .animate-repeat.ng-enter, .animate-repeat.ng-leave { -webkit-transition:all linear 0.5s; transition:all linear 0.5s; } .animate-repeat.ng-leave.ng-leave-active, .animate-repeat.ng-move, .animate-repeat.ng-enter { opacity:0; max-height:0; } .animate-repeat.ng-leave, .animate-repeat.ng-move.ng-move-active, .animate-repeat.ng-enter.ng-enter-active { opacity:1; max-height:40px; } </file> <file name="protractor.js" type="protractor"> var friends = element.all(by.repeater('friend in friends')); it('should render initial data set', function() { expect(friends.count()).toBe(10); expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.'); expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.'); expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.'); expect(element(by.binding('friends.length')).getText()) .toMatch("I have 10 friends. They are:"); }); it('should update repeater when filter predicate changes', function() { expect(friends.count()).toBe(10); element(by.model('q')).sendKeys('ma'); expect(friends.count()).toBe(2); expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.'); expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.'); }); </file> </example> */ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { var NG_REMOVED = '$$NG_REMOVED'; var ngRepeatMinErr = minErr('ngRepeat'); var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) { // TODO(perf): generate setters to shave off ~40ms or 1-1.5% scope[valueIdentifier] = value; if (keyIdentifier) scope[keyIdentifier] = key; scope.$index = index; scope.$first = (index === 0); scope.$last = (index === (arrayLength - 1)); scope.$middle = !(scope.$first || scope.$last); // jshint bitwise: false scope.$odd = !(scope.$even = (index&1) === 0); // jshint bitwise: true }; var getBlockStart = function(block) { return block.clone[0]; }; var getBlockEnd = function(block) { return block.clone[block.clone.length - 1]; }; return { restrict: 'A', multiElement: true, transclude: 'element', priority: 1000, terminal: true, $$tlb: true, compile: function ngRepeatCompile($element, $attr) { var expression = $attr.ngRepeat; var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' '); var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); if (!match) { throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", expression); } var lhs = match[1]; var rhs = match[2]; var aliasAs = match[3]; var trackByExp = match[4]; match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); if (!match) { throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", lhs); } var valueIdentifier = match[3] || match[1]; var keyIdentifier = match[2]; if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) || /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent)$/.test(aliasAs))) { throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.", aliasAs); } var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn; var hashFnLocals = {$id: hashKey}; if (trackByExp) { trackByExpGetter = $parse(trackByExp); } else { trackByIdArrayFn = function(key, value) { return hashKey(value); }; trackByIdObjFn = function(key) { return key; }; } return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) { if (trackByExpGetter) { trackByIdExpFn = function(key, value, index) { // assign key, value, and $index to the locals so that they can be used in hash functions if (keyIdentifier) hashFnLocals[keyIdentifier] = key; hashFnLocals[valueIdentifier] = value; hashFnLocals.$index = index; return trackByExpGetter($scope, hashFnLocals); }; } // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is objects with following properties. // - scope: bound scope // - element: previous element. // - index: position // // We are using no-proto object so that we don't need to guard against inherited props via // hasOwnProperty. var lastBlockMap = createMap(); //watch props $scope.$watchCollection(rhs, function ngRepeatAction(collection) { var index, length, previousNode = $element[0], // node that cloned nodes should be inserted after // initialized to the comment node anchor nextNode, // Same as lastBlockMap but it has the current state. It will become the // lastBlockMap on the next iteration. nextBlockMap = createMap(), collectionLength, key, value, // key/value of iteration trackById, trackByIdFn, collectionKeys, block, // last object information {scope, element, id} nextBlockOrder, elementsToRemove; if (aliasAs) { $scope[aliasAs] = collection; } if (isArrayLike(collection)) { collectionKeys = collection; trackByIdFn = trackByIdExpFn || trackByIdArrayFn; } else { trackByIdFn = trackByIdExpFn || trackByIdObjFn; // if object, extract keys, sort them and use to determine order of iteration over obj props collectionKeys = []; for (var itemKey in collection) { if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') { collectionKeys.push(itemKey); } } collectionKeys.sort(); } collectionLength = collectionKeys.length; nextBlockOrder = new Array(collectionLength); // locate existing items for (index = 0; index < collectionLength; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; trackById = trackByIdFn(key, value, index); if (lastBlockMap[trackById]) { // found previously seen block block = lastBlockMap[trackById]; delete lastBlockMap[trackById]; nextBlockMap[trackById] = block; nextBlockOrder[index] = block; } else if (nextBlockMap[trackById]) { // if collision detected. restore lastBlockMap and throw an error forEach(nextBlockOrder, function(block) { if (block && block.scope) lastBlockMap[block.id] = block; }); throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}", expression, trackById, value); } else { // new never before seen block nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined}; nextBlockMap[trackById] = true; } } // remove leftover items for (var blockKey in lastBlockMap) { block = lastBlockMap[blockKey]; elementsToRemove = getBlockNodes(block.clone); $animate.leave(elementsToRemove); if (elementsToRemove[0].parentNode) { // if the element was not removed yet because of pending animation, mark it as deleted // so that we can ignore it later for (index = 0, length = elementsToRemove.length; index < length; index++) { elementsToRemove[index][NG_REMOVED] = true; } } block.scope.$destroy(); } // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0; index < collectionLength; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; block = nextBlockOrder[index]; if (block.scope) { // if we have already seen this object, then we need to reuse the // associated scope/element nextNode = previousNode; // skip nodes that are already pending removal via leave animation do { nextNode = nextNode.nextSibling; } while (nextNode && nextNode[NG_REMOVED]); if (getBlockStart(block) != nextNode) { // existing item which got moved $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode)); } previousNode = getBlockEnd(block); updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); } else { // new item which we don't know about $transclude(function ngRepeatTransclude(clone, scope) { block.scope = scope; // http://jsperf.com/clone-vs-createcomment var endNode = ngRepeatEndComment.cloneNode(false); clone[clone.length++] = endNode; // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper? $animate.enter(clone, null, jqLite(previousNode)); previousNode = endNode; // Note: We only need the first/last node of the cloned nodes. // However, we need to keep the reference to the jqlite wrapper as it might be changed later // by a directive with templateUrl when its template arrives. block.clone = clone; nextBlockMap[block.id] = block; updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); }); } } lastBlockMap = nextBlockMap; }); }; } }; }]; var NG_HIDE_CLASS = 'ng-hide'; var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; /** * @ngdoc directive * @name ngShow * * @description * The `ngShow` directive shows or hides the given HTML element based on the expression * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined * in AngularJS and sets the display style to none (using an !important flag). * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * * ```html * <!-- when $scope.myValue is truthy (element is visible) --> * <div ng-show="myValue"></div> * * <!-- when $scope.myValue is falsy (element is hidden) --> * <div ng-show="myValue" class="ng-hide"></div> * ``` * * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed * from the element causing the element not to appear hidden. * * ## Why is !important used? * * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector * can be easily overridden by heavier selectors. For example, something as simple * as changing the display style on a HTML list item would make hidden elements appear visible. * This also becomes a bigger issue when dealing with CSS frameworks. * * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. * * ### Overriding `.ng-hide` * * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` * class in CSS: * * ```css * .ng-hide { * /&#42; this is just another form of hiding an element &#42;/ * display: block!important; * position: absolute; * top: -9999px; * left: -9999px; * } * ``` * * By default you don't need to override in CSS anything and the animations will work around the display style. * * ## A note about animations with `ngShow` * * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression * is true and false. This system works like the animation system present with ngClass except that * you must also include the !important flag to override the display property * so that you can perform an animation when the element is hidden during the time of the animation. * * ```css * // * //a working example can be found at the bottom of this page * // * .my-element.ng-hide-add, .my-element.ng-hide-remove { * /&#42; this is required as of 1.3x to properly * apply all styling in a show/hide animation &#42;/ * transition: 0s linear all; * } * * .my-element.ng-hide-add-active, * .my-element.ng-hide-remove-active { * /&#42; the transition is defined in the active class &#42;/ * transition: 1s linear all; * } * * .my-element.ng-hide-add { ... } * .my-element.ng-hide-add.ng-hide-add-active { ... } * .my-element.ng-hide-remove { ... } * .my-element.ng-hide-remove.ng-hide-remove-active { ... } * ``` * * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display * property to block during animation states--ngAnimate will handle the style toggling automatically for you. * * @animations * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <div class="check-element animate-show" ng-show="checked"> <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked. </div> </div> <div> Hide: <div class="check-element animate-show" ng-hide="checked"> <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked. </div> </div> </file> <file name="glyphicons.css"> @import url(../../components/bootstrap-3.1.1/css/bootstrap.css); </file> <file name="animations.css"> .animate-show { line-height: 20px; opacity: 1; padding: 10px; border: 1px solid black; background: white; } .animate-show.ng-hide-add.ng-hide-add-active, .animate-show.ng-hide-remove.ng-hide-remove-active { -webkit-transition: all linear 0.5s; transition: all linear 0.5s; } .animate-show.ng-hide { line-height: 0; opacity: 0; padding: 0 10px; } .check-element { padding: 10px; border: 1px solid black; background: white; } </file> <file name="protractor.js" type="protractor"> var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); it('should check ng-show / ng-hide', function() { expect(thumbsUp.isDisplayed()).toBeFalsy(); expect(thumbsDown.isDisplayed()).toBeTruthy(); element(by.model('checked')).click(); expect(thumbsUp.isDisplayed()).toBeTruthy(); expect(thumbsDown.isDisplayed()).toBeFalsy(); }); </file> </example> */ var ngShowDirective = ['$animate', function($animate) { return { restrict: 'A', multiElement: true, link: function(scope, element, attr) { scope.$watch(attr.ngShow, function ngShowWatchAction(value) { // we're adding a temporary, animation-specific class for ng-hide since this way // we can control when the element is actually displayed on screen without having // to have a global/greedy CSS selector that breaks when other animations are run. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845 $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, { tempClasses: NG_HIDE_IN_PROGRESS_CLASS }); }); } }; }]; /** * @ngdoc directive * @name ngHide * * @description * The `ngHide` directive shows or hides the given HTML element based on the expression * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined * in AngularJS and sets the display style to none (using an !important flag). * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). * * ```html * <!-- when $scope.myValue is truthy (element is hidden) --> * <div ng-hide="myValue" class="ng-hide"></div> * * <!-- when $scope.myValue is falsy (element is visible) --> * <div ng-hide="myValue"></div> * ``` * * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed * from the element causing the element not to appear hidden. * * ## Why is !important used? * * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector * can be easily overridden by heavier selectors. For example, something as simple * as changing the display style on a HTML list item would make hidden elements appear visible. * This also becomes a bigger issue when dealing with CSS frameworks. * * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. * * ### Overriding `.ng-hide` * * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` * class in CSS: * * ```css * .ng-hide { * /&#42; this is just another form of hiding an element &#42;/ * display: block!important; * position: absolute; * top: -9999px; * left: -9999px; * } * ``` * * By default you don't need to override in CSS anything and the animations will work around the display style. * * ## A note about animations with `ngHide` * * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide` * CSS class is added and removed for you instead of your own CSS class. * * ```css * // * //a working example can be found at the bottom of this page * // * .my-element.ng-hide-add, .my-element.ng-hide-remove { * transition: 0.5s linear all; * } * * .my-element.ng-hide-add { ... } * .my-element.ng-hide-add.ng-hide-add-active { ... } * .my-element.ng-hide-remove { ... } * .my-element.ng-hide-remove.ng-hide-remove-active { ... } * ``` * * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display * property to block during animation states--ngAnimate will handle the style toggling automatically for you. * * @animations * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} is truthy then * the element is shown or hidden respectively. * * @example <example module="ngAnimate" deps="angular-animate.js" animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <div class="check-element animate-hide" ng-show="checked"> <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked. </div> </div> <div> Hide: <div class="check-element animate-hide" ng-hide="checked"> <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked. </div> </div> </file> <file name="glyphicons.css"> @import url(../../components/bootstrap-3.1.1/css/bootstrap.css); </file> <file name="animations.css"> .animate-hide { -webkit-transition: all linear 0.5s; transition: all linear 0.5s; line-height: 20px; opacity: 1; padding: 10px; border: 1px solid black; background: white; } .animate-hide.ng-hide { line-height: 0; opacity: 0; padding: 0 10px; } .check-element { padding: 10px; border: 1px solid black; background: white; } </file> <file name="protractor.js" type="protractor"> var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); it('should check ng-show / ng-hide', function() { expect(thumbsUp.isDisplayed()).toBeFalsy(); expect(thumbsDown.isDisplayed()).toBeTruthy(); element(by.model('checked')).click(); expect(thumbsUp.isDisplayed()).toBeTruthy(); expect(thumbsDown.isDisplayed()).toBeFalsy(); }); </file> </example> */ var ngHideDirective = ['$animate', function($animate) { return { restrict: 'A', multiElement: true, link: function(scope, element, attr) { scope.$watch(attr.ngHide, function ngHideWatchAction(value) { // The comment inside of the ngShowDirective explains why we add and // remove a temporary class for the show/hide animation $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, { tempClasses: NG_HIDE_IN_PROGRESS_CLASS }); }); } }; }]; /** * @ngdoc directive * @name ngStyle * @restrict AC * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle * * {@link guide/expression Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * Since some CSS style names are not valid keys for an object, they must be quoted. * See the 'background-color' style in the example below. * * @example <example> <file name="index.html"> <input type="button" value="set color" ng-click="myStyle={color:'red'}"> <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </file> <file name="style.css"> span { color: black; } </file> <file name="protractor.js" type="protractor"> var colorSpan = element(by.css('span')); it('should check ng-style', function() { expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); element(by.css('input[value=\'set color\']')).click(); expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); element(by.css('input[value=clear]')).click(); expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); }); </file> </example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }, true); }); /** * @ngdoc directive * @name ngSwitch * @restrict EA * * @description * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location * as specified in the template. * * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element * matches the value obtained from the evaluated expression. In other words, you define a container element * (where you place the directive), place an expression on the **`on="..."` attribute** * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default * attribute is displayed. * * <div class="alert alert-info"> * Be aware that the attribute values to match against cannot be expressions. They are interpreted * as literal string values to match against. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the * value of the expression `$scope.someVal`. * </div> * @animations * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM * * @usage * * ``` * <ANY ng-switch="expression"> * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * <ANY ng-switch-default>...</ANY> * </ANY> * ``` * * * @scope * @priority 1200 * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * On child elements add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. If the same match appears multiple times, all the * elements will be displayed. * * `ngSwitchDefault`: the default case when no other case match. If there * are multiple default cases, all of them will be displayed when no other * case match. * * * @example <example module="switchExample" deps="angular-animate.js" animations="true"> <file name="index.html"> <div ng-controller="ExampleController"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div class="animate-switch-container" ng-switch on="selection"> <div class="animate-switch" ng-switch-when="settings">Settings Div</div> <div class="animate-switch" ng-switch-when="home">Home Span</div> <div class="animate-switch" ng-switch-default>default</div> </div> </div> </file> <file name="script.js"> angular.module('switchExample', ['ngAnimate']) .controller('ExampleController', ['$scope', function($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; }]); </file> <file name="animations.css"> .animate-switch-container { position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .animate-switch { padding:10px; } .animate-switch.ng-animate { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; } .animate-switch.ng-leave.ng-leave-active, .animate-switch.ng-enter { top:-50px; } .animate-switch.ng-leave, .animate-switch.ng-enter.ng-enter-active { top:0; } </file> <file name="protractor.js" type="protractor"> var switchElem = element(by.css('[ng-switch]')); var select = element(by.model('selection')); it('should start in settings', function() { expect(switchElem.getText()).toMatch(/Settings Div/); }); it('should change to home', function() { select.all(by.css('option')).get(1).click(); expect(switchElem.getText()).toMatch(/Home Span/); }); it('should select default', function() { select.all(by.css('option')).get(2).click(); expect(switchElem.getText()).toMatch(/default/); }); </file> </example> */ var ngSwitchDirective = ['$animate', function($animate) { return { restrict: 'EA', require: 'ngSwitch', // asks for $scope to fool the BC controller module controller: ['$scope', function ngSwitchController() { this.cases = {}; }], link: function(scope, element, attr, ngSwitchController) { var watchExpr = attr.ngSwitch || attr.on, selectedTranscludes = [], selectedElements = [], previousLeaveAnimations = [], selectedScopes = []; var spliceFactory = function(array, index) { return function() { array.splice(index, 1); }; }; scope.$watch(watchExpr, function ngSwitchWatchAction(value) { var i, ii; for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) { $animate.cancel(previousLeaveAnimations[i]); } previousLeaveAnimations.length = 0; for (i = 0, ii = selectedScopes.length; i < ii; ++i) { var selected = getBlockNodes(selectedElements[i].clone); selectedScopes[i].$destroy(); var promise = previousLeaveAnimations[i] = $animate.leave(selected); promise.then(spliceFactory(previousLeaveAnimations, i)); } selectedElements.length = 0; selectedScopes.length = 0; if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { forEach(selectedTranscludes, function(selectedTransclude) { selectedTransclude.transclude(function(caseElement, selectedScope) { selectedScopes.push(selectedScope); var anchor = selectedTransclude.element; caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: '); var block = { clone: caseElement }; selectedElements.push(block); $animate.enter(caseElement, anchor.parent(), anchor); }); }); } }); } }; }]; var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 1200, require: '^ngSwitch', multiElement: true, link: function(scope, element, attrs, ctrl, $transclude) { ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element }); } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 1200, require: '^ngSwitch', multiElement: true, link: function(scope, element, attr, ctrl, $transclude) { ctrl.cases['?'] = (ctrl.cases['?'] || []); ctrl.cases['?'].push({ transclude: $transclude, element: element }); } }); /** * @ngdoc directive * @name ngTransclude * @restrict EAC * * @description * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. * * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. * * @element ANY * * @example <example module="transcludeExample"> <file name="index.html"> <script> angular.module('transcludeExample', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: { title:'@' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<ng-transclude></ng-transclude>' + '</div>' }; }) .controller('ExampleController', ['$scope', function($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; }]); </script> <div ng-controller="ExampleController"> <input ng-model="title"><br> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </file> <file name="protractor.js" type="protractor"> it('should have transcluded', function() { var titleElement = element(by.model('title')); titleElement.clear(); titleElement.sendKeys('TITLE'); var textElement = element(by.model('text')); textElement.clear(); textElement.sendKeys('TEXT'); expect(element(by.binding('title')).getText()).toEqual('TITLE'); expect(element(by.binding('text')).getText()).toEqual('TEXT'); }); </file> </example> * */ var ngTranscludeDirective = ngDirective({ restrict: 'EAC', link: function($scope, $element, $attrs, controller, $transclude) { if (!$transclude) { throw minErr('ngTransclude')('orphan', 'Illegal use of ngTransclude directive in the template! ' + 'No parent directive that requires a transclusion found. ' + 'Element: {0}', startingTag($element)); } $transclude(function(clone) { $element.empty(); $element.append(clone); }); } }); /** * @ngdoc directive * @name script * @restrict E * * @description * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the * template can be used by {@link ng.directive:ngInclude `ngInclude`}, * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be * assigned through the element's `id`, which can then be used as a directive's `templateUrl`. * * @param {string} type Must be set to `'text/ng-template'`. * @param {string} id Cache name of the template. * * @example <example> <file name="index.html"> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </file> <file name="protractor.js" type="protractor"> it('should load template defined inside script tag', function() { element(by.css('#tpl-link')).click(); expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/); }); </file> </example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; var ngOptionsMinErr = minErr('ngOptions'); /** * @ngdoc directive * @name select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * The `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for the `<select>` element using the array or object obtained by evaluating the * `ngOptions` comprehension_expression. * * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a * similar result. However, the `ngOptions` provides some benefits such as reducing memory and * increasing speed by not creating a new scope for each repeated instance, as well as providing * more flexibility in how the `select`'s model is assigned via `select as`. `ngOptions` should be * used when the `select` model needs to be bound to a non-string value. This is because an option * element can only be bound to string values at present. * * When an item in the `<select>` menu is selected, the array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent the `null` or "not selected" * option. See example below for demonstration. * * <div class="alert alert-warning"> * **Note:** `ngModel` compares by reference, not value. This is important when binding to an * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/). * </div> * * ## `select as` * * Using `select as` will bind the result of the `select as` expression to the model, but * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources) * or property name (for object data sources) of the value within the collection. If a `track by` expression * is used, the result of that expression will be set as the value of the `option` and `select` elements. * * ### `select as` with `trackexpr` * * Using `select as` together with `trackexpr` is not recommended. Reasoning: * * - Example: &lt;select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"&gt; * values: [{id: 1, label: 'aLabel', subItem: {name: 'aSubItem'}}, {id: 2, label: 'bLabel', subItem: {name: 'bSubItem'}}], * $scope.selected = {name: 'aSubItem'}; * - track by is always applied to `value`, with the purpose of preserving the selection, * (to `item` in this case) * - to calculate whether an item is selected we do the following: * 1. apply `track by` to the values in the array, e.g. * In the example: [1,2] * 2. apply `track by` to the already selected value in `ngModel`: * In the example: this is not possible, as `track by` refers to `item.id`, but the selected * value from `ngModel` is `{name: aSubItem}`. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required The control is considered valid only if value is entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be * used to identify the objects in the array. The `trackexpr` will most likely refer to the * `value` variable (e.g. `value.propertyName`). With this the selection is preserved * even when the options are recreated (e.g. reloaded from the server). * * @example <example module="selectExample"> <file name="index.html"> <script> angular.module('selectExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.myColor = $scope.colors[2]; // red }]); </script> <div ng-controller="ExampleController"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.splice($index, 1)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="myColor" ng-options="color.name for color in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="myColor" ng-options="color.name for color in colors"> <option value="">-- choose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors"> </select><br/> Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:myColor} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':myColor.name}"> </div> </div> </file> <file name="protractor.js" type="protractor"> it('should check ng-options', function() { expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red'); element.all(by.model('myColor')).first().click(); element.all(by.css('select[ng-model="myColor"] option')).first().click(); expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black'); element(by.css('.nullable select[ng-model="myColor"]')).click(); element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(); expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null'); }); </file> </example> */ var ngOptionsDirective = valueFn({ restrict: 'A', terminal: true }); // jshint maxlen: false var selectDirective = ['$compile', '$parse', function($compile, $parse) { //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888 var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/, nullModelCtrl = {$setViewValue: noop}; // jshint maxlen: 100 return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.databound = $attrs.ngModel; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; }; self.addOption = function(value, element) { assertNotHasOwnProperty(value, '"option value"'); optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459 // Adding an <option selected="selected"> element to a <select required="required"> should // automatically select the new element if (element && element[0].hasAttribute('selected')) { element[0].selected = true; } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue == value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE }; self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); }; $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, renderScheduled = false, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value === '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple) { ngModelCtrl.$isEmpty = function(value) { return !value || value.length === 0; }; } if (optionsExp) setupAsOptions(scope, element, ngModelCtrl); else if (multiple) setupAsMultiple(scope, element, ngModelCtrl); else setupAsSingle(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.on('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function setupAsMultiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.find('option'), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function selectMultipleWatch() { if (!equals(lastView, ctrl.$viewValue)) { lastView = shallowCopy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.on('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.find('option'), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function setupAsOptions(scope, selectElement, ctrl) { var match; if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw ngOptionsMinErr('iexp', "Expected expression in form of " + "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" + " but got '{0}'. Element: {1}", optionsExp, startingTag(selectElement)); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], selectAs = / as /.test(match[0]) && match[1], selectAsFn = selectAs ? $parse(selectAs) : null, keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), track = match[8], trackFn = track ? $parse(match[8]) : null, trackKeysCache = {}, // This is an array of array of existing option groups in DOM. // We try to reuse these if possible // - optionGroupsCache[0] is the options with no option group // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]], //re-usable object to represent option's locals locals = {}; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.empty() because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.empty(); selectElement.on('change', selectionChanged); ctrl.$render = render; scope.$watchCollection(valuesFn, scheduleRendering); scope.$watchCollection(getLabels, scheduleRendering); if (multiple) { scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering); } // ------------------------------------------------------------------ // function callExpression(exprFn, key, value) { locals[valueName] = value; if (keyName) locals[keyName] = key; return exprFn(scope, locals); } function selectionChanged() { scope.$apply(function() { var collection = valuesFn(scope) || []; var viewValue; if (multiple) { viewValue = []; forEach(selectElement.val(), function(selectedKey) { selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey; viewValue.push(getViewValue(selectedKey, collection[selectedKey])); }); } else { var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val(); viewValue = getViewValue(selectedKey, collection[selectedKey]); } ctrl.$setViewValue(viewValue); render(); }); } function getViewValue(key, value) { if (key === '?') { return undefined; } else if (key === '') { return null; } else { var viewValueFn = selectAsFn ? selectAsFn : valueFn; return callExpression(viewValueFn, key, value); } } function getLabels() { var values = valuesFn(scope); var toDisplay; if (values && isArray(values)) { toDisplay = new Array(values.length); for (var i = 0, ii = values.length; i < ii; i++) { toDisplay[i] = callExpression(displayFn, i, values[i]); } return toDisplay; } else if (values) { // TODO: Add a test for this case toDisplay = {}; for (var prop in values) { if (values.hasOwnProperty(prop)) { toDisplay[prop] = callExpression(displayFn, prop, values[prop]); } } } return toDisplay; } function createIsSelectedFn(viewValue) { var selectedSet; if (multiple) { if (trackFn && isArray(viewValue)) { selectedSet = new HashMap([]); for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) { // tracking by key selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true); } } else { selectedSet = new HashMap(viewValue); } } else if (trackFn) { viewValue = callExpression(trackFn, null, viewValue); } return function isSelected(key, value) { var compareValueFn; if (trackFn) { compareValueFn = trackFn; } else if (selectAsFn) { compareValueFn = selectAsFn; } else { compareValueFn = valueFn; } if (multiple) { return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value))); } else { return viewValue === callExpression(compareValueFn, key, value); } }; } function scheduleRendering() { if (!renderScheduled) { scope.$$postDigest(render); renderScheduled = true; } } /** * A new labelMap is created with each render. * This function is called for each existing option with added=false, * and each new option with added=true. * - Labels that are passed to this method twice, * (once with added=true and once with added=false) will end up with a value of 0, and * will cause no change to happen to the corresponding option. * - Labels that are passed to this method only once with added=false will end up with a * value of -1 and will eventually be passed to selectCtrl.removeOption() * - Labels that are passed to this method only once with added=true will end up with a * value of 1 and will eventually be passed to selectCtrl.addOption() */ function updateLabelMap(labelMap, label, added) { labelMap[label] = labelMap[label] || 0; labelMap[label] += (added ? 1 : -1); } function render() { renderScheduled = false; // Temporary location for the option groups before we render them var optionGroups = {'':[]}, optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, viewValue = ctrl.$viewValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, key, value, groupLength, length, groupIndex, index, labelMap = {}, selected, isSelected = createIsSelectedFn(viewValue), anySelected = false, lastElement, element, label, optionId; trackKeysCache = {}; // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { key = index; if (keyName) { key = keys[index]; if (key.charAt(0) === '$') continue; } value = values[key]; optionGroupName = callExpression(groupByFn, key, value) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } selected = isSelected(key, value); anySelected = anySelected || selected; label = callExpression(displayFn, key, value); // what will be seen by the user // doing displayFn(scope, locals) || '' overwrites zero values label = isDefined(label) ? label : ''; optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index); if (trackFn) { trackKeysCache[optionId] = key; } optionGroup.push({ // either the index into array or key from object id: optionId, label: label, selected: selected // determine if we should be selected }); } if (!multiple) { if (nullOption || viewValue === null) { // insert null option if we have a placeholder, or the model is null optionGroups[''].unshift({id:'', label:'', selected:!anySelected}); } else if (!anySelected) { // option could not be found, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for (index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index + 1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { updateLabelMap(labelMap, existingOption.label, false); updateLabelMap(labelMap, option.label, true); lastElement.text(existingOption.label = option.label); lastElement.prop('label', existingOption.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } // lastElement.prop('selected') provided by jQuery has side-effects if (lastElement[0].selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); if (msie) { // See #7692 // The selected item wouldn't visually update on IE without this. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well lastElement.prop('selected', existingOption.selected); } } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .prop('selected', option.selected) .attr('selected', option.selected) .prop('label', option.label) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); updateLabelMap(labelMap, option.label, true); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while (existingOptions.length > index) { option = existingOptions.pop(); updateLabelMap(labelMap, option.label, false); option.element.remove(); } forEach(labelMap, function(count, label) { if (count > 0) { selectCtrl.addOption(label); } else if (count < 0) { selectCtrl.removeOption(label); } }); } // remove any excessive OPTGROUPs from select while (optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } } } }; }]; var optionDirective = ['$interpolate', function($interpolate) { var nullSelectCtrl = { addOption: noop, removeOption: noop }; return { restrict: 'E', priority: 100, compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } return function(scope, element, attr) { var selectCtrlName = '$selectController', parent = element.parent(), selectCtrl = parent.data(selectCtrlName) || parent.parent().data(selectCtrlName); // in case we are in optgroup if (!selectCtrl || !selectCtrl.databound) { selectCtrl = nullSelectCtrl; } if (interpolateFn) { scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) { attr.$set('value', newVal); if (oldVal !== newVal) { selectCtrl.removeOption(oldVal); } selectCtrl.addOption(newVal, element); }); } else { selectCtrl.addOption(attr.value, element); } element.on('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } }; }]; var styleDirective = valueFn({ restrict: 'E', terminal: false }); if (window.angular.bootstrap) { //AngularJS is already loaded, so we can return here... console.log('WARNING: Tried to load angular more than once.'); return; } //try to bind to jquery now so that one can write jqLite(document).ready() //but we will rebind on bootstrap again. bindJQuery(); publishExternalAPI(angular); jqLite(document).ready(function() { angularInit(document, bootstrap); }); })(window, document); !window.angular.$$csp() && window.angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}</style>');
CKEDITOR.plugins.setLang("uicolor","el",{title:"Διεπαφή Επιλογής Χρωμάτων",options:"Color Options",highlight:"Highlight",selected:"Selected Color",predefined:"Προκαθορισμένα σύνολα χρωμάτων",config:"Επικολλήστε αυτό το κείμενο στο αρχείο config.js"});
/** * @module PreloadJS */ (function () { "use strict"; /** * A PreloadJS plugin provides a way to inject functionality into PreloadJS to load file types that are unsupported, * or in a way that PreloadJS does not. * * <strong>Note that this class is mainly for documentation purposes, and is not a real plugin.</strong> * * Plugins are registered based on file extension, or supported preload types, which are defined as constants on * the {{#crossLink "LoadQueue"}}{{/crossLink}} class. Available load types are: * <ul> * <li>binary ({{#crossLink "LoadQueue/BINARY:property"}}{{/crossLink}})</li> * <li>css ({{#crossLink "LoadQueue/CSS:property"}}{{/crossLink}})</li> * <li>image ({{#crossLink "LoadQueue/IMAGE:property"}}{{/crossLink}})</li> * <li>javascript ({{#crossLink "LoadQueue/JAVASCRIPT:property"}}{{/crossLink}})</li> * <li>json ({{#crossLink "LoadQueue/JSON:property"}}{{/crossLink}})</li> * <li>jsonp ({{#crossLink "LoadQueue/JSONP:property"}}{{/crossLink}})</li> * <li>manifest ({{#crossLink "LoadQueue/MANIFEST:property"}}{{/crossLink}})</li> * <li>sound ({{#crossLink "LoadQueue/SOUND:property"}}{{/crossLink}})</li> * <li>spriteSheet ({{#crossLink "LoadQueue/SPRITESHEET:property"}}{{/crossLink}})</li> * <li>svg ({{#crossLink "LoadQueue/SVG:property"}}{{/crossLink}})</li> * <li>text ({{#crossLink "LoadQueue/TEXT:property"}}{{/crossLink}})</li> * <li>xml ({{#crossLink "LoadQueue/XML:property"}}{{/crossLink}})</li> * </ul> * * A plugin defines what types or extensions it handles via a {{#crossLink "SamplePlugin/getPreloadHandlers"}}{{/crossLink}} * method, which is called when a plugin is first registered. * * To register a plugin with PreloadJS, simply install it into a LoadQueue before files begin to load using the * {{#crossLink "LoadQueue/installPlugin"}}{{/crossLink}} method: * * var queue = new createjs.LoadQueue(); * queue.installPlugin(createjs.SamplePlugin); * queue.loadFile("test.jpg"); * * The {{#crossLink "SamplePlugin/getPreloadHandlers"}}{{/crossLink}} method can also return a `callback` * property, which is a function that will be invoked before each file is loaded. Check out the {{#crossLink "SamplePlugin/preloadHandler"}}{{/crossLink}} * for more information on how the callback works. For example, the SoundJS plugin allows PreloadJS to manage a * download that uses the Flash Player. * * @class SamplePlugin * @static */ var SamplePlugin = function () { }; var s = SamplePlugin; /** * When a plugin is installed, this method will be called to let PreloadJS know when to invoke the plugin. * * PreloadJS expects this method to return an object containing: * <ul> * <li><strong>callback:</strong> The function to call on the plugin class right before an item is loaded. Check * out the {{#crossLink "SamplePlugin/preloadHandler"}}{{/crossLink}} method for more information. The callback * is automatically called in the scope of the plugin.</li> * <li><strong>types:</strong> An array of recognized PreloadJS load types to handle. Supported load types are * "binary","image", "javascript", "json", "jsonp", "sound", "svg", "text", and "xml".</li> * <li><strong>extensions:</strong> An array of strings containing file extensions to handle, such as "jpg", * "mp3", etc. This only fires if an applicable type handler is not found by the plugin.</li> * </ul> * * Note that currently, PreloadJS only supports a single handler for each extension or file type. * * <h4>Example</h4> * * // Check out the SamplePlugin source for a more complete example. * SamplePlugin.getPreloadHandlers = function() { * return { * callback: SamplePlugin.preloadHandler, * extensions: ["jpg", "jpeg", "png", "gif"] * } * } * * If a plugin provides both "type" and "extension" handlers, the type handler will take priority, and will only * fire once per file. For example if you have a handler for type=sound, and for extension=mp3, the callback will * fire when it matches the type. * * @method getPreloadHandlers * @return {Object} An object defining a callback, type handlers, and extension handlers (see description) */ s.getPreloadHandlers = function () { return { callback: s.preloadHandler, // Proxy the method to maintain scope types: ["image"], extensions: ["jpg", "jpeg", "png", "gif"] } }; /** * This is a sample method to show how to handle the callback specified in the {{#crossLink "LoadQueue/getPreloadHandlers"}}{{/crossLink}}. * Right before a file is loaded, if a plugin for the file type or extension is found, then the callback for that * plugin will be invoked. This gives the plugin an opportunity to modify the load item, or even cancel the load. * The return value of the callback determines how PreloadJS will handle the file: * <ul> * <li><strong>false:</strong> Skip the item. This allows plugins to determine if a file should be loaded or * not. For example,the plugin could determine if a file type is supported at all on the current system, and * skip those that do not.</li> * <li><strong>true:</strong> Continue normally. The plugin will not affect the load.</li> * <li><strong>AbstractLoader instance:</strong> Used as the loader for the content. This is new in 0.6.0.</li> * </ul> * * Since the {{#crossLink "LoadItem"}}{{/crossLink}} is passed by reference, a plugin can modify as needed, even * appending additional data to it. Note that if the {{#crossLink "LoadItem/src:property"}}{{/crossLink}} is * modified, PreloadJS will automatically update the {{#crossLink "LoadItem/ext:property"}}{{/crossLink}} property. * * <h4>Example</h4> * * // Cancel a load * SamplePlugin.preloadHandler = function(loadItem, queue) { * if (loadItem.id.indexOf("thumb") { return false; } // Don't load items like "image-thumb.png" * return true; * } * * // Specify a completeHandler * SamplePlugin.preloadHandler = function(loadItem, queue) { * item.completeHandler = SamplePlugin.fileLoadHandler; * } * * // Check out the SamplePlugin source to see another example. * * <em>Note: In 0.4.2 and earlier, instead of a {{#crossLink "LoadItem"}}{{/crossLink}}, arguments were passed in, * and a modified object was returned to PreloadJS. This has been changed to passing a reference to the LoadItem, * which can be directly modified.</em> * * @method preloadHandler * @param {LoadItem|Object} loadItem The item that PreloadJS is going to load. This item is passes by reference, * so it can be directly modified. * @param {LoadQueue} queue The {{#crossLink "LoadQueue"}}{{/crossLink}} instance that is preloading the item. * @return {Boolean|AbstractLoader} How PreloadJS should handle the load. See the main description for more info. */ s.preloadHandler = function (loadItem, queue) { var options = {}; // Tell PreloadJS to skip this file if (options.stopDownload) { return false; } // Tell PreloadJS to continue normally if (options.doNothing) { return true; } // Modify the LoadItem loadItem.id = "newId"; loadItem.completeHandler = createjs.proxy(s.fileCompleteHandler, s); // Return a new loader. This is an advanced usage, similar to what SoundJS does. var loader = new createjs.ImageLoader(loadItem); loader.on("complete", createjs.proxy(s.fileCompleteHandler, s)); return loader; }; /** * This is a sample method to show a `completeHandler`, which is optionally specified by the return object in the * {{#crossLink "SamplePlugin/preloadHandler"}}{{/crossLink}}. This sample provides a `completeHandler` to the * {{#crossLink "LoadItem"}}{{/crossLink}}. This method is called after the item has completely loaded, but before * the {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}} event is dispatched from the {{#crossLink "LoadQueue"}}{{/crossLink}}. * * The provided sample also listens for the {{#crossLink "AbstractLoader/complete:event"}}{{/crossLink}} * event on the loader it returns to show a different usage. * * @method fileLoadHandler * @param event {Event} A {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}} event. */ s.fileLoadHandler = function (event) { // Do something with the result. }; createjs.SamplePlugin = SamplePlugin; }());
exports.BattleFormatsData = { purrloin: { randomBattleMoves: ["foulplay","swagger","substitute","thunderwave"], tier: "LC" }, liepard: { randomBattleMoves: ["foulplay","swagger","substitute","thunderwave"], tier: "NU" } };
///* // * storage-object-test.js: Tests for uploading files to Rackspace Cloudfiles when not authenticated. // * // * (C) 2010 Charlie Robbins, Ken Perkins, Ross Kukulinski & the Contributors. // * MIT LICENSE // * // */ // // TODO Enable all rackspace storage client tests with mocks //var path = require('path'), // vows = require('vows'), // fs = require('fs'), // assert = require('../../helpers/assert'), // macros = require('../macros'), // pkgcloud = require('../../../lib/pkgcloud'), // helpers = require('../../helpers'); // //if (process.env.MOCK) { // return; //} // //var client = function () { // return helpers.createClient('rackspace', 'storage') // }, // fixturesDir = path.join(__dirname, '..', '..', 'fixtures'), // sampleData = fs.readFileSync(path.join(fixturesDir, 'fillerama.txt'), 'utf8'), // testData = {}; // //vows.describe('pkgcloud/rackspace/storage/file').addBatch( // macros.shouldCreateContainer( // client(), // 'test_storage_objects' // ) //).addBatch({ // "The pkgcloud Rackspace storage client": { // "the upload() method": { // "with a filepath": macros.upload.fullpath(client(), { // container: 'test_storage_objects', // remote: 'file1.txt', // local: path.join(fixturesDir, 'fillerama.txt') // }), // "with a ReadStream instance": macros.upload.stream( // client(), // 'test_storage_objects', // path.join(fixturesDir, 'fillerama.txt'), // 'file3.txt' // ), // "when piped to": macros.upload.piped( // client(), // 'test_storage_objects', // path.join(fixturesDir, 'fillerama.txt'), // 'file2.txt' // ) // } // } //}).addBatch({ // "The pkgcloud Rackspace storage client": { // "the getFiles() method": { // topic: function () { // client().getFiles('test_storage_objects', this.callback); // }, // "should return a valid list of files": function (err, files) { // files.forEach(function (file) { // assert.assertFile(file); // }); // } // } // } //}).addBatch({ // "The pkgcloud Rackspace storage client": { // "the getFile() method": { // "for a file that exists": { // topic: function () { // client().getFile('test_storage_objects', 'file1.txt', this.callback); // }, // "should return a valid File": function (err, file) { // assert.assertFile(file); // testData.file = file; // } // } // } // } //}).addBatch({ // "The pkgcloud Rackspace storage client": { // "the download() method": { // topic: function () { // var that = this; // var dstream = client().download({ // container: 'test_storage_objects', // remote: 'file3.txt', // local: path.join(__dirname, '..', '..', 'fixtures', 'test-download3.txt') // }, function () { }); // // dstream.on('end', function () { // // // // TODO: Check fs.stat on the file we just saved. // // // setTimeout(that.callback, 5000); // }); // }, // "should write the file to the specified location": function (err, stats) { // assert.isNull(err); // //assert.isNotNull(stats); // } // } // } //})/*.addBatch({ // "The pkgcloud Rackspace storage client": { // "the destroyFile() method": { // "for a file that exists": { // topic: function () { // client.destroyFile('test_storage_objects', 'file1.txt', this.callback); // }, // "should return true": function (err, deleted) { // assert.isTrue(deleted); // } // } // } // } //}).addBatch({ // "The pkgcloud Rackspace storage client": { // "an instance of a StorageObject": { // "the destroy() method": { // "for a file that exists": { // topic: function () { // testData.file.destroy(this.callback); // }, // "should return true": function (err, deleted) { // assert.isTrue(deleted); // } // } // } // } // } //})*/.export(module);
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('leaflet'), require('react'), require('react-dom')) : typeof define === 'function' && define.amd ? define(['exports', 'leaflet', 'react', 'react-dom'], factory) : (factory((global.ReactLeaflet = {}),global.L,global.React,global.ReactDOM)); }(this, (function (exports,leaflet,React,reactDom) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; 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; /** * 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. * */ /** * 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. */ var validateFormat = function validateFormat(format) {}; { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); 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; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction_1; { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { 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) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } var warning_1 = warning; /* 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 invariant$1 = invariant_1; var warning$1 = warning_1; var ReactPropTypesSecret$1 = ReactPropTypesSecret_1; var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant$1(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1); } catch (ex) { error = ex; } warning$1(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); 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] = true; var stack = getStack ? getStack() : ''; warning$1(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } var checkPropTypes_1 = checkPropTypes; var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // 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]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker, }; /** * 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 if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret_1) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package 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' ); } else if ("development" !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { warning_1( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction_1.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + 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 + ']', ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` 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 expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { warning_1(false, 'Invalid argument supplied to oneOf, expected an instance of array.'); return emptyFunction_1.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + 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, ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { warning_1(false, 'Invalid argument supplied to oneOfType, expected an instance of array.'); return emptyFunction_1.thatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { warning_1( false, 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received %s at index %s.', getPostfixForTypeWarning(checker), i ); return emptyFunction_1.thatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + 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]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } // We need to check all keys in case some are required but missing from // props. var allKeys = objectAssign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes_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. */ { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = factoryWithTypeCheckers(isValidElement, throwOnDirectAccess); } }); var latlng = propTypes.oneOfType([propTypes.arrayOf(propTypes.number), // [number, number] propTypes.shape({ lat: propTypes.number, lng: propTypes.number }), propTypes.shape({ lat: propTypes.number, lon: propTypes.number })]); var latlngList = propTypes.arrayOf(latlng); var bounds = propTypes.oneOfType([propTypes.instanceOf(leaflet.LatLngBounds), latlngList]); var children = propTypes.oneOfType([propTypes.arrayOf(propTypes.node), propTypes.node]); var controlPositionType = propTypes.oneOf(['topleft', 'topright', 'bottomleft', 'bottomright']); var layer = propTypes.object; var layerContainer = propTypes.shape({ addLayer: propTypes.func.isRequired, removeLayer: propTypes.func.isRequired }); var map = propTypes.instanceOf(leaflet.Map); var viewport = propTypes.shape({ center: latlng, zoom: propTypes.number }); var index = Object.freeze({ bounds: bounds, children: children, controlPosition: controlPositionType, latlng: latlng, latlngList: latlngList, layer: layer, layerContainer: layerContainer, map: map, viewport: viewport }); 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 _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 MapControl = function (_Component) { inherits(MapControl, _Component); function MapControl() { classCallCheck(this, MapControl); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } // eslint-disable-next-line no-unused-vars MapControl.prototype.createLeafletElement = function createLeafletElement(props) { throw new Error('createLeafletElement() must be implemented'); }; MapControl.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.position !== fromProps.position) { this.leafletElement.setPosition(toProps.position); } }; MapControl.prototype.componentWillMount = function componentWillMount() { this.leafletElement = this.createLeafletElement(this.props); }; MapControl.prototype.componentDidMount = function componentDidMount() { this.leafletElement.addTo(this.context.map); }; MapControl.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { this.updateLeafletElement(prevProps, this.props); }; MapControl.prototype.componentWillUnmount = function componentWillUnmount() { this.leafletElement.remove(); }; MapControl.prototype.render = function render$$1() { return null; }; return MapControl; }(React.Component); MapControl.propTypes = { position: controlPositionType }; MapControl.contextTypes = { map: map }; var AttributionControl = function (_MapControl) { inherits(AttributionControl, _MapControl); function AttributionControl() { classCallCheck(this, AttributionControl); return possibleConstructorReturn(this, _MapControl.apply(this, arguments)); } AttributionControl.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.Control.Attribution(props); }; return AttributionControl; }(MapControl); AttributionControl.propTypes = { position: controlPositionType, prefix: propTypes.string }; /** * 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; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** 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')(); /** Built-in value references. */ var Symbol$1 = root.Symbol; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag$1 = Symbol$1 ? Symbol$1.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$1.call(value, symToStringTag$1), tag = value[symToStringTag$1]; try { value[symToStringTag$1] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag$1] = tag; } else { delete value[symToStringTag$1]; } } return result; } /** Used for built-in method references. */ var objectProto$1 = 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$1.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); } /** `Object#toString` result references. */ var nullTag = '[object Null]'; var undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol$1 ? Symbol$1.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 && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * 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'; } /** `Object#toString` result references. */ var symbolTag = '[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(value) && baseGetTag(value) == symbolTag); } /** 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(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * 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'); } /** `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(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; } /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** 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); } /** Used for built-in method references. */ var funcProto$1 = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.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$1.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * 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 = Function.prototype; var objectProto$2 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$2.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty$2).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(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * 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]; } /** * 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; } /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * 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; } /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$3.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$3.call(data, key) ? data[key] : undefined; } /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$4.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$4.call(data, key); } /** 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; } /** * 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; /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * 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); } /** * 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(array[length][0], key)) { return length; } } return -1; } /** 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; } /** * 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]; } /** * 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; } /** * 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; } /** * 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; /* Built-in method references that are verified to be native. */ var Map$1 = getNative(root, 'Map'); /** * 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$1 || ListCache), 'string': new Hash }; } /** * 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); } /** * 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; } /** * 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; } /** * 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); } /** * 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); } /** * 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; } /** * 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; /** 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; /** 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(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** 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; }); /** * 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; } /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined; var symbolToString = symbolProto ? symbolProto.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(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * 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); } /** * 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(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** 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(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } /** * 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 defineProperty$1 = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** * 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$1) { defineProperty$1(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$5.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$5.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 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 : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * 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(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(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * 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; } /** * 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); } /** `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(value) && baseGetTag(value) == argsTag; } /** Used for built-in method references. */ var objectProto$6 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$6.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$6.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(value) && hasOwnProperty$6.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 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$1; } /** * 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(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * 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); } /** * 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(object, path); }); } /** * 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; } /** Built-in value references. */ var spreadableSymbol = Symbol$1 ? Symbol$1.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(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * 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; } /** * 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) : []; } /** * 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); } /* 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); }; } /** * 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; }; } /** * 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; } /** * 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$1 ? identity : function(func, string) { return defineProperty$1(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** 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); }; } /** * 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); /** * 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), func + ''); } /** * 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); }); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * 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; } /** * 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); } /** * 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); } /** 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$1 || (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; } /** * 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; /** 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; } /** * 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); } /** * * 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; /** * 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; } /** * 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); } /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 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$1, 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; } /** Built-in value references. */ var Uint8Array = root.Uint8Array; /** * 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; } /** * 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; } /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; var COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]'; var dateTag = '[object Date]'; var errorTag = '[object Error]'; var mapTag = '[object Map]'; var numberTag = '[object Number]'; var regexpTag = '[object RegExp]'; var setTag = '[object Set]'; var stringTag = '[object String]'; var symbolTag$1 = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]'; var dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined; var symbolValueOf = symbolProto$1 ? symbolProto$1.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: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // 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: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2; 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$1: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * 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(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * 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; } /** * 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 []; } /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$9.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 : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable$1.call(object, symbol); }); }; /** * 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; } /** * 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; } /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == '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; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]'; var arrayTag$1 = '[object Array]'; var boolTag$1 = '[object Boolean]'; var dateTag$1 = '[object Date]'; var errorTag$1 = '[object Error]'; var funcTag$1 = '[object Function]'; var mapTag$1 = '[object Map]'; var numberTag$1 = '[object Number]'; var objectTag$1 = '[object Object]'; var regexpTag$1 = '[object RegExp]'; var setTag$1 = '[object Set]'; var stringTag$1 = '[object String]'; var weakMapTag = '[object WeakMap]'; var arrayBufferTag$1 = '[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$2] = typedArrayTags[arrayTag$1] = typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag$1] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag$1] = typedArrayTags[regexpTag$1] = typedArrayTags[setTag$1] = typedArrayTags[stringTag$1] = typedArrayTags[weakMapTag] = 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(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * 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); }; } /** Detect free variable `exports`. */ var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports$1 && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* 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; /** 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(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(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; } /** Used for built-in method references. */ var objectProto$12 = 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$12; return value === proto; } /** * 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)); }; } /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); /** 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 `_.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$10.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * 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(value.length) && !isFunction(value); } /** * 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(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * 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, getSymbols); } /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$8.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$3, 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$8.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; } /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); /* Built-in method references that are verified to be native. */ var Promise$1 = getNative(root, 'Promise'); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); /** `Object#toString` result references. */ var mapTag$2 = '[object Map]'; var objectTag$2 = '[object Object]'; var promiseTag = '[object Promise]'; var setTag$2 = '[object Set]'; var weakMapTag$1 = '[object WeakMap]'; var dataViewTag$2 = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView); var mapCtorString = toSource(Map$1); var promiseCtorString = toSource(Promise$1); 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$2) || (Map$1 && getTag(new Map$1) != mapTag$2) || (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag$2) || (WeakMap && getTag(new WeakMap) != weakMapTag$1)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag$2 ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$2; case mapCtorString: return mapTag$2; case promiseCtorString: return promiseTag; case setCtorString: return setTag$2; case weakMapCtorString: return weakMapTag$1; } } return result; }; } var getTag$1 = getTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]'; var arrayTag = '[object Array]'; var objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$7.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(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag$1(object), othTag = othIsArr ? arrayTag : getTag$1(other); objTag = objTag == argsTag$1 ? objectTag : objTag; othTag = othTag == argsTag$1 ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty$7.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$7.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); } /** * 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(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * 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); } /** * 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; } /** * 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; }; } /** * 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(); /** * 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); } /** * 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(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; }; } /** * 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); /** 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; } /** * 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(value); } /** * 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(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * 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))); }; } /** * 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); }; } /** * 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$1(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** 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(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } /** * 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]; }; } /** * 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); }; } /** * 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); } /** * 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; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * 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; } /** * 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(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * 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; } /** * 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; } /** * 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(collection) ? arrayEach : baseEach; return func(collection, castFunction(iteratee)); } /** * 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; } /** * 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(source), object); } /** * 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; } /** Used for built-in method references. */ var objectProto$13 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$11 = objectProto$13.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(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$11.call(object, key)))) { result.push(key); } } return result; } /** * 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(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * 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); } /** Detect free variable `exports`. */ var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; /** Built-in value references. */ var Buffer$1 = moduleExports$2 ? root.Buffer : undefined; var allocUnsafe = Buffer$1 ? Buffer$1.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; } /** * 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; } /** * 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); } /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); /* 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 : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * 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); } /** * 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); } /** Used for built-in method references. */ var objectProto$14 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$12 = objectProto$14.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$12.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * 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; } /** * 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); } /** * 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; } /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 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$1) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } /** 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; } /** * 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; } /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$2 = 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$2) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = Symbol$1 ? Symbol$1.prototype : undefined; var symbolValueOf$1 = symbolProto$2 ? symbolProto$2.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$1 ? Object(symbolValueOf$1.call(symbol)) : {}; } /** * 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); } /** `Object#toString` result references. */ var boolTag$3 = '[object Boolean]'; var dateTag$3 = '[object Date]'; var mapTag$4 = '[object Map]'; var numberTag$3 = '[object Number]'; var regexpTag$3 = '[object RegExp]'; var setTag$4 = '[object Set]'; var stringTag$3 = '[object String]'; var symbolTag$3 = '[object Symbol]'; var arrayBufferTag$3 = '[object ArrayBuffer]'; var dataViewTag$4 = '[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]'; /** * 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$3: return cloneArrayBuffer(object); case boolTag$3: case dateTag$3: return new Ctor(+object); case dataViewTag$4: return cloneDataView(object, isDeep); case float32Tag$2: case float64Tag$2: case int8Tag$2: case int16Tag$2: case int32Tag$2: case uint8Tag$2: case uint8ClampedTag$2: case uint16Tag$2: case uint32Tag$2: return cloneTypedArray(object, isDeep); case mapTag$4: return cloneMap(object, isDeep, cloneFunc); case numberTag$3: case stringTag$3: return new Ctor(object); case regexpTag$3: return cloneRegExp(object); case setTag$4: return cloneSet(object, isDeep, cloneFunc); case symbolTag$3: return cloneSymbol(object); } } /** 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(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * 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)) : {}; } /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; var CLONE_FLAT_FLAG = 2; var CLONE_SYMBOLS_FLAG$1 = 4; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]'; var arrayTag$2 = '[object Array]'; var boolTag$2 = '[object Boolean]'; var dateTag$2 = '[object Date]'; var errorTag$2 = '[object Error]'; var funcTag$2 = '[object Function]'; var genTag$1 = '[object GeneratorFunction]'; var mapTag$3 = '[object Map]'; var numberTag$2 = '[object Number]'; var objectTag$3 = '[object Object]'; var regexpTag$2 = '[object RegExp]'; var setTag$3 = '[object Set]'; var stringTag$2 = '[object String]'; var symbolTag$2 = '[object Symbol]'; var weakMapTag$2 = '[object WeakMap]'; var arrayBufferTag$2 = '[object ArrayBuffer]'; var dataViewTag$3 = '[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]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag$3] = cloneableTags[arrayTag$2] = cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] = cloneableTags[boolTag$2] = cloneableTags[dateTag$2] = cloneableTags[float32Tag$1] = cloneableTags[float64Tag$1] = cloneableTags[int8Tag$1] = cloneableTags[int16Tag$1] = cloneableTags[int32Tag$1] = cloneableTags[mapTag$3] = cloneableTags[numberTag$2] = cloneableTags[objectTag$3] = cloneableTags[regexpTag$2] = cloneableTags[setTag$3] = cloneableTags[stringTag$2] = cloneableTags[symbolTag$2] = cloneableTags[uint8Tag$1] = cloneableTags[uint8ClampedTag$1] = cloneableTags[uint16Tag$1] = cloneableTags[uint32Tag$1] = true; cloneableTags[errorTag$2] = 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, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG$1; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag$1(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag$3 || tag == argsTag$3 || (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); 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; } /** Used to compose bitmasks for cloning. */ var CLONE_SYMBOLS_FLAG = 4; /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } var EVENTS_RE = /^on(.+)$/i; var MapComponent = function (_Component) { inherits(MapComponent, _Component); function MapComponent(props, context) { classCallCheck(this, MapComponent); var _this = possibleConstructorReturn(this, _Component.call(this, props, context)); _this._leafletEvents = {}; return _this; } MapComponent.prototype.componentWillMount = function componentWillMount() { this._leafletEvents = this.extractLeafletEvents(this.props); }; MapComponent.prototype.componentDidMount = function componentDidMount() { this.bindLeafletEvents(this._leafletEvents); }; MapComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var next = this.extractLeafletEvents(nextProps); this._leafletEvents = this.bindLeafletEvents(next, this._leafletEvents); }; MapComponent.prototype.componentWillUnmount = function componentWillUnmount() { var el = this.leafletElement; if (!el) return; forEach(this._leafletEvents, function (cb, ev) { el.off(ev, cb); }); }; MapComponent.prototype.extractLeafletEvents = function extractLeafletEvents(props) { return reduce(keys(props), function (res, prop) { if (EVENTS_RE.test(prop)) { var _key = prop.replace(EVENTS_RE, function (match, p) { return p.toLowerCase(); }); if (props[prop] != null) { res[_key] = props[prop]; } } return res; }, {}); }; MapComponent.prototype.bindLeafletEvents = function bindLeafletEvents() { var next = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var prev = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var el = this.leafletElement; if (el == null || el.on == null) return {}; var diff = clone(prev); forEach(prev, function (cb, ev) { if (!next[ev] || cb !== next[ev]) { delete diff[ev]; el.off(ev, cb); } }); forEach(next, function (cb, ev) { if (!prev[ev] || cb !== prev[ev]) { diff[ev] = cb; el.on(ev, cb); } }); return diff; }; MapComponent.prototype.fireLeafletEvent = function fireLeafletEvent(type, data) { var el = this.leafletElement; if (el) el.fire(type, data); }; MapComponent.prototype.getOptions = function getOptions(props) { var pane = props.pane == null ? this.context.pane : props.pane; return pane ? _extends({}, props, { pane: pane }) : props; }; return MapComponent; }(React.Component); var MapLayer = function (_MapComponent) { inherits(MapLayer, _MapComponent); function MapLayer() { classCallCheck(this, MapLayer); return possibleConstructorReturn(this, _MapComponent.apply(this, arguments)); } // eslint-disable-next-line no-unused-vars MapLayer.prototype.createLeafletElement = function createLeafletElement(props) { throw new Error('createLeafletElement() must be implemented'); }; // eslint-disable-next-line no-unused-vars MapLayer.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) {}; MapLayer.prototype.componentWillMount = function componentWillMount() { _MapComponent.prototype.componentWillMount.call(this); this.leafletElement = this.createLeafletElement(this.props); }; MapLayer.prototype.componentDidMount = function componentDidMount() { _MapComponent.prototype.componentDidMount.call(this); this.layerContainer.addLayer(this.leafletElement); }; MapLayer.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { this.updateLeafletElement(prevProps, this.props); }; MapLayer.prototype.componentWillUnmount = function componentWillUnmount() { _MapComponent.prototype.componentWillUnmount.call(this); this.layerContainer.removeLayer(this.leafletElement); }; MapLayer.prototype.render = function render$$1() { var children$$1 = this.props.children; if (React.Children.count(children$$1) > 1) { return React__default.createElement( 'div', { style: { display: 'none' } }, children$$1 ); } return children$$1 == null ? null : children$$1; }; createClass(MapLayer, [{ key: 'layerContainer', get: function get$$1() { return this.context.layerContainer || this.context.map; } }]); return MapLayer; }(MapComponent); MapLayer.propTypes = { children: children }; MapLayer.contextTypes = { layerContainer: layerContainer, map: map, pane: propTypes.string }; var OPTIONS = ['stroke', 'color', 'weight', 'opacity', 'lineCap', 'lineJoin', 'dashArray', 'dashOffset', 'fill', 'fillColor', 'fillOpacity', 'fillRule', 'bubblingMouseEvents', 'renderer', 'className', // Interactive Layer 'interactive', // Layer 'pane', 'attribution']; var Path = function (_MapLayer) { inherits(Path, _MapLayer); function Path() { classCallCheck(this, Path); return possibleConstructorReturn(this, _MapLayer.apply(this, arguments)); } Path.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { _MapLayer.prototype.componentDidUpdate.call(this, prevProps); this.setStyleIfChanged(prevProps, this.props); }; Path.prototype.getChildContext = function getChildContext() { return { popupContainer: this.leafletElement }; }; Path.prototype.getPathOptions = function getPathOptions(props) { return pick(props, OPTIONS); }; Path.prototype.setStyle = function setStyle() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.leafletElement.setStyle(options); }; Path.prototype.setStyleIfChanged = function setStyleIfChanged(fromProps, toProps) { var nextStyle = this.getPathOptions(toProps); if (!isEqual(nextStyle, this.getPathOptions(fromProps))) { this.setStyle(nextStyle); } }; return Path; }(MapLayer); Path.childContextTypes = { children: children, popupContainer: layer }; var Circle$1 = function (_Path) { inherits(Circle$$1, _Path); function Circle$$1() { classCallCheck(this, Circle$$1); return possibleConstructorReturn(this, _Path.apply(this, arguments)); } Circle$$1.prototype.createLeafletElement = function createLeafletElement(props) { var center = props.center, radius = props.radius, options = objectWithoutProperties(props, ['center', 'radius']); return new leaflet.Circle(center, radius, this.getOptions(options)); }; Circle$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.center !== fromProps.center) { this.leafletElement.setLatLng(toProps.center); } if (toProps.radius !== fromProps.radius) { this.leafletElement.setRadius(toProps.radius); } }; return Circle$$1; }(Path); Circle$1.propTypes = { center: latlng.isRequired, children: children, radius: propTypes.number.isRequired }; var CircleMarker$1 = function (_Path) { inherits(CircleMarker$$1, _Path); function CircleMarker$$1() { classCallCheck(this, CircleMarker$$1); return possibleConstructorReturn(this, _Path.apply(this, arguments)); } CircleMarker$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.CircleMarker(props.center, this.getOptions(props)); }; CircleMarker$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.center !== fromProps.center) { this.leafletElement.setLatLng(toProps.center); } if (toProps.radius !== fromProps.radius) { this.leafletElement.setRadius(toProps.radius); } }; return CircleMarker$$1; }(Path); CircleMarker$1.propTypes = { center: latlng.isRequired, children: children, radius: propTypes.number }; var FeatureGroup$1 = function (_Path) { inherits(FeatureGroup$$1, _Path); function FeatureGroup$$1() { classCallCheck(this, FeatureGroup$$1); return possibleConstructorReturn(this, _Path.apply(this, arguments)); } FeatureGroup$$1.prototype.getChildContext = function getChildContext() { return { layerContainer: this.leafletElement, popupContainer: this.leafletElement }; }; FeatureGroup$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.FeatureGroup(this.getOptions(props)); }; FeatureGroup$$1.prototype.componentDidMount = function componentDidMount() { _Path.prototype.componentDidMount.call(this); this.setStyle(this.props); }; return FeatureGroup$$1; }(Path); FeatureGroup$1.childContextTypes = { children: children, layerContainer: layerContainer, popupContainer: layer }; var GeoJSON$1 = function (_Path) { inherits(GeoJSON$$1, _Path); function GeoJSON$$1() { classCallCheck(this, GeoJSON$$1); return possibleConstructorReturn(this, _Path.apply(this, arguments)); } GeoJSON$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.GeoJSON(props.data, this.getOptions(props)); }; GeoJSON$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (isFunction(toProps.style)) { this.setStyle(toProps.style); } else { this.setStyleIfChanged(fromProps, toProps); } }; return GeoJSON$$1; }(Path); GeoJSON$1.propTypes = { children: children, data: propTypes.oneOfType([propTypes.array, propTypes.object]).isRequired }; var GridLayer$1 = function (_MapLayer) { inherits(GridLayer$$1, _MapLayer); function GridLayer$$1() { classCallCheck(this, GridLayer$$1); return possibleConstructorReturn(this, _MapLayer.apply(this, arguments)); } GridLayer$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.GridLayer(this.getOptions(props)); }; GridLayer$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { var opacity = toProps.opacity, zIndex = toProps.zIndex; if (opacity !== fromProps.opacity) { this.leafletElement.setOpacity(opacity); } if (zIndex !== fromProps.zIndex) { this.leafletElement.setZIndex(zIndex); } }; GridLayer$$1.prototype.render = function render$$1() { return null; }; return GridLayer$$1; }(MapLayer); GridLayer$1.propTypes = { children: children, opacity: propTypes.number, zIndex: propTypes.number }; var ImageOverlay$1 = function (_MapLayer) { inherits(ImageOverlay$$1, _MapLayer); function ImageOverlay$$1() { classCallCheck(this, ImageOverlay$$1); return possibleConstructorReturn(this, _MapLayer.apply(this, arguments)); } ImageOverlay$$1.prototype.getChildContext = function getChildContext() { return { popupContainer: this.leafletElement }; }; ImageOverlay$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.ImageOverlay(props.url, props.bounds, this.getOptions(props)); }; ImageOverlay$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.url !== fromProps.url) { this.leafletElement.setUrl(toProps.url); } if (toProps.bounds !== fromProps.bounds) { this.leafletElement.setBounds(leaflet.latLngBounds(toProps.bounds)); } if (toProps.opacity !== fromProps.opacity) { this.leafletElement.setOpacity(toProps.opacity); } if (toProps.zIndex !== fromProps.zIndex) { this.leafletElement.setZIndex(toProps.zIndex); } }; return ImageOverlay$$1; }(MapLayer); ImageOverlay$1.propTypes = { attribution: propTypes.string, bounds: bounds.isRequired, children: children, opacity: propTypes.number, url: propTypes.string.isRequired, zIndex: propTypes.number }; ImageOverlay$1.childContextTypes = { popupContainer: layer }; var LayerGroup$1 = function (_MapLayer) { inherits(LayerGroup$$1, _MapLayer); function LayerGroup$$1() { classCallCheck(this, LayerGroup$$1); return possibleConstructorReturn(this, _MapLayer.apply(this, arguments)); } LayerGroup$$1.prototype.getChildContext = function getChildContext() { return { layerContainer: this.leafletElement }; }; LayerGroup$$1.prototype.createLeafletElement = function createLeafletElement() { return new leaflet.LayerGroup(this.getOptions(this.props)); }; return LayerGroup$$1; }(MapLayer); LayerGroup$1.childContextTypes = { layerContainer: layerContainer }; var baseControlledLayerPropTypes = { checked: propTypes.bool, children: propTypes.node.isRequired, removeLayer: propTypes.func, removeLayerControl: propTypes.func }; var controlledLayerPropTypes = _extends({}, baseControlledLayerPropTypes, { addBaseLayer: propTypes.func, addOverlay: propTypes.func, name: propTypes.string.isRequired }); // Abtract class for layer container, extended by BaseLayer and Overlay var ControlledLayer = function (_Component) { inherits(ControlledLayer, _Component); function ControlledLayer() { classCallCheck(this, ControlledLayer); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } ControlledLayer.prototype.getChildContext = function getChildContext() { return { layerContainer: { addLayer: this.addLayer.bind(this), removeLayer: this.removeLayer.bind(this) } }; }; ControlledLayer.prototype.componentWillReceiveProps = function componentWillReceiveProps(_ref) { var checked = _ref.checked; // Handle dynamically (un)checking the layer => adding/removing from the map if (checked === true && (this.props.checked == null || this.props.checked === false)) { this.context.map.addLayer(this.layer); } else if (this.props.checked === true && (checked == null || checked === false)) { this.context.map.removeLayer(this.layer); } }; ControlledLayer.prototype.componentWillUnmount = function componentWillUnmount() { this.props.removeLayerControl(this.layer); }; ControlledLayer.prototype.addLayer = function addLayer() { throw new Error('Must be implemented in extending class'); }; ControlledLayer.prototype.removeLayer = function removeLayer(layer) { this.props.removeLayer(layer); }; ControlledLayer.prototype.render = function render$$1() { return this.props.children || null; }; return ControlledLayer; }(React.Component); ControlledLayer.propTypes = baseControlledLayerPropTypes; ControlledLayer.contextTypes = { map: map }; ControlledLayer.childContextTypes = { layerContainer: layerContainer }; var BaseLayer = function (_ControlledLayer) { inherits(BaseLayer, _ControlledLayer); function BaseLayer() { classCallCheck(this, BaseLayer); return possibleConstructorReturn(this, _ControlledLayer.apply(this, arguments)); } BaseLayer.prototype.addLayer = function addLayer(layer) { this.layer = layer; // Keep layer reference to handle dynamic changes of props var _props = this.props, addBaseLayer = _props.addBaseLayer, checked = _props.checked, name = _props.name; addBaseLayer(layer, name, checked); }; return BaseLayer; }(ControlledLayer); BaseLayer.propTypes = controlledLayerPropTypes; var Overlay = function (_ControlledLayer2) { inherits(Overlay, _ControlledLayer2); function Overlay() { classCallCheck(this, Overlay); return possibleConstructorReturn(this, _ControlledLayer2.apply(this, arguments)); } Overlay.prototype.addLayer = function addLayer(layer) { this.layer = layer; // Keep layer reference to handle dynamic changes of props var _props2 = this.props, addOverlay = _props2.addOverlay, checked = _props2.checked, name = _props2.name; addOverlay(layer, name, checked); }; return Overlay; }(ControlledLayer); Overlay.propTypes = controlledLayerPropTypes; var LayersControl = function (_MapControl) { inherits(LayersControl, _MapControl); function LayersControl() { classCallCheck(this, LayersControl); return possibleConstructorReturn(this, _MapControl.apply(this, arguments)); } LayersControl.prototype.createLeafletElement = function createLeafletElement(props) { var _children = props.children, options = objectWithoutProperties(props, ['children']); return new leaflet.Control.Layers(undefined, undefined, options); }; LayersControl.prototype.componentWillMount = function componentWillMount() { _MapControl.prototype.componentWillMount.call(this); this.controlProps = { addBaseLayer: this.addBaseLayer.bind(this), addOverlay: this.addOverlay.bind(this), removeLayer: this.removeLayer.bind(this), removeLayerControl: this.removeLayerControl.bind(this) }; }; LayersControl.prototype.componentWillUnmount = function componentWillUnmount() { var _this5 = this; setTimeout(function () { _MapControl.prototype.componentWillUnmount.call(_this5); }, 0); }; LayersControl.prototype.addBaseLayer = function addBaseLayer(layer, name) { var checked = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (checked) { this.context.map.addLayer(layer); } this.leafletElement.addBaseLayer(layer, name); }; LayersControl.prototype.addOverlay = function addOverlay(layer, name) { var checked = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (checked) { this.context.map.addLayer(layer); } this.leafletElement.addOverlay(layer, name); }; LayersControl.prototype.removeLayer = function removeLayer(layer) { this.context.map.removeLayer(layer); }; LayersControl.prototype.removeLayerControl = function removeLayerControl(layer) { this.leafletElement.removeLayer(layer); }; LayersControl.prototype.render = function render$$1() { var _this6 = this; var children$$1 = React.Children.map(this.props.children, function (child) { return child ? React.cloneElement(child, _this6.controlProps) : null; }); return React__default.createElement( 'div', { style: { display: 'none' } }, children$$1 ); }; return LayersControl; }(MapControl); LayersControl.propTypes = { baseLayers: propTypes.object, children: children, overlays: propTypes.object, position: controlPositionType }; LayersControl.contextTypes = { layerContainer: layerContainer, map: map }; LayersControl.BaseLayer = BaseLayer; LayersControl.Overlay = Overlay; /** * 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; } /** * 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; } /** * 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)); } /** * 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(path))]; } /** `Object#toString` result references. */ var objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype; var objectProto$15 = 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$13 = objectProto$15.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(value) || baseGetTag(value) != objectTag$4) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$13.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } /** * 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(value) ? undefined : value; } /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$3 = 1; var CLONE_FLAT_FLAG$1 = 2; var CLONE_SYMBOLS_FLAG$2 = 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$2, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * 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 OTHER_PROPS = ['children', 'className', 'id', 'style', 'useFlyTo', 'whenReady']; var normalizeCenter = function normalizeCenter(pos) { return Array.isArray(pos) ? [pos[0], pos[1]] : [pos.lat, pos.lon ? pos.lon : pos.lng]; }; var Map$3 = function (_MapComponent) { inherits(Map$$1, _MapComponent); function Map$$1(props, context) { classCallCheck(this, Map$$1); var _this = possibleConstructorReturn(this, _MapComponent.call(this, props, context)); _this.viewport = { center: undefined, zoom: undefined }; _this._updating = false; _this.onViewportChange = function () { var center = _this.leafletElement.getCenter(); _this.viewport = { center: center ? [center.lat, center.lng] : undefined, zoom: _this.leafletElement.getZoom() }; if (_this.props.onViewportChange && !_this._updating) { _this.props.onViewportChange(_this.viewport); } }; _this.onViewportChanged = function () { if (_this.props.onViewportChanged && !_this._updating) { _this.props.onViewportChanged(_this.viewport); } }; _this.bindContainer = function (container) { _this.container = container; }; _this.className = props.className; return _this; } Map$$1.prototype.getChildContext = function getChildContext() { return { layerContainer: this.leafletElement, map: this.leafletElement }; }; Map$$1.prototype.createLeafletElement = function createLeafletElement(props) { var viewport$$1 = props.viewport, options = objectWithoutProperties(props, ['viewport']); if (viewport$$1) { if (viewport$$1.center) { options.center = viewport$$1.center; } if (typeof viewport$$1.zoom === 'number') { options.zoom = viewport$$1.zoom; } } return new leaflet.Map(this.container, options); }; Map$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { this._updating = true; var animate = toProps.animate, bounds$$1 = toProps.bounds, boundsOptions = toProps.boundsOptions, center = toProps.center, className = toProps.className, maxBounds = toProps.maxBounds, useFlyTo = toProps.useFlyTo, viewport$$1 = toProps.viewport, zoom = toProps.zoom; if (className !== fromProps.className) { if (fromProps.className != null) { leaflet.DomUtil.removeClass(this.container, fromProps.className); } if (className != null) { leaflet.DomUtil.addClass(this.container, className); } } if (viewport$$1 && viewport$$1 !== fromProps.viewport) { var c = viewport$$1.center ? viewport$$1.center : center; var z = viewport$$1.zoom == null ? zoom : viewport$$1.zoom; if (useFlyTo === true) { this.leafletElement.flyTo(c, z, { animate: animate }); } else { this.leafletElement.setView(c, z, { animate: animate }); } } else if (center && this.shouldUpdateCenter(center, fromProps.center)) { if (useFlyTo === true) { this.leafletElement.flyTo(center, zoom, { animate: animate }); } else { this.leafletElement.setView(center, zoom, { animate: animate }); } } else if (typeof zoom === 'number' && zoom !== fromProps.zoom) { if (fromProps.zoom == null) { this.leafletElement.setView(center, zoom); } else { this.leafletElement.setZoom(zoom); } } if (maxBounds && this.shouldUpdateBounds(maxBounds, fromProps.maxBounds)) { this.leafletElement.setMaxBounds(maxBounds); } if (bounds$$1 && (this.shouldUpdateBounds(bounds$$1, fromProps.bounds) || boundsOptions !== fromProps.boundsOptions)) { if (useFlyTo === true) { this.leafletElement.flyToBounds(bounds$$1, boundsOptions); } else { this.leafletElement.fitBounds(bounds$$1, boundsOptions); } } this._updating = false; }; Map$$1.prototype.componentDidMount = function componentDidMount() { var props = omit(this.props, OTHER_PROPS); this.leafletElement = this.createLeafletElement(props); this.leafletElement.on('move', this.onViewportChange); this.leafletElement.on('moveend', this.onViewportChanged); if (!isUndefined(props.bounds)) { this.leafletElement.fitBounds(props.bounds, props.boundsOptions); } if (this.props.whenReady) { this.leafletElement.whenReady(this.props.whenReady); } _MapComponent.prototype.componentDidMount.call(this); this.forceUpdate(); // Re-render now that leafletElement is created }; Map$$1.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { this.updateLeafletElement(prevProps, this.props); }; Map$$1.prototype.componentWillUnmount = function componentWillUnmount() { _MapComponent.prototype.componentWillUnmount.call(this); this.leafletElement.off('move', this.onViewportChange); this.leafletElement.off('moveend', this.onViewportChanged); this.leafletElement.remove(); }; Map$$1.prototype.shouldUpdateCenter = function shouldUpdateCenter(next, prev) { if (!prev) return true; next = normalizeCenter(next); prev = normalizeCenter(prev); return next[0] !== prev[0] || next[1] !== prev[1]; }; Map$$1.prototype.shouldUpdateBounds = function shouldUpdateBounds(next, prev) { return prev ? !leaflet.latLngBounds(next).equals(leaflet.latLngBounds(prev)) : true; }; Map$$1.prototype.render = function render$$1() { var map$$1 = this.leafletElement; var children$$1 = map$$1 ? this.props.children : null; return React__default.createElement( 'div', { className: this.className, id: this.props.id, ref: this.bindContainer, style: this.props.style }, children$$1 ); }; return Map$$1; }(MapComponent); Map$3.propTypes = { animate: propTypes.bool, bounds: bounds, boundsOptions: propTypes.object, center: latlng, children: children, className: propTypes.string, id: propTypes.string, maxBounds: bounds, maxZoom: propTypes.number, minZoom: propTypes.number, style: propTypes.object, useFlyTo: propTypes.bool, viewport: viewport, whenReady: propTypes.func, zoom: propTypes.number }; Map$3.childContextTypes = { layerContainer: layerContainer, map: map }; var Marker$1 = function (_MapLayer) { inherits(Marker$$1, _MapLayer); function Marker$$1() { classCallCheck(this, Marker$$1); return possibleConstructorReturn(this, _MapLayer.apply(this, arguments)); } Marker$$1.prototype.getChildContext = function getChildContext() { return { popupContainer: this.leafletElement }; }; Marker$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.Marker(props.position, this.getOptions(props)); }; Marker$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.position !== fromProps.position) { this.leafletElement.setLatLng(toProps.position); } if (toProps.icon !== fromProps.icon) { this.leafletElement.setIcon(toProps.icon); } if (toProps.zIndexOffset !== fromProps.zIndexOffset) { this.leafletElement.setZIndexOffset(toProps.zIndexOffset); } if (toProps.opacity !== fromProps.opacity) { this.leafletElement.setOpacity(toProps.opacity); } if (toProps.draggable !== fromProps.draggable) { if (toProps.draggable === true) { this.leafletElement.dragging.enable(); } else { this.leafletElement.dragging.disable(); } } }; return Marker$$1; }(MapLayer); Marker$1.propTypes = { children: children, draggable: propTypes.bool, icon: propTypes.instanceOf(leaflet.Icon), opacity: propTypes.number, position: latlng.isRequired, zIndexOffset: propTypes.number }; Marker$1.childContextTypes = { popupContainer: layer }; /** Used to generate unique IDs. */ var idCounter = 0; /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /** * 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. */ /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var __DEV__ = "development" !== 'production'; var warning$2 = function() {}; if (__DEV__) { warning$2 = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // 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) {} } }; } var warning_1$2 = warning$2; // flowlint sketchy-null-string:off var LEAFLET_PANES = ['tile', 'shadow', 'overlay', 'map', 'marker', 'tooltip', 'popup']; var isLeafletPane = function isLeafletPane(name) { return LEAFLET_PANES.indexOf(name.replace(/-*pane/gi, '')) !== -1; }; var paneStyles = { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 }; var Pane = function (_Component) { inherits(Pane, _Component); function Pane() { var _temp, _this, _ret; classCallCheck(this, Pane); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { name: undefined }, _this.setStyle = function () { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.props, style = _ref.style, className = _ref.className; var pane = _this.getPane(_this.state.name); if (pane) { if (className) { pane.classList.add(className); } if (style) { forEach(style, function (value, key) { pane.style[key] = value; }); } } }, _temp), possibleConstructorReturn(_this, _ret); } Pane.prototype.getChildContext = function getChildContext() { return { pane: this.state.name }; }; Pane.prototype.componentDidMount = function componentDidMount() { this.createPane(this.props); }; Pane.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (!this.state.name) { // Do nothing if this.state.name is undefined due to errors or // an invalid props.name value return; } // If the 'name' prop has changed the current pane is unmounted and a new // pane is created. if (nextProps.name !== this.props.name) { this.removePane(); this.createPane(nextProps); } else { // Remove the previous css class name from the pane if it has changed. // setStyle will take care of adding in the updated className if (this.props.className && nextProps.className !== this.props.className) { var _pane = this.getPane(); if (_pane && this.props.className) _pane.classList.remove(this.props.className); } // Update the pane's DOM node style and class this.setStyle(nextProps); } }; Pane.prototype.componentWillUnmount = function componentWillUnmount() { this.removePane(); }; Pane.prototype.createPane = function createPane(props) { var map$$1 = this.context.map; var name = props.name || 'pane-' + uniqueId(); if (map$$1 && map$$1.createPane) { var isDefault = isLeafletPane(name); var existing = isDefault || this.getPane(name); if (!existing) { map$$1.createPane(name, this.getParentPane()); } else { var message = isDefault ? 'You must use a unique name for a pane that is not a default leaflet pane (' + name + ')' : 'A pane with this name already exists. (' + name + ')'; warning_1$2(false, message); } this.setState({ name: name }, this.setStyle); } }; Pane.prototype.removePane = function removePane() { // Remove the created pane var name = this.state.name; if (name) { var _pane2 = this.getPane(name); if (_pane2 && _pane2.remove) _pane2.remove(); var _map = this.context.map; if (_map && _map._panes) { _map._panes = omit(_map._panes, name); _map._paneRenderers = omit(_map._paneRenderers, name); } this.setState({ name: undefined }); } }; Pane.prototype.getParentPane = function getParentPane() { return this.getPane(this.props.pane || this.context.pane); }; Pane.prototype.getPane = function getPane(name) { return name ? this.context.map.getPane(name) : undefined; }; Pane.prototype.render = function render$$1() { return this.state.name ? React__default.createElement( 'div', { style: paneStyles }, this.props.children ) : null; }; return Pane; }(React.Component); Pane.propTypes = { name: propTypes.string, children: children, map: map, className: propTypes.string, style: propTypes.object, pane: propTypes.string }; Pane.contextTypes = { map: map, pane: propTypes.string }; Pane.childContextTypes = { pane: propTypes.string }; var multiLatLngList = propTypes.arrayOf(latlngList); var Polygon$1 = function (_Path) { inherits(Polygon$$1, _Path); function Polygon$$1() { classCallCheck(this, Polygon$$1); return possibleConstructorReturn(this, _Path.apply(this, arguments)); } Polygon$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.Polygon(props.positions, this.getOptions(props)); }; Polygon$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.positions !== fromProps.positions) { this.leafletElement.setLatLngs(toProps.positions); } this.setStyleIfChanged(fromProps, toProps); }; return Polygon$$1; }(Path); Polygon$1.propTypes = { children: children, positions: propTypes.oneOfType([latlngList, multiLatLngList, propTypes.arrayOf(multiLatLngList)]).isRequired }; var Polyline$1 = function (_Path) { inherits(Polyline$$1, _Path); function Polyline$$1() { classCallCheck(this, Polyline$$1); return possibleConstructorReturn(this, _Path.apply(this, arguments)); } Polyline$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.Polyline(props.positions, this.getOptions(props)); }; Polyline$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.positions !== fromProps.positions) { this.leafletElement.setLatLngs(toProps.positions); } this.setStyleIfChanged(fromProps, toProps); }; return Polyline$$1; }(Path); Polyline$1.propTypes = { children: children, positions: propTypes.oneOfType([latlngList, propTypes.arrayOf(latlngList)]).isRequired }; var Popup$1 = function (_MapComponent) { inherits(Popup$$1, _MapComponent); function Popup$$1() { var _temp, _this, _ret; classCallCheck(this, Popup$$1); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _MapComponent.call.apply(_MapComponent, [this].concat(args))), _this), _this.onPopupOpen = function (_ref) { var popup = _ref.popup; if (popup === _this.leafletElement) { _this.renderPopupContent(); if (_this.props.onOpen) { _this.props.onOpen(); } } }, _this.onPopupClose = function (_ref2) { var popup = _ref2.popup; if (popup === _this.leafletElement) { _this.removePopupContent(); if (_this.props.onClose) { _this.props.onClose(); } } }, _this.renderPopupContent = function () { if (_this.props.children == null) { _this.removePopupContent(); } else { reactDom.render(React.Children.only(_this.props.children), _this.leafletElement._contentNode); _this.leafletElement.update(); if (_this.props.autoPan !== false) { if (_this.leafletElement._map && _this.leafletElement._map._panAnim) { _this.leafletElement._map._panAnim = undefined; } _this.leafletElement._adjustPan(); } } }, _this.removePopupContent = function () { if (_this.leafletElement._contentNode) { reactDom.unmountComponentAtNode(_this.leafletElement._contentNode); } }, _temp), possibleConstructorReturn(_this, _ret); } Popup$$1.prototype.getOptions = function getOptions(props) { return _extends({}, _MapComponent.prototype.getOptions.call(this, props), { autoPan: false }); }; Popup$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.Popup(this.getOptions(props), this.context.popupContainer); }; Popup$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.position !== fromProps.position) { this.leafletElement.setLatLng(toProps.position); } }; Popup$$1.prototype.componentWillMount = function componentWillMount() { _MapComponent.prototype.componentWillMount.call(this); this.leafletElement = this.createLeafletElement(this.props); this.leafletElement.options.autoPan = this.props.autoPan !== false; this.context.map.on({ popupopen: this.onPopupOpen, popupclose: this.onPopupClose }); }; Popup$$1.prototype.componentDidMount = function componentDidMount() { var position = this.props.position; var _context = this.context, map$$1 = _context.map, popupContainer = _context.popupContainer; var el = this.leafletElement; if (popupContainer) { // Attach to container component popupContainer.bindPopup(el); } else { // Attach to a Map if (position) { el.setLatLng(position); } el.openOn(map$$1); } }; Popup$$1.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { this.updateLeafletElement(prevProps, this.props); if (this.leafletElement.isOpen()) { this.renderPopupContent(); } }; Popup$$1.prototype.componentWillUnmount = function componentWillUnmount() { this.removePopupContent(); this.context.map.off({ popupopen: this.onPopupOpen, popupclose: this.onPopupClose }); this.context.map.removeLayer(this.leafletElement); _MapComponent.prototype.componentWillUnmount.call(this); }; Popup$$1.prototype.render = function render$$1() { return null; }; return Popup$$1; }(MapComponent); Popup$1.propTypes = { children: propTypes.node, onClose: propTypes.func, onOpen: propTypes.func, position: latlng }; Popup$1.contextTypes = { map: map, popupContainer: layer, pane: propTypes.string }; Popup$1.defaultProps = { pane: 'popupPane' }; var Rectangle$1 = function (_Path) { inherits(Rectangle$$1, _Path); function Rectangle$$1() { classCallCheck(this, Rectangle$$1); return possibleConstructorReturn(this, _Path.apply(this, arguments)); } Rectangle$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.Rectangle(props.bounds, this.getOptions(props)); }; Rectangle$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.bounds !== fromProps.bounds) { this.leafletElement.setBounds(toProps.bounds); } this.setStyleIfChanged(fromProps, toProps); }; return Rectangle$$1; }(Path); Rectangle$1.propTypes = { children: children, bounds: bounds.isRequired }; var ScaleControl = function (_MapControl) { inherits(ScaleControl, _MapControl); function ScaleControl() { classCallCheck(this, ScaleControl); return possibleConstructorReturn(this, _MapControl.apply(this, arguments)); } ScaleControl.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.Control.Scale(props); }; return ScaleControl; }(MapControl); ScaleControl.propTypes = { imperial: propTypes.bool, maxWidth: propTypes.number, metric: propTypes.bool, position: controlPositionType, updateWhenIdle: propTypes.bool }; var TileLayer$1 = function (_GridLayer) { inherits(TileLayer$$1, _GridLayer); function TileLayer$$1() { classCallCheck(this, TileLayer$$1); return possibleConstructorReturn(this, _GridLayer.apply(this, arguments)); } TileLayer$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.TileLayer(props.url, this.getOptions(props)); }; TileLayer$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { _GridLayer.prototype.updateLeafletElement.call(this, fromProps, toProps); if (toProps.url !== fromProps.url) { this.leafletElement.setUrl(toProps.url); } }; return TileLayer$$1; }(GridLayer$1); TileLayer$1.propTypes = { children: children, opacity: propTypes.number, url: propTypes.string.isRequired, zIndex: propTypes.number }; var Tooltip$1 = function (_MapComponent) { inherits(Tooltip$$1, _MapComponent); function Tooltip$$1() { var _temp, _this, _ret; classCallCheck(this, Tooltip$$1); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _MapComponent.call.apply(_MapComponent, [this].concat(args))), _this), _this.onTooltipOpen = function (_ref) { var tooltip = _ref.tooltip; if (tooltip === _this.leafletElement) { _this.renderTooltipContent(); if (_this.props.onOpen) { _this.props.onOpen(); } } }, _this.onTooltipClose = function (_ref2) { var tooltip = _ref2.tooltip; if (tooltip === _this.leafletElement) { _this.removeTooltipContent(); if (_this.props.onClose) { _this.props.onClose(); } } }, _this.renderTooltipContent = function () { if (_this.props.children == null) { _this.removeTooltipContent(); } else { reactDom.render(React.Children.only(_this.props.children), _this.leafletElement._contentNode); _this.leafletElement.update(); } }, _this.removeTooltipContent = function () { if (_this.leafletElement._contentNode) { reactDom.unmountComponentAtNode(_this.leafletElement._contentNode); } }, _temp), possibleConstructorReturn(_this, _ret); } Tooltip$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.Tooltip(this.getOptions(props), this.context.popupContainer); }; Tooltip$$1.prototype.componentWillMount = function componentWillMount() { _MapComponent.prototype.componentWillMount.call(this); this.leafletElement = this.createLeafletElement(this.props); this.context.popupContainer.on({ tooltipopen: this.onTooltipOpen, tooltipclose: this.onTooltipClose }); }; Tooltip$$1.prototype.componentDidMount = function componentDidMount() { this.context.popupContainer.bindTooltip(this.leafletElement); }; Tooltip$$1.prototype.componentDidUpdate = function componentDidUpdate() { if (this.leafletElement.isOpen()) { this.renderTooltipContent(); } }; Tooltip$$1.prototype.componentWillUnmount = function componentWillUnmount() { var popupContainer = this.context.popupContainer; this.removeTooltipContent(); popupContainer.off({ tooltipopen: this.onTooltipOpen, tooltipclose: this.onTooltipClose }); popupContainer.unbindTooltip(this.leafletElement); _MapComponent.prototype.componentWillUnmount.call(this); }; Tooltip$$1.prototype.render = function render$$1() { return null; }; return Tooltip$$1; }(MapComponent); Tooltip$1.propTypes = { children: propTypes.node, onClose: propTypes.func, onOpen: propTypes.func }; Tooltip$1.contextTypes = { map: map, popupContainer: layer, pane: propTypes.string }; Tooltip$1.defaultProps = { pane: 'tooltipPane' }; var VideoOverlay$1 = function (_MapLayer) { inherits(VideoOverlay$$1, _MapLayer); function VideoOverlay$$1() { classCallCheck(this, VideoOverlay$$1); return possibleConstructorReturn(this, _MapLayer.apply(this, arguments)); } VideoOverlay$$1.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.VideoOverlay(props.url, props.bounds, this.getOptions(props)); }; VideoOverlay$$1.prototype.componentDidMount = function componentDidMount() { _MapLayer.prototype.componentDidMount.call(this); if (this.props.play === true) { this.leafletElement.getElement().play(); } }; VideoOverlay$$1.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { if (toProps.url !== fromProps.url) { this.leafletElement.setUrl(toProps.url); } if (toProps.bounds !== fromProps.bounds) { this.leafletElement.setBounds(leaflet.latLngBounds(toProps.bounds)); } if (toProps.opacity !== fromProps.opacity) { this.leafletElement.setOpacity(toProps.opacity); } if (toProps.zIndex !== fromProps.zIndex) { this.leafletElement.setZIndex(toProps.zIndex); } // flowlint-next-line sketchy-null-bool:off if (toProps.play === true && !fromProps.play) { this.leafletElement.getElement().play(); // flowlint-next-line sketchy-null-bool:off } else if (!toProps.play && fromProps.play === true) { this.leafletElement.getElement().pause(); } }; return VideoOverlay$$1; }(MapLayer); VideoOverlay$1.propTypes = { attribution: propTypes.string, bounds: bounds.isRequired, opacity: propTypes.number, play: propTypes.bool, url: propTypes.oneOfType([propTypes.string, propTypes.arrayOf(propTypes.string), propTypes.instanceOf(HTMLVideoElement)]).isRequired, zIndex: propTypes.number }; var WMSTileLayer = function (_GridLayer) { inherits(WMSTileLayer, _GridLayer); function WMSTileLayer() { classCallCheck(this, WMSTileLayer); return possibleConstructorReturn(this, _GridLayer.apply(this, arguments)); } WMSTileLayer.prototype.createLeafletElement = function createLeafletElement(props) { var url = props.url, params = objectWithoutProperties(props, ['url']); return new leaflet.TileLayer.WMS(url, this.getOptions(params)); }; WMSTileLayer.prototype.updateLeafletElement = function updateLeafletElement(fromProps, toProps) { _GridLayer.prototype.updateLeafletElement.call(this, fromProps, toProps); var prevUrl = fromProps.url, _po = fromProps.opacity, _pz = fromProps.zIndex, prevParams = objectWithoutProperties(fromProps, ['url', 'opacity', 'zIndex']); var url = toProps.url, _o = toProps.opacity, _z = toProps.zIndex, params = objectWithoutProperties(toProps, ['url', 'opacity', 'zIndex']); if (url !== prevUrl) { this.leafletElement.setUrl(url); } if (!isEqual(params, prevParams)) { this.leafletElement.setParams(params); } }; WMSTileLayer.prototype.getOptions = function getOptions(params) { return reduce(_GridLayer.prototype.getOptions.call(this, params), function (options, value, key) { if (!EVENTS_RE.test(key)) { options[key] = value; } return options; }, {}); }; return WMSTileLayer; }(GridLayer$1); WMSTileLayer.propTypes = { children: children, opacity: propTypes.number, url: propTypes.string.isRequired, zIndex: propTypes.number }; var ZoomControl = function (_MapControl) { inherits(ZoomControl, _MapControl); function ZoomControl() { classCallCheck(this, ZoomControl); return possibleConstructorReturn(this, _MapControl.apply(this, arguments)); } ZoomControl.prototype.createLeafletElement = function createLeafletElement(props) { return new leaflet.Control.Zoom(props); }; return ZoomControl; }(MapControl); ZoomControl.propTypes = { position: controlPositionType, zoomInText: propTypes.string, zoomInTitle: propTypes.string, zoomOutText: propTypes.string, zoomOutTitle: propTypes.string }; exports.PropTypes = index; exports.AttributionControl = AttributionControl; exports.Circle = Circle$1; exports.CircleMarker = CircleMarker$1; exports.FeatureGroup = FeatureGroup$1; exports.GeoJSON = GeoJSON$1; exports.GridLayer = GridLayer$1; exports.ImageOverlay = ImageOverlay$1; exports.LayerGroup = LayerGroup$1; exports.LayersControl = LayersControl; exports.Map = Map$3; exports.MapComponent = MapComponent; exports.MapControl = MapControl; exports.MapLayer = MapLayer; exports.Marker = Marker$1; exports.Pane = Pane; exports.Path = Path; exports.Polygon = Polygon$1; exports.Polyline = Polyline$1; exports.Popup = Popup$1; exports.Rectangle = Rectangle$1; exports.ScaleControl = ScaleControl; exports.TileLayer = TileLayer$1; exports.Tooltip = Tooltip$1; exports.VideoOverlay = VideoOverlay$1; exports.WMSTileLayer = WMSTileLayer; exports.ZoomControl = ZoomControl; Object.defineProperty(exports, '__esModule', { value: true }); })));
var os = require('os') , fs = require('fs') , path = require('path') , spawn = require('child_process').spawn var mkdirp = require('mkdirp') var phantomscript = path.join(__dirname, 'phantomscript.js') module.exports = { process: processMermaid } function processMermaid(files, _options, _next) { var options = _options || {} , outputDir = options.outputDir || process.cwd() , next = _next || function() {} , phantomArgs = [ phantomscript , outputDir , options.png , options.svg , options.css || '' , options.sequenceConfig , options.ganttConfig , options.verbose ] files.forEach(function(file) { phantomArgs.push(file) }) mkdirp(outputDir, function(err) { if (err) { throw err return } phantom = spawn(options.phantomPath, phantomArgs) phantom.on('exit', next) phantom.stderr.pipe(process.stderr) phantom.stdout.pipe(process.stdout) }) }
/* jquery.LavaLamp v1.4 http://nixbox.com/projects/jquery-lavalamp/ Copyright (c) 2008-2012 Jolyon Terwilliger - jolyon@nixbox.com Dual licensed under the MIT and GPL licenses: http://www.opensource.org/licenses/mit-license.php http://www.gnu.org/licenses/gpl.html */ (function(c){jQuery.fn.lavaLamp=function(a){function d(a){a=parseInt(a);return isNaN(a)?0:a}a=c.extend({target:"li",container:"",fx:"swing",speed:500,click:function(){return!0},startItem:"",includeMargins:!1,autoReturn:!0,returnDelay:0,setOnClick:!0,homeTop:0,homeLeft:0,homeWidth:0,homeHeight:0,returnHome:!1,autoResize:!1,selectClass:"selectedLava",homeClass:"homeLava",skipClass:"noLava",returnStart:function(){},returnFinish:function(){},hoverStart:function(){},hoverFinish:function(){}},a||{});""== a.container&&(a.container=a.target);a.autoResize&&c(window).resize(function(){c(a.target+"."+a.selectClass).trigger("mouseenter")});return this.each(function(){function k(e,c){c=="return"?a.returnStart(e):a.hoverStart(e);e||(e=b);if(!a.includeMargins){h=d(e.css("marginLeft"));i=d(e.css("marginTop"))}var g={left:e.position().left+h,top:e.position().top+i,width:e.outerWidth()-l,height:e.outerHeight()-m};f.stop().animate(g,a.speed,a.fx,function(){c=="return"?a.returnFinish(e):a.hoverFinish(e)})}c(this).css("position")== "static"&&c(this).css("position","relative");if(a.homeTop||a.homeLeft){var n=c("<"+a.container+' class="'+a.homeClass+'"></'+a.container+">").css({left:a.homeLeft,top:a.homeTop,width:a.homeWidth,height:a.homeHeight,position:"absolute",display:"block"});c(this).prepend(n)}var s=location.pathname+location.search+location.hash,b,f,j=c(a.target,this).not("."+a.skipClass),g,l=0,m=0,p=0,q=0,h=0,i=0;b=c(a.target+"."+a.selectClass,this);a.startItem!=""&&(b=j.eq(a.startItem));if((a.homeTop||a.homeLeft)&&b.length< 1)b=n;if(b.length<1){var o=0,r;j.each(function(){var a=c("a:first",this).attr("href");if(s.indexOf(a)>-1&&a.length>o){r=c(this);o=a.length}});o>0&&(b=r)}b.length<1&&(b=j.eq(0));b=c(b.eq(0).addClass(a.selectClass));j.bind("mouseenter focusin",function(){if(g){clearTimeout(g);g=null}k(c(this))}).click(function(e){if(a.setOnClick){b.removeClass(a.selectClass);b=c(this).addClass(a.selectClass)}return a.click.apply(this,[e,this])});f=c("<"+a.container+' class="backLava"><div class="leftLava"></div><div class="bottomLava"></div><div class="cornerLava"></div></'+ a.container+">").css({position:"absolute",display:"block",margin:0,padding:0}).prependTo(this);if(a.includeMargins){p=d(b.css("marginTop"))+d(b.css("marginBottom"));q=d(b.css("marginLeft"))+d(b.css("marginRight"))}l=d(f.css("borderLeftWidth"))+d(f.css("borderRightWidth"))+d(f.css("paddingLeft"))+d(f.css("paddingRight"))-q;m=d(f.css("borderTopWidth"))+d(f.css("borderBottomWidth"))+d(f.css("paddingTop"))+d(f.css("paddingBottom"))-p;if(a.homeTop||a.homeLeft)f.css({left:a.homeLeft,top:a.homeTop,width:a.homeWidth, height:a.homeHeight});else{if(!a.includeMargins){h=d(b.css("marginLeft"));i=d(b.css("marginTop"))}f.css({left:b.position().left+h,top:b.position().top+i,width:b.outerWidth()-l,height:b.outerHeight()-m})}c(this).bind("mouseleave focusout",function(){var b=null;if(a.returnHome)b=n;else if(!a.autoReturn)return true;if(a.returnDelay){g&&clearTimeout(g);g=setTimeout(function(){k(b,"return")},a.returnDelay)}else k(b,"return");return true})})}})(jQuery);
YUI.add('history-hash-ie', function (Y, NAME) { /** * Improves IE6/7 support in history-hash by using a hidden iframe to create * entries in IE's browser history. This module is only needed if IE6/7 support * is necessary; it's not needed for any other browser. * * @module history * @submodule history-hash-ie * @since 3.2.0 */ // Combination of a UA sniff to ensure this is IE (or a browser that wants us to // treat it like IE) and feature detection for native hashchange support (false // for IE < 8 or IE8/9 in IE7 mode). if (Y.UA.ie && !Y.HistoryBase.nativeHashChange) { var Do = Y.Do, GlobalEnv = YUI.namespace('Env.HistoryHash'), HistoryHash = Y.HistoryHash, iframe = GlobalEnv._iframe, win = Y.config.win; /** * Gets the raw (not decoded) current location hash from the IE iframe, * minus the preceding '#' character and the hashPrefix (if one is set). * * @method getIframeHash * @return {String} current iframe hash * @static */ HistoryHash.getIframeHash = function () { if (!iframe || !iframe.contentWindow) { return ''; } var prefix = HistoryHash.hashPrefix, hash = iframe.contentWindow.location.hash.substr(1); return prefix && hash.indexOf(prefix) === 0 ? hash.replace(prefix, '') : hash; }; /** * Updates the history iframe with the specified hash. * * @method _updateIframe * @param {String} hash location hash * @param {Boolean} replace (optional) if <code>true</code>, the current * history state will be replaced without adding a new history entry * @protected * @static * @for HistoryHash */ HistoryHash._updateIframe = function (hash, replace) { var iframeDoc = iframe && iframe.contentWindow && iframe.contentWindow.document, iframeLocation = iframeDoc && iframeDoc.location; if (!iframeDoc || !iframeLocation) { return; } Y.log('updating history iframe: ' + hash + ', replace: ' + !!replace, 'info', 'history'); if (replace) { iframeLocation.replace(hash.charAt(0) === '#' ? hash : '#' + hash); } else { iframeDoc.open().close(); iframeLocation.hash = hash; } }; Do.before(HistoryHash._updateIframe, HistoryHash, 'replaceHash', HistoryHash, true); if (!iframe) { Y.on('domready', function () { var lastUrlHash = HistoryHash.getHash(); // Create a hidden iframe to store history state, following the // iframe-hiding recommendations from // http://www.paciellogroup.com/blog/?p=604. // // This iframe will allow history navigation within the current page // context. After navigating to another page, all but the most // recent history state will be lost. // // Earlier versions of the YUI History Utility attempted to work // around this limitation by having the iframe load a static // resource. This workaround was extremely fragile and tended to // break frequently (and silently) since it was entirely dependent // on IE's inconsistent handling of iframe history. // // Since this workaround didn't work much of the time anyway and // added significant complexity, it has been removed, and IE6 and 7 // now get slightly degraded history support. Y.log('creating dynamic history iframe', 'info', 'history'); iframe = GlobalEnv._iframe = Y.Node.getDOMNode(Y.Node.create( '<iframe src="javascript:0" style="display:none" height="0" width="0" tabindex="-1" title="empty"/>' )); // Append the iframe to the documentElement rather than the body. // Keeping it outside the body prevents scrolling on the initial // page load (hat tip to Ben Alman and jQuery BBQ for this // technique). Y.config.doc.documentElement.appendChild(iframe); // Update the iframe with the initial location hash, if any. This // will create an initial history entry that the user can return to // after the state has changed. HistoryHash._updateIframe(lastUrlHash || '#'); // Listen for hashchange events and keep the iframe's hash in sync // with the parent frame's hash. Y.on('hashchange', function (e) { lastUrlHash = e.newHash; if (HistoryHash.getIframeHash() !== lastUrlHash) { Y.log('updating iframe hash to match URL hash', 'info', 'history'); HistoryHash._updateIframe(lastUrlHash); } }, win); // Watch the iframe hash in order to detect back/forward navigation. Y.later(50, null, function () { var iframeHash = HistoryHash.getIframeHash(); if (iframeHash !== lastUrlHash) { Y.log('updating URL hash to match iframe hash', 'info', 'history'); HistoryHash.setHash(iframeHash); } }, null, true); }); } } }, '3.18.1', {"requires": ["history-hash", "node-base"]});
/* flatpickr v4.0.2, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.pt = {}))); }(this, (function (exports) { 'use strict'; var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {}, }; var Portuguese = { weekdays: { shorthand: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"], longhand: [ "Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado", ], }, months: { shorthand: [ "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez", ], longhand: [ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro", ], }, rangeSeparator: " até ", }; fp.l10ns.pt = Portuguese; var pt = fp.l10ns; exports.Portuguese = Portuguese; exports['default'] = pt; Object.defineProperty(exports, '__esModule', { value: true }); })));
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ var TAG_SPRITE = 1; var ClickAndMoveTestScene = TestScene.extend({ runThisTest:function () { var layer = new MainLayer(); this.addChild(layer); director.replaceScene(this); } }); var MainLayer = cc.Layer.extend({ ctor:function () { this._super(); this.init(); if( 'touches' in sys.capabilities ) this.setTouchEnabled(true); else if ('mouse' in sys.capabilities ) this.setMouseEnabled(true); var sprite = cc.Sprite.create(s_pathGrossini); var layer = cc.LayerColor.create(cc.c4b(255, 255, 0, 100)); this.addChild(layer, -1); this.addChild(sprite, 0, TAG_SPRITE); sprite.setPosition(20, 150); sprite.runAction(cc.JumpTo.create(4, cc.p(300, 48), 100, 4)); var fadeIn = cc.FadeIn.create(1); var fadeOut = cc.FadeOut.create(1); var forever = cc.RepeatForever.create(cc.Sequence.create(fadeIn, fadeOut)); layer.runAction(forever); }, moveSprite:function(position) { var sprite = this.getChildByTag(TAG_SPRITE); sprite.stopAllActions(); sprite.runAction(cc.MoveTo.create(1, position)); var current = sprite.getPosition(); var o = position.x - current.x; var a = position.y - current.y; var at = Math.atan(o / a) * 57.29577951; // radians to degrees if (a < 0) { if (o < 0) at = 180 + Math.abs(at); else at = 180 - Math.abs(at); } sprite.runAction(cc.RotateTo.create(1, at)); }, onMouseUp:function (event) { var location = event.getLocation(); this.moveSprite(location); }, onTouchesEnded:function (touches, event) { if (touches.length <= 0) return; var touch = touches[0]; var location = touch.getLocation(); this.moveSprite(location); } });
var Checker = require('../../../lib/checker'); var expect = require('chai').expect; describe('rules/validate-comment-position', function() { var checker; beforeEach(function() { checker = new Checker(); checker.registerDefaultRules(); }); it('accepts valid position', function() { var validPositions = [ 'above', 'beside' ]; validPositions.forEach(function(position) { expect(function() { checker.configure({ validateCommentPosition: { position: position }}); }).to.not.throw(); }); }); it('rejects invalid position', function() { var invalidPositions = [ 'beneath', 'under', 'perpendicular', true ]; invalidPositions.forEach(function(position) { expect(function() { checker.configure({ validateCommentPosition: { position: position }}); }).to.throw('AssertionError'); }); }); it('accepts valid exceptions', function() { expect(function() { checker.configure({ validateCommentPosition: { position: 'above', allExcept: ['pragma', 'linter'] }}); }).to.not.throw(); }); it('rejects invalid exceptions', function() { var invalidExceptions = [ [1, 2, 3], ['linter', 1, true] ]; invalidExceptions.forEach(function(exception) { expect(function() { checker.configure({ validateCommentPosition: { position: 'above', allExcept: exception }}); }).to.throw('AssertionError'); }); }); it('should not accept non-objects', function() { expect(function() { checker.configure({ validateCommentPosition: 'true' }); }).to.throw('AssertionError'); }); describe('position value "above"', function() { beforeEach(function() { checker.configure({ validateCommentPosition: { position: 'above' }}); }); it('should report on a comment beside a statement', function() { expect(checker.checkString('1 + 1; // invalid comment')) .to.have.one.validation.error.from('validateCommentPosition'); }); it('should not report on a comment above a statement', function() { expect(checker.checkString('// valid comment\n1 + 1;')).to.have.no.errors(); }); it('should not report on block comments above a statement', function() { expect(checker.checkString('/* block comments are skipped */\n1 + 1;')).to.have.no.errors(); }); it('should not report on block comments beside a statement', function() { expect(checker.checkString('1 + 1; /* block comments are skipped */')).to.have.no.errors(); }); it('should not report on eslint inline configurations', function() { expect(checker.checkString('1 + 1; /* eslint eqeqeq */')).to.have.no.errors(); }); it('should not report on eslint-disable pragma', function() { expect(checker.checkString('1 + 1; /* eslint-disable */')).to.have.no.errors(); }); it('should not report on eslint-enable pragma', function() { expect(checker.checkString('1 + 1; /* eslint-enable */')).to.have.no.errors(); }); it('should not report eslint-disable-line pragma', function() { expect(checker.checkString('1 + 1; // eslint-disable-line')).to.have.no.errors(); }); it('should not report on excepted global variables (eslint)', function() { expect(checker.checkString('1 + 1; /* global MY_GLOBAL, ANOTHER */')).to.have.no.errors(); }); it('should not report on jshint compatible jslint options', function() { expect(checker.checkString('1 + 1; /* jslint vars: true */')).to.have.no.errors(); }); it('should not report on excepted global variables (jshint)', function() { expect(checker.checkString('1 + 1; /* globals MY_GLOBAL: true */')).to.have.no.errors(); }); it('should not report on jshint `exported` directives', function() { expect(checker.checkString('1 + 1; /* exported MY_GLOBAL, ANOTHER */')).to.have.no.errors(); }); it('should not report on jshint `falls through` directives', function() { expect(checker.checkString('1 + 1; /* falls through */')).to.have.no.errors(); }); it('should report on comments beginning with words made up of partial keywords', function() { expect(checker.checkString('1 + 1; // globalization is a word')) .to.have.one.validation.error.from('validateCommentPosition'); }); it('should report on comments that mention keywords, but are not valid pragmas', function() { expect(checker.checkString('1 + 1; // mentioning falls through')) .to.have.one.validation.error.from('validateCommentPosition'); }); it('should not report on jshint line comment directives', function() { expect(checker.checkString('1 + 1; // jshint ignore:line')).to.have.no.errors(); }); it('should not report on istanbul pragmas', function() { expect(checker.checkString('1 + 1; /* istanbul ignore next */')).to.have.no.errors(); }); }); describe('position value "above" with exceptions', function() { beforeEach(function() { checker.configure({ validateCommentPosition: { position: 'above', allExcept: ['pragma', 'linter'] }}); }); it('should not report on comments that start with excepted keywords', function() { expect(checker.checkString('1 + 1; // linter excepted comment')).to.have.no.errors(); }); it('should still report on comments beside statements after skipping excepted comments', function() { expect(checker.checkString('1 + 1; // linter\n2 + 2; // invalid comment')) .to.have.one.validation.error.from('validateCommentPosition'); }); }); describe('position value "beside"', function() { beforeEach(function() { checker.configure({ validateCommentPosition: { position: 'beside' }}); }); it('should report on comments above statements', function() { expect(checker.checkString('// invalid comment\n1 + 1;')) .to.have.one.validation.error.from('validateCommentPosition'); }); it('should not report on comments beside statements', function() { expect(checker.checkString('1 + 1; // valid comment')).to.have.no.errors(); }); it('should not report on inline jscs disable rules', function() { expect(checker.checkString('// jscs: disable\n1 + 1;')).to.have.no.errors(); }); it('should not report on jscs enable rules', function() { expect(checker.checkString('// jscs: enable\n1 + 1;')).to.have.no.errors(); }); it('should not report on block comments above statements', function() { expect(checker.checkString('/* block comments are skipped */\n1 + 1;')).to.have.no.errors(); }); it('should not report on stacked block comments', function() { expect(checker.checkString('/*block comment*/\n/*block comment*/\n1 + 1;')).to.have.no.errors(); }); it('should not report on block comments beside statements', function() { expect(checker.checkString('1 + 1; /* block comment are skipped*/')).to.have.no.errors(); }); it('should not report on jshint directives beside statements', function() { expect(checker.checkString('1 + 1; // jshint strict: true')).to.have.no.errors(); }); }); describe('position value "beside" with exceptions', function() { beforeEach(function() { checker.configure({ validateCommentPosition: { position: 'beside', allExcept: ['pragma', 'linter'] }}); }); it('should not report on comments that are above statements that begin with excepted keywords', function() { expect(checker.checkString('// pragma valid comment\n1 + 1;')).to.have.no.errors(); }); it('should still report on comments that are above statements that follow excepted comments', function() { expect(checker.checkString('// pragma\n// invalid\n1 + 1;')) .to.have.one.validation.error.from('validateCommentPosition'); }); }); });
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.2 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("./context/context"); var context_2 = require("./context/context"); var TemplateService = (function () { function TemplateService() { this.templateCache = {}; this.waitingCallbacks = {}; } // returns the template if it is loaded, or null if it is not loaded // but will call the callback when it is loaded TemplateService.prototype.getTemplate = function (url, callback) { var templateFromCache = this.templateCache[url]; if (templateFromCache) { return templateFromCache; } var callbackList = this.waitingCallbacks[url]; var that = this; if (!callbackList) { // first time this was called, so need a new list for callbacks callbackList = []; this.waitingCallbacks[url] = callbackList; // and also need to do the http request var client = new XMLHttpRequest(); client.onload = function () { that.handleHttpResult(this, url); }; client.open("GET", url); client.send(); } // add this callback if (callback) { callbackList.push(callback); } // caller needs to wait for template to load, so return null return null; }; TemplateService.prototype.handleHttpResult = function (httpResult, url) { if (httpResult.status !== 200 || httpResult.response === null) { console.warn('Unable to get template error ' + httpResult.status + ' - ' + url); return; } // response success, so process it // in IE9 the response is in - responseText this.templateCache[url] = httpResult.response || httpResult.responseText; // inform all listeners that this is now in the cache var callbacks = this.waitingCallbacks[url]; for (var i = 0; i < callbacks.length; i++) { var callback = callbacks[i]; // we could pass the callback the response, however we know the client of this code // is the cell renderer, and it passes the 'cellRefresh' method in as the callback // which doesn't take any parameters. callback(); } if (this.$scope) { var that_1 = this; setTimeout(function () { that_1.$scope.$apply(); }, 0); } }; __decorate([ context_2.Autowired('$scope'), __metadata("design:type", Object) ], TemplateService.prototype, "$scope", void 0); TemplateService = __decorate([ context_1.Bean('templateService') ], TemplateService); return TemplateService; }()); exports.TemplateService = TemplateService;
if (!RedactorPlugins) var RedactorPlugins = {}; RedactorPlugins.filemanager = function() { return { init: function() { if (!this.opts.fileManagerJson) return; this.modal.addCallback('file', this.filemanager.load); }, load: function() { var $modal = this.modal.getModal(); this.modal.createTabber($modal); this.modal.addTab(1, 'Upload', 'active'); this.modal.addTab(2, 'Choose'); $('#redactor-modal-file-upload-box').addClass('redactor-tab redactor-tab1'); var $box = $('<div id="redactor-file-manager-box" style="overflow: auto; height: 300px;" class="redactor-tab redactor-tab2">').hide(); $modal.append($box); $.ajax({ dataType: "json", cache: false, url: this.opts.fileManagerJson, success: $.proxy(function(data) { var ul = $('<ul id="redactor-modal-list">'); $.each(data, $.proxy(function(key, val) { var a = $('<a href="#" title="' + val.title + '" rel="' + val.link + '">' + val.title + ' <span style="font-size: 11px; color: #888;">' + val.name + '</span> <span style="position: absolute; right: 10px; font-size: 11px; color: #888;">(' + val.size + ')</span></a>'); var li = $('<li />'); a.on('click', $.proxy(this.filemanager.insert, this)); li.append(a); ul.append(li); }, this)); $('#redactor-file-manager-box').append(ul); }, this) }); }, insert: function(e) { e.preventDefault(); this.file.insert('<a href="' + $(e.target).attr('rel') + '">' + $(e.target).attr('title') + '</a>'); } }; };
'use strict'; var numbro = require('../../numbro'), culture = require('../../languages/th-TH'); numbro.culture(culture.langLocaleCode, culture); exports['culture:th-TH'] = { setUp: function (callback) { numbro.culture('th-TH'); callback(); }, tearDown: function (callback) { numbro.culture('en-US'); callback(); }, format: function (test) { test.expect(16); var tests = [ [10000,'0,0.0000','10,000.0000'], [10000.23,'0,0','10,000'], [-10000,'0,0.0','-10,000.0'], [10000.1234,'0.000','10000.123'], [-10000,'(0,0.0000)','(10,000.0000)'], [-0.23,'.00','-.23'], [-0.23,'(.00)','(.23)'], [0.23,'0.00000','0.23000'], [1230974,'0.0a','1.2ล้าน'], [1460,'0a','1พัน'], [-104000,'0a','-104พัน'], [1,'0o','1.'], [52,'0o','52.'], [23,'0o','23.'], [100,'0o','100.'], [1,'0[.]0','1'] ]; for (var i = 0; i < tests.length; i++) { test.strictEqual(numbro(tests[i][0]).format(tests[i][1]), tests[i][2], tests[i][1]); } test.done(); }, currency: function (test) { test.expect(4); var tests = [ [1000.234,'$0,0.00','฿1,000.23'], [-1000.234,'($0,0)','(฿1,000)'], [-1000.234,'$0.00','-฿1000.23'], [1230974,'($0.00a)','฿1.23ล้าน'] ]; for (var i = 0; i < tests.length; i++) { test.strictEqual(numbro(tests[i][0]).format(tests[i][1]), tests[i][2], tests[i][1]); } test.done(); }, percentages: function (test) { test.expect(4); var tests = [ [1,'0%','100%'], [0.974878234,'0.000%','97.488%'], [-0.43,'0%','-43%'], [0.43,'(0.000%)','43.000%'] ]; for (var i = 0; i < tests.length; i++) { test.strictEqual(numbro(tests[i][0]).format(tests[i][1]), tests[i][2], tests[i][1]); } test.done(); }, unformat: function (test) { test.expect(9); var tests = [ ['10,000.123',10000.123], ['(0.12345)',-0.12345], ['(฿1.23ล้าน)',-1230000], ['10พัน',10000], ['-10พัน',-10000], ['23.',23], ['฿10,000.00',10000], ['-76%',-0.76], ['2:23:57',8637] ]; for (var i = 0; i < tests.length; i++) { test.strictEqual(numbro().unformat(tests[i][0]), tests[i][1], tests[i][0]); } test.done(); } };
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import { formatMuiErrorMessage as _formatMuiErrorMessage } from "@material-ui/utils"; import { deepmerge } from '@material-ui/utils'; import common from '../colors/common'; import grey from '../colors/grey'; import indigo from '../colors/indigo'; import pink from '../colors/pink'; import red from '../colors/red'; import orange from '../colors/orange'; import blue from '../colors/blue'; import green from '../colors/green'; import { darken, getContrastRatio, lighten } from './colorManipulator'; export var light = { // The colors used to style the text. text: { // The most important text. primary: 'rgba(0, 0, 0, 0.87)', // Secondary text. secondary: 'rgba(0, 0, 0, 0.54)', // Disabled text have even lower visual prominence. disabled: 'rgba(0, 0, 0, 0.38)', // Text hints. hint: 'rgba(0, 0, 0, 0.38)' }, // The color used to divide different elements. divider: 'rgba(0, 0, 0, 0.12)', // The background colors used to style the surfaces. // Consistency between these values is important. background: { paper: common.white, default: grey[50] }, // The colors used to style the action elements. action: { // The color of an active action like an icon button. active: 'rgba(0, 0, 0, 0.54)', // The color of an hovered action. hover: 'rgba(0, 0, 0, 0.04)', hoverOpacity: 0.04, // The color of a selected action. selected: 'rgba(0, 0, 0, 0.08)', selectedOpacity: 0.08, // The color of a disabled action. disabled: 'rgba(0, 0, 0, 0.26)', // The background color of a disabled action. disabledBackground: 'rgba(0, 0, 0, 0.12)', disabledOpacity: 0.38, focus: 'rgba(0, 0, 0, 0.12)', focusOpacity: 0.12, activatedOpacity: 0.12 } }; export var dark = { text: { primary: common.white, secondary: 'rgba(255, 255, 255, 0.7)', disabled: 'rgba(255, 255, 255, 0.5)', hint: 'rgba(255, 255, 255, 0.5)', icon: 'rgba(255, 255, 255, 0.5)' }, divider: 'rgba(255, 255, 255, 0.12)', background: { paper: grey[800], default: '#303030' }, action: { active: common.white, hover: 'rgba(255, 255, 255, 0.08)', hoverOpacity: 0.08, selected: 'rgba(255, 255, 255, 0.16)', selectedOpacity: 0.16, disabled: 'rgba(255, 255, 255, 0.3)', disabledBackground: 'rgba(255, 255, 255, 0.12)', disabledOpacity: 0.38, focus: 'rgba(255, 255, 255, 0.12)', focusOpacity: 0.12, activatedOpacity: 0.24 } }; function addLightOrDark(intent, direction, shade, tonalOffset) { var tonalOffsetLight = tonalOffset.light || tonalOffset; var tonalOffsetDark = tonalOffset.dark || tonalOffset * 1.5; if (!intent[direction]) { if (intent.hasOwnProperty(shade)) { intent[direction] = intent[shade]; } else if (direction === 'light') { intent.light = lighten(intent.main, tonalOffsetLight); } else if (direction === 'dark') { intent.dark = darken(intent.main, tonalOffsetDark); } } } export default function createPalette(palette) { var _palette$primary = palette.primary, primary = _palette$primary === void 0 ? { light: indigo[300], main: indigo[500], dark: indigo[700] } : _palette$primary, _palette$secondary = palette.secondary, secondary = _palette$secondary === void 0 ? { light: pink.A200, main: pink.A400, dark: pink.A700 } : _palette$secondary, _palette$error = palette.error, error = _palette$error === void 0 ? { light: red[300], main: red[500], dark: red[700] } : _palette$error, _palette$warning = palette.warning, warning = _palette$warning === void 0 ? { light: orange[300], main: orange[500], dark: orange[700] } : _palette$warning, _palette$info = palette.info, info = _palette$info === void 0 ? { light: blue[300], main: blue[500], dark: blue[700] } : _palette$info, _palette$success = palette.success, success = _palette$success === void 0 ? { light: green[300], main: green[500], dark: green[700] } : _palette$success, _palette$type = palette.type, type = _palette$type === void 0 ? 'light' : _palette$type, _palette$contrastThre = palette.contrastThreshold, contrastThreshold = _palette$contrastThre === void 0 ? 3 : _palette$contrastThre, _palette$tonalOffset = palette.tonalOffset, tonalOffset = _palette$tonalOffset === void 0 ? 0.2 : _palette$tonalOffset, other = _objectWithoutProperties(palette, ["primary", "secondary", "error", "warning", "info", "success", "type", "contrastThreshold", "tonalOffset"]); // Use the same logic as // Bootstrap: https://github.com/twbs/bootstrap/blob/1d6e3710dd447de1a200f29e8fa521f8a0908f70/scss/_functions.scss#L59 // and material-components-web https://github.com/material-components/material-components-web/blob/ac46b8863c4dab9fc22c4c662dc6bd1b65dd652f/packages/mdc-theme/_functions.scss#L54 function getContrastText(background) { var contrastText = getContrastRatio(background, dark.text.primary) >= contrastThreshold ? dark.text.primary : light.text.primary; if (process.env.NODE_ENV !== 'production') { var contrast = getContrastRatio(background, contrastText); if (contrast < 3) { console.error(["Material-UI: The contrast ratio of ".concat(contrast, ":1 for ").concat(contrastText, " on ").concat(background), 'falls below the WCAG recommended absolute minimum contrast ratio of 3:1.', 'https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast'].join('\n')); } } return contrastText; } var augmentColor = function augmentColor(color) { var mainShade = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500; var lightShade = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 300; var darkShade = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 700; color = _extends({}, color); if (!color.main && color[mainShade]) { color.main = color[mainShade]; } if (!color.main) { throw new Error(process.env.NODE_ENV !== "production" ? "Material-UI: The color provided to augmentColor(color) is invalid.\nThe color object needs to have a `main` property or a `".concat(mainShade, "` property.") : _formatMuiErrorMessage(4, mainShade)); } if (typeof color.main !== 'string') { throw new Error(process.env.NODE_ENV !== "production" ? "Material-UI: The color provided to augmentColor(color) is invalid.\n`color.main` should be a string, but `".concat(JSON.stringify(color.main), "` was provided instead.\n\nDid you intend to use one of the following approaches?\n\nimport {\xA0green } from \"@material-ui/core/colors\";\n\nconst theme1 = createMuiTheme({ palette: {\n primary: green,\n} });\n\nconst theme2 = createMuiTheme({ palette: {\n primary: { main: green[500] },\n} });") : _formatMuiErrorMessage(5, JSON.stringify(color.main))); } addLightOrDark(color, 'light', lightShade, tonalOffset); addLightOrDark(color, 'dark', darkShade, tonalOffset); if (!color.contrastText) { color.contrastText = getContrastText(color.main); } return color; }; var types = { dark: dark, light: light }; if (process.env.NODE_ENV !== 'production') { if (!types[type]) { console.error("Material-UI: The palette type `".concat(type, "` is not supported.")); } } var paletteOutput = deepmerge(_extends({ // A collection of common colors. common: common, // The palette type, can be light or dark. type: type, // The colors used to represent primary interface elements for a user. primary: augmentColor(primary), // The colors used to represent secondary interface elements for a user. secondary: augmentColor(secondary, 'A400', 'A200', 'A700'), // The colors used to represent interface elements that the user should be made aware of. error: augmentColor(error), // The colors used to represent potentially dangerous actions or important messages. warning: augmentColor(warning), // The colors used to present information to the user that is neutral and not necessarily important. info: augmentColor(info), // The colors used to indicate the successful completion of an action that user triggered. success: augmentColor(success), // The grey colors. grey: grey, // Used by `getContrastText()` to maximize the contrast between // the background and the text. contrastThreshold: contrastThreshold, // Takes a background color and returns the text color that maximizes the contrast. getContrastText: getContrastText, // Generate a rich color object. augmentColor: augmentColor, // Used by the functions below to shift a color's luminance by approximately // two indexes within its tonal palette. // E.g., shift from Red 500 to Red 300 or Red 700. tonalOffset: tonalOffset }, types[type]), other); return paletteOutput; }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ "use strict"; var core_1 = require('@angular/core'); var core_private_1 = require('../core_private'); var browser_1 = require('./browser'); var browser_adapter_1 = require('./browser/browser_adapter'); var testability_1 = require('./browser/testability'); var dom_adapter_1 = require('./dom/dom_adapter'); var dom_renderer_1 = require('./dom/dom_renderer'); var dom_tokens_1 = require('./dom/dom_tokens'); var dom_events_1 = require('./dom/events/dom_events'); var event_manager_1 = require('./dom/events/event_manager'); var hammer_gestures_1 = require('./dom/events/hammer_gestures'); var key_events_1 = require('./dom/events/key_events'); var shared_styles_host_1 = require('./dom/shared_styles_host'); var exceptions_1 = require('./facade/exceptions'); var lang_1 = require('./facade/lang'); var api_1 = require('./web_workers/shared/api'); var client_message_broker_1 = require('./web_workers/shared/client_message_broker'); var message_bus_1 = require('./web_workers/shared/message_bus'); var post_message_bus_1 = require('./web_workers/shared/post_message_bus'); var render_store_1 = require('./web_workers/shared/render_store'); var serializer_1 = require('./web_workers/shared/serializer'); var service_message_broker_1 = require('./web_workers/shared/service_message_broker'); var renderer_1 = require('./web_workers/ui/renderer'); var WORKER_RENDER_PLATFORM_MARKER = new core_1.OpaqueToken('WorkerRenderPlatformMarker'); var WebWorkerInstance = (function () { function WebWorkerInstance() { } /** @internal */ WebWorkerInstance.prototype.init = function (worker, bus) { this.worker = worker; this.bus = bus; }; /** @nocollapse */ WebWorkerInstance.decorators = [ { type: core_1.Injectable }, ]; return WebWorkerInstance; }()); exports.WebWorkerInstance = WebWorkerInstance; /** * @experimental WebWorker support is currently experimental. */ exports.WORKER_SCRIPT = new core_1.OpaqueToken('WebWorkerScript'); /** * A multiple providers used to automatically call the `start()` method after the service is * created. * * TODO(vicb): create an interface for startable services to implement * @experimental WebWorker support is currently experimental. */ exports.WORKER_UI_STARTABLE_MESSAGING_SERVICE = new core_1.OpaqueToken('WorkerRenderStartableMsgService'); /** * @experimental WebWorker support is currently experimental. */ exports.WORKER_UI_PLATFORM_PROVIDERS = [ core_1.PLATFORM_COMMON_PROVIDERS, { provide: WORKER_RENDER_PLATFORM_MARKER, useValue: true }, { provide: core_1.PLATFORM_INITIALIZER, useValue: initWebWorkerRenderPlatform, multi: true } ]; /** * @experimental WebWorker support is currently experimental. */ exports.WORKER_UI_APPLICATION_PROVIDERS = [ core_1.APPLICATION_COMMON_PROVIDERS, renderer_1.MessageBasedRenderer, { provide: exports.WORKER_UI_STARTABLE_MESSAGING_SERVICE, useExisting: renderer_1.MessageBasedRenderer, multi: true }, browser_1.BROWSER_SANITIZATION_PROVIDERS, { provide: core_1.ExceptionHandler, useFactory: _exceptionHandler, deps: [] }, { provide: dom_tokens_1.DOCUMENT, useFactory: _document, deps: [] }, // TODO(jteplitz602): Investigate if we definitely need EVENT_MANAGER on the render thread // #5298 { provide: event_manager_1.EVENT_MANAGER_PLUGINS, useClass: dom_events_1.DomEventsPlugin, multi: true }, { provide: event_manager_1.EVENT_MANAGER_PLUGINS, useClass: key_events_1.KeyEventsPlugin, multi: true }, { provide: event_manager_1.EVENT_MANAGER_PLUGINS, useClass: hammer_gestures_1.HammerGesturesPlugin, multi: true }, { provide: hammer_gestures_1.HAMMER_GESTURE_CONFIG, useClass: hammer_gestures_1.HammerGestureConfig }, { provide: dom_renderer_1.DomRootRenderer, useClass: dom_renderer_1.DomRootRenderer_ }, { provide: core_1.RootRenderer, useExisting: dom_renderer_1.DomRootRenderer }, { provide: shared_styles_host_1.SharedStylesHost, useExisting: shared_styles_host_1.DomSharedStylesHost }, { provide: service_message_broker_1.ServiceMessageBrokerFactory, useClass: service_message_broker_1.ServiceMessageBrokerFactory_ }, { provide: client_message_broker_1.ClientMessageBrokerFactory, useClass: client_message_broker_1.ClientMessageBrokerFactory_ }, { provide: core_private_1.AnimationDriver, useFactory: _resolveDefaultAnimationDriver }, serializer_1.Serializer, { provide: api_1.ON_WEB_WORKER, useValue: false }, render_store_1.RenderStore, shared_styles_host_1.DomSharedStylesHost, core_1.Testability, event_manager_1.EventManager, WebWorkerInstance, { provide: core_1.APP_INITIALIZER, useFactory: initWebWorkerAppFn, multi: true, deps: [core_1.Injector] }, { provide: message_bus_1.MessageBus, useFactory: messageBusFactory, deps: [WebWorkerInstance] } ]; function initializeGenericWorkerRenderer(injector) { var bus = injector.get(message_bus_1.MessageBus); var zone = injector.get(core_1.NgZone); bus.attachToZone(zone); // initialize message services after the bus has been created var services = injector.get(exports.WORKER_UI_STARTABLE_MESSAGING_SERVICE); zone.runGuarded(function () { services.forEach(function (svc) { svc.start(); }); }); } function messageBusFactory(instance) { return instance.bus; } function initWebWorkerRenderPlatform() { browser_adapter_1.BrowserDomAdapter.makeCurrent(); core_private_1.wtfInit(); testability_1.BrowserGetTestability.init(); } /** * @experimental WebWorker support is currently experimental. */ function workerUiPlatform() { if (lang_1.isBlank(core_1.getPlatform())) { core_1.createPlatform(core_1.ReflectiveInjector.resolveAndCreate(exports.WORKER_UI_PLATFORM_PROVIDERS)); } return core_1.assertPlatform(WORKER_RENDER_PLATFORM_MARKER); } exports.workerUiPlatform = workerUiPlatform; function _exceptionHandler() { return new core_1.ExceptionHandler(dom_adapter_1.getDOM()); } function _document() { return dom_adapter_1.getDOM().defaultDoc(); } function initWebWorkerAppFn(injector) { return function () { var scriptUri; try { scriptUri = injector.get(exports.WORKER_SCRIPT); } catch (e) { throw new exceptions_1.BaseException('You must provide your WebWorker\'s initialization script with the WORKER_SCRIPT token'); } var instance = injector.get(WebWorkerInstance); spawnWebWorker(scriptUri, instance); initializeGenericWorkerRenderer(injector); }; } /** * Spawns a new class and initializes the WebWorkerInstance */ function spawnWebWorker(uri, instance) { var webWorker = new Worker(uri); var sink = new post_message_bus_1.PostMessageBusSink(webWorker); var source = new post_message_bus_1.PostMessageBusSource(webWorker); var bus = new post_message_bus_1.PostMessageBus(sink, source); instance.init(webWorker, bus); } function _resolveDefaultAnimationDriver() { // web workers have not been tested or configured to // work with animations just yet... return new core_private_1.NoOpAnimationDriver(); } //# sourceMappingURL=worker_render.js.map
/* Leaflet.markercluster, Provides Beautiful Animated Marker Clustering functionality for Leaflet, a JS library for interactive maps. https://github.com/Leaflet/Leaflet.markercluster (c) 2012-2013, Dave Leaver, smartrak */ (function (window, document, undefined) {/* * L.MarkerClusterGroup extends L.FeatureGroup by clustering the markers contained within */ L.MarkerClusterGroup = L.FeatureGroup.extend({ options: { maxClusterRadius: 80, //A cluster will cover at most this many pixels from its center iconCreateFunction: null, spiderfyOnMaxZoom: true, showCoverageOnHover: true, zoomToBoundsOnClick: true, singleMarkerMode: false, disableClusteringAtZoom: null, // Setting this to false prevents the removal of any clusters outside of the viewpoint, which // is the default behaviour for performance reasons. removeOutsideVisibleBounds: true, //Whether to animate adding markers after adding the MarkerClusterGroup to the map // If you are adding individual markers set to true, if adding bulk markers leave false for massive performance gains. animateAddingMarkers: false, //Increase to increase the distance away that spiderfied markers appear from the center spiderfyDistanceMultiplier: 1, //Options to pass to the L.Polygon constructor polygonOptions: {} }, initialize: function (options) { L.Util.setOptions(this, options); if (!this.options.iconCreateFunction) { this.options.iconCreateFunction = this._defaultIconCreateFunction; } this._featureGroup = L.featureGroup(); this._featureGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this); this._nonPointGroup = L.featureGroup(); this._nonPointGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this); this._inZoomAnimation = 0; this._needsClustering = []; this._needsRemoving = []; //Markers removed while we aren't on the map need to be kept track of //The bounds of the currently shown area (from _getExpandedVisibleBounds) Updated on zoom/move this._currentShownBounds = null; this._queue = []; }, addLayer: function (layer) { if (layer instanceof L.LayerGroup) { var array = []; for (var i in layer._layers) { array.push(layer._layers[i]); } return this.addLayers(array); } //Don't cluster non point data if (!layer.getLatLng) { this._nonPointGroup.addLayer(layer); return this; } if (!this._map) { this._needsClustering.push(layer); return this; } if (this.hasLayer(layer)) { return this; } //If we have already clustered we'll need to add this one to a cluster if (this._unspiderfy) { this._unspiderfy(); } this._addLayer(layer, this._maxZoom); //Work out what is visible var visibleLayer = layer, currentZoom = this._map.getZoom(); if (layer.__parent) { while (visibleLayer.__parent._zoom >= currentZoom) { visibleLayer = visibleLayer.__parent; } } if (this._currentShownBounds.contains(visibleLayer.getLatLng())) { if (this.options.animateAddingMarkers) { this._animationAddLayer(layer, visibleLayer); } else { this._animationAddLayerNonAnimated(layer, visibleLayer); } } return this; }, removeLayer: function (layer) { if (layer instanceof L.LayerGroup) { var array = []; for (var i in layer._layers) { array.push(layer._layers[i]); } return this.removeLayers(array); } //Non point layers if (!layer.getLatLng) { this._nonPointGroup.removeLayer(layer); return this; } if (!this._map) { if (!this._arraySplice(this._needsClustering, layer) && this.hasLayer(layer)) { this._needsRemoving.push(layer); } return this; } if (!layer.__parent) { return this; } if (this._unspiderfy) { this._unspiderfy(); this._unspiderfyLayer(layer); } //Remove the marker from clusters this._removeLayer(layer, true); if (this._featureGroup.hasLayer(layer)) { this._featureGroup.removeLayer(layer); if (layer.setOpacity) { layer.setOpacity(1); } } return this; }, //Takes an array of markers and adds them in bulk addLayers: function (layersArray) { var i, l, m, onMap = this._map, fg = this._featureGroup, npg = this._nonPointGroup; for (i = 0, l = layersArray.length; i < l; i++) { m = layersArray[i]; //Not point data, can't be clustered if (!m.getLatLng) { npg.addLayer(m); continue; } if (this.hasLayer(m)) { continue; } if (!onMap) { this._needsClustering.push(m); continue; } this._addLayer(m, this._maxZoom); //If we just made a cluster of size 2 then we need to remove the other marker from the map (if it is) or we never will if (m.__parent) { if (m.__parent.getChildCount() === 2) { var markers = m.__parent.getAllChildMarkers(), otherMarker = markers[0] === m ? markers[1] : markers[0]; fg.removeLayer(otherMarker); } } } if (onMap) { //Update the icons of all those visible clusters that were affected fg.eachLayer(function (c) { if (c instanceof L.MarkerCluster && c._iconNeedsUpdate) { c._updateIcon(); } }); this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds); } return this; }, //Takes an array of markers and removes them in bulk removeLayers: function (layersArray) { var i, l, m, fg = this._featureGroup, npg = this._nonPointGroup; if (!this._map) { for (i = 0, l = layersArray.length; i < l; i++) { m = layersArray[i]; this._arraySplice(this._needsClustering, m); npg.removeLayer(m); } return this; } for (i = 0, l = layersArray.length; i < l; i++) { m = layersArray[i]; if (!m.__parent) { npg.removeLayer(m); continue; } this._removeLayer(m, true, true); if (fg.hasLayer(m)) { fg.removeLayer(m); if (m.setOpacity) { m.setOpacity(1); } } } //Fix up the clusters and markers on the map this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds); fg.eachLayer(function (c) { if (c instanceof L.MarkerCluster) { c._updateIcon(); } }); return this; }, //Removes all layers from the MarkerClusterGroup clearLayers: function () { //Need our own special implementation as the LayerGroup one doesn't work for us //If we aren't on the map (yet), blow away the markers we know of if (!this._map) { this._needsClustering = []; delete this._gridClusters; delete this._gridUnclustered; } if (this._noanimationUnspiderfy) { this._noanimationUnspiderfy(); } //Remove all the visible layers this._featureGroup.clearLayers(); this._nonPointGroup.clearLayers(); this.eachLayer(function (marker) { delete marker.__parent; }); if (this._map) { //Reset _topClusterLevel and the DistanceGrids this._generateInitialClusters(); } return this; }, //Override FeatureGroup.getBounds as it doesn't work getBounds: function () { var bounds = new L.LatLngBounds(); if (this._topClusterLevel) { bounds.extend(this._topClusterLevel._bounds); } else { for (var i = this._needsClustering.length - 1; i >= 0; i--) { bounds.extend(this._needsClustering[i].getLatLng()); } } bounds.extend(this._nonPointGroup.getBounds()); return bounds; }, //Overrides LayerGroup.eachLayer eachLayer: function (method, context) { var markers = this._needsClustering.slice(), i; if (this._topClusterLevel) { this._topClusterLevel.getAllChildMarkers(markers); } for (i = markers.length - 1; i >= 0; i--) { method.call(context, markers[i]); } this._nonPointGroup.eachLayer(method, context); }, //Overrides LayerGroup.getLayers getLayers: function () { var layers = []; this.eachLayer(function (l) { layers.push(l); }); return layers; }, //Overrides LayerGroup.getLayer, WARNING: Really bad performance getLayer: function (id) { var result = null; this.eachLayer(function (l) { if (L.stamp(l) === id) { result = l; } }); return result; }, //Returns true if the given layer is in this MarkerClusterGroup hasLayer: function (layer) { if (!layer) { return false; } var i, anArray = this._needsClustering; for (i = anArray.length - 1; i >= 0; i--) { if (anArray[i] === layer) { return true; } } anArray = this._needsRemoving; for (i = anArray.length - 1; i >= 0; i--) { if (anArray[i] === layer) { return false; } } return !!(layer.__parent && layer.__parent._group === this) || this._nonPointGroup.hasLayer(layer); }, //Zoom down to show the given layer (spiderfying if necessary) then calls the callback zoomToShowLayer: function (layer, callback) { var showMarker = function () { if ((layer._icon || layer.__parent._icon) && !this._inZoomAnimation) { this._map.off('moveend', showMarker, this); this.off('animationend', showMarker, this); if (layer._icon) { callback(); } else if (layer.__parent._icon) { var afterSpiderfy = function () { this.off('spiderfied', afterSpiderfy, this); callback(); }; this.on('spiderfied', afterSpiderfy, this); layer.__parent.spiderfy(); } } }; if (layer._icon && this._map.getBounds().contains(layer.getLatLng())) { callback(); } else if (layer.__parent._zoom < this._map.getZoom()) { //Layer should be visible now but isn't on screen, just pan over to it this._map.on('moveend', showMarker, this); this._map.panTo(layer.getLatLng()); } else { this._map.on('moveend', showMarker, this); this.on('animationend', showMarker, this); this._map.setView(layer.getLatLng(), layer.__parent._zoom + 1); layer.__parent.zoomToBounds(); } }, //Overrides FeatureGroup.onAdd onAdd: function (map) { this._map = map; var i, l, layer; if (!isFinite(this._map.getMaxZoom())) { throw "Map has no maxZoom specified"; } this._featureGroup.onAdd(map); this._nonPointGroup.onAdd(map); if (!this._gridClusters) { this._generateInitialClusters(); } for (i = 0, l = this._needsRemoving.length; i < l; i++) { layer = this._needsRemoving[i]; this._removeLayer(layer, true); } this._needsRemoving = []; for (i = 0, l = this._needsClustering.length; i < l; i++) { layer = this._needsClustering[i]; //If the layer doesn't have a getLatLng then we can't cluster it, so add it to our child featureGroup if (!layer.getLatLng) { this._featureGroup.addLayer(layer); continue; } if (layer.__parent) { continue; } this._addLayer(layer, this._maxZoom); } this._needsClustering = []; this._map.on('zoomend', this._zoomEnd, this); this._map.on('moveend', this._moveEnd, this); if (this._spiderfierOnAdd) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely this._spiderfierOnAdd(); } this._bindEvents(); //Actually add our markers to the map: //Remember the current zoom level and bounds this._zoom = this._map.getZoom(); this._currentShownBounds = this._getExpandedVisibleBounds(); //Make things appear on the map this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds); }, //Overrides FeatureGroup.onRemove onRemove: function (map) { map.off('zoomend', this._zoomEnd, this); map.off('moveend', this._moveEnd, this); this._unbindEvents(); //In case we are in a cluster animation this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', ''); if (this._spiderfierOnRemove) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely this._spiderfierOnRemove(); } //Clean up all the layers we added to the map this._hideCoverage(); this._featureGroup.onRemove(map); this._nonPointGroup.onRemove(map); this._featureGroup.clearLayers(); this._map = null; }, getVisibleParent: function (marker) { var vMarker = marker; while (vMarker && !vMarker._icon) { vMarker = vMarker.__parent; } return vMarker || null; }, //Remove the given object from the given array _arraySplice: function (anArray, obj) { for (var i = anArray.length - 1; i >= 0; i--) { if (anArray[i] === obj) { anArray.splice(i, 1); return true; } } }, //Internal function for removing a marker from everything. //dontUpdateMap: set to true if you will handle updating the map manually (for bulk functions) _removeLayer: function (marker, removeFromDistanceGrid, dontUpdateMap) { var gridClusters = this._gridClusters, gridUnclustered = this._gridUnclustered, fg = this._featureGroup, map = this._map; //Remove the marker from distance clusters it might be in if (removeFromDistanceGrid) { for (var z = this._maxZoom; z >= 0; z--) { if (!gridUnclustered[z].removeObject(marker, map.project(marker.getLatLng(), z))) { break; } } } //Work our way up the clusters removing them as we go if required var cluster = marker.__parent, markers = cluster._markers, otherMarker; //Remove the marker from the immediate parents marker list this._arraySplice(markers, marker); while (cluster) { cluster._childCount--; if (cluster._zoom < 0) { //Top level, do nothing break; } else if (removeFromDistanceGrid && cluster._childCount <= 1) { //Cluster no longer required //We need to push the other marker up to the parent otherMarker = cluster._markers[0] === marker ? cluster._markers[1] : cluster._markers[0]; //Update distance grid gridClusters[cluster._zoom].removeObject(cluster, map.project(cluster._cLatLng, cluster._zoom)); gridUnclustered[cluster._zoom].addObject(otherMarker, map.project(otherMarker.getLatLng(), cluster._zoom)); //Move otherMarker up to parent this._arraySplice(cluster.__parent._childClusters, cluster); cluster.__parent._markers.push(otherMarker); otherMarker.__parent = cluster.__parent; if (cluster._icon) { //Cluster is currently on the map, need to put the marker on the map instead fg.removeLayer(cluster); if (!dontUpdateMap) { fg.addLayer(otherMarker); } } } else { cluster._recalculateBounds(); if (!dontUpdateMap || !cluster._icon) { cluster._updateIcon(); } } cluster = cluster.__parent; } delete marker.__parent; }, _isOrIsParent: function (el, oel) { while (oel) { if (el === oel) { return true; } oel = oel.parentNode; } return false; }, _propagateEvent: function (e) { if (e.layer instanceof L.MarkerCluster) { //Prevent multiple clustermouseover/off events if the icon is made up of stacked divs (Doesn't work in ie <= 8, no relatedTarget) if (e.originalEvent && this._isOrIsParent(e.layer._icon, e.originalEvent.relatedTarget)) { return; } e.type = 'cluster' + e.type; } this.fire(e.type, e); }, //Default functionality _defaultIconCreateFunction: function (cluster) { var childCount = cluster.getChildCount(); var c = ' marker-cluster-'; if (childCount < 10) { c += 'small'; } else if (childCount < 100) { c += 'medium'; } else { c += 'large'; } return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) }); }, _bindEvents: function () { var map = this._map, spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom, showCoverageOnHover = this.options.showCoverageOnHover, zoomToBoundsOnClick = this.options.zoomToBoundsOnClick; //Zoom on cluster click or spiderfy if we are at the lowest level if (spiderfyOnMaxZoom || zoomToBoundsOnClick) { this.on('clusterclick', this._zoomOrSpiderfy, this); } //Show convex hull (boundary) polygon on mouse over if (showCoverageOnHover) { this.on('clustermouseover', this._showCoverage, this); this.on('clustermouseout', this._hideCoverage, this); map.on('zoomend', this._hideCoverage, this); } }, _zoomOrSpiderfy: function (e) { var map = this._map; if (map.getMaxZoom() === map.getZoom()) { if (this.options.spiderfyOnMaxZoom) { e.layer.spiderfy(); } } else if (this.options.zoomToBoundsOnClick) { e.layer.zoomToBounds(); } // Focus the map again for keyboard users. if (e.originalEvent && e.originalEvent.keyCode === 13) { map._container.focus(); } }, _showCoverage: function (e) { var map = this._map; if (this._inZoomAnimation) { return; } if (this._shownPolygon) { map.removeLayer(this._shownPolygon); } if (e.layer.getChildCount() > 2 && e.layer !== this._spiderfied) { this._shownPolygon = new L.Polygon(e.layer.getConvexHull(), this.options.polygonOptions); map.addLayer(this._shownPolygon); } }, _hideCoverage: function () { if (this._shownPolygon) { this._map.removeLayer(this._shownPolygon); this._shownPolygon = null; } }, _unbindEvents: function () { var spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom, showCoverageOnHover = this.options.showCoverageOnHover, zoomToBoundsOnClick = this.options.zoomToBoundsOnClick, map = this._map; if (spiderfyOnMaxZoom || zoomToBoundsOnClick) { this.off('clusterclick', this._zoomOrSpiderfy, this); } if (showCoverageOnHover) { this.off('clustermouseover', this._showCoverage, this); this.off('clustermouseout', this._hideCoverage, this); map.off('zoomend', this._hideCoverage, this); } }, _zoomEnd: function () { if (!this._map) { //May have been removed from the map by a zoomEnd handler return; } this._mergeSplitClusters(); this._zoom = this._map._zoom; this._currentShownBounds = this._getExpandedVisibleBounds(); }, _moveEnd: function () { if (this._inZoomAnimation) { return; } var newBounds = this._getExpandedVisibleBounds(); this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, newBounds); this._topClusterLevel._recursivelyAddChildrenToMap(null, this._map._zoom, newBounds); this._currentShownBounds = newBounds; return; }, _generateInitialClusters: function () { var maxZoom = this._map.getMaxZoom(), radius = this.options.maxClusterRadius, radiusFn = radius; //If we just set maxClusterRadius to a single number, we need to create //a simple function to return that number. Otherwise, we just have to //use the function we've passed in. if (typeof radius !== "function") { radiusFn = function () { return radius; }; } if (this.options.disableClusteringAtZoom) { maxZoom = this.options.disableClusteringAtZoom - 1; } this._maxZoom = maxZoom; this._gridClusters = {}; this._gridUnclustered = {}; //Set up DistanceGrids for each zoom for (var zoom = maxZoom; zoom >= 0; zoom--) { this._gridClusters[zoom] = new L.DistanceGrid(radiusFn(zoom)); this._gridUnclustered[zoom] = new L.DistanceGrid(radiusFn(zoom)); } this._topClusterLevel = new L.MarkerCluster(this, -1); }, //Zoom: Zoom to start adding at (Pass this._maxZoom to start at the bottom) _addLayer: function (layer, zoom) { var gridClusters = this._gridClusters, gridUnclustered = this._gridUnclustered, markerPoint, z; if (this.options.singleMarkerMode) { layer.options.icon = this.options.iconCreateFunction({ getChildCount: function () { return 1; }, getAllChildMarkers: function () { return [layer]; } }); } //Find the lowest zoom level to slot this one in for (; zoom >= 0; zoom--) { markerPoint = this._map.project(layer.getLatLng(), zoom); // calculate pixel position //Try find a cluster close by var closest = gridClusters[zoom].getNearObject(markerPoint); if (closest) { closest._addChild(layer); layer.__parent = closest; return; } //Try find a marker close by to form a new cluster with closest = gridUnclustered[zoom].getNearObject(markerPoint); if (closest) { var parent = closest.__parent; if (parent) { this._removeLayer(closest, false); } //Create new cluster with these 2 in it var newCluster = new L.MarkerCluster(this, zoom, closest, layer); gridClusters[zoom].addObject(newCluster, this._map.project(newCluster._cLatLng, zoom)); closest.__parent = newCluster; layer.__parent = newCluster; //First create any new intermediate parent clusters that don't exist var lastParent = newCluster; for (z = zoom - 1; z > parent._zoom; z--) { lastParent = new L.MarkerCluster(this, z, lastParent); gridClusters[z].addObject(lastParent, this._map.project(closest.getLatLng(), z)); } parent._addChild(lastParent); //Remove closest from this zoom level and any above that it is in, replace with newCluster for (z = zoom; z >= 0; z--) { if (!gridUnclustered[z].removeObject(closest, this._map.project(closest.getLatLng(), z))) { break; } } return; } //Didn't manage to cluster in at this zoom, record us as a marker here and continue upwards gridUnclustered[zoom].addObject(layer, markerPoint); } //Didn't get in anything, add us to the top this._topClusterLevel._addChild(layer); layer.__parent = this._topClusterLevel; return; }, //Enqueue code to fire after the marker expand/contract has happened _enqueue: function (fn) { this._queue.push(fn); if (!this._queueTimeout) { this._queueTimeout = setTimeout(L.bind(this._processQueue, this), 300); } }, _processQueue: function () { for (var i = 0; i < this._queue.length; i++) { this._queue[i].call(this); } this._queue.length = 0; clearTimeout(this._queueTimeout); this._queueTimeout = null; }, //Merge and split any existing clusters that are too big or small _mergeSplitClusters: function () { //Incase we are starting to split before the animation finished this._processQueue(); if (this._zoom < this._map._zoom && this._currentShownBounds.contains(this._getExpandedVisibleBounds())) { //Zoom in, split this._animationStart(); //Remove clusters now off screen this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, this._getExpandedVisibleBounds()); this._animationZoomIn(this._zoom, this._map._zoom); } else if (this._zoom > this._map._zoom) { //Zoom out, merge this._animationStart(); this._animationZoomOut(this._zoom, this._map._zoom); } else { this._moveEnd(); } }, //Gets the maps visible bounds expanded in each direction by the size of the screen (so the user cannot see an area we do not cover in one pan) _getExpandedVisibleBounds: function () { if (!this.options.removeOutsideVisibleBounds) { return this.getBounds(); } var map = this._map, bounds = map.getBounds(), sw = bounds._southWest, ne = bounds._northEast, latDiff = L.Browser.mobile ? 0 : Math.abs(sw.lat - ne.lat), lngDiff = L.Browser.mobile ? 0 : Math.abs(sw.lng - ne.lng); return new L.LatLngBounds( new L.LatLng(sw.lat - latDiff, sw.lng - lngDiff, true), new L.LatLng(ne.lat + latDiff, ne.lng + lngDiff, true)); }, //Shared animation code _animationAddLayerNonAnimated: function (layer, newCluster) { if (newCluster === layer) { this._featureGroup.addLayer(layer); } else if (newCluster._childCount === 2) { newCluster._addToMap(); var markers = newCluster.getAllChildMarkers(); this._featureGroup.removeLayer(markers[0]); this._featureGroup.removeLayer(markers[1]); } else { newCluster._updateIcon(); } } }); L.MarkerClusterGroup.include(!L.DomUtil.TRANSITION ? { //Non Animated versions of everything _animationStart: function () { //Do nothing... }, _animationZoomIn: function (previousZoomLevel, newZoomLevel) { this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel); this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds()); }, _animationZoomOut: function (previousZoomLevel, newZoomLevel) { this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel); this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds()); }, _animationAddLayer: function (layer, newCluster) { this._animationAddLayerNonAnimated(layer, newCluster); } } : { //Animated versions here _animationStart: function () { this._map._mapPane.className += ' leaflet-cluster-anim'; this._inZoomAnimation++; }, _animationEnd: function () { if (this._map) { this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', ''); } this._inZoomAnimation--; this.fire('animationend'); }, _animationZoomIn: function (previousZoomLevel, newZoomLevel) { var bounds = this._getExpandedVisibleBounds(), fg = this._featureGroup, i; //Add all children of current clusters to map and remove those clusters from map this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) { var startPos = c._latlng, markers = c._markers, m; if (!bounds.contains(startPos)) { startPos = null; } if (c._isSingleParent() && previousZoomLevel + 1 === newZoomLevel) { //Immediately add the new child and remove us fg.removeLayer(c); c._recursivelyAddChildrenToMap(null, newZoomLevel, bounds); } else { //Fade out old cluster c.setOpacity(0); c._recursivelyAddChildrenToMap(startPos, newZoomLevel, bounds); } //Remove all markers that aren't visible any more //TODO: Do we actually need to do this on the higher levels too? for (i = markers.length - 1; i >= 0; i--) { m = markers[i]; if (!bounds.contains(m._latlng)) { fg.removeLayer(m); } } }); this._forceLayout(); //Update opacities this._topClusterLevel._recursivelyBecomeVisible(bounds, newZoomLevel); //TODO Maybe? Update markers in _recursivelyBecomeVisible fg.eachLayer(function (n) { if (!(n instanceof L.MarkerCluster) && n._icon) { n.setOpacity(1); } }); //update the positions of the just added clusters/markers this._topClusterLevel._recursively(bounds, previousZoomLevel, newZoomLevel, function (c) { c._recursivelyRestoreChildPositions(newZoomLevel); }); //Remove the old clusters and close the zoom animation this._enqueue(function () { //update the positions of the just added clusters/markers this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) { fg.removeLayer(c); c.setOpacity(1); }); this._animationEnd(); }); }, _animationZoomOut: function (previousZoomLevel, newZoomLevel) { this._animationZoomOutSingle(this._topClusterLevel, previousZoomLevel - 1, newZoomLevel); //Need to add markers for those that weren't on the map before but are now this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds()); //Remove markers that were on the map before but won't be now this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel, this._getExpandedVisibleBounds()); }, _animationZoomOutSingle: function (cluster, previousZoomLevel, newZoomLevel) { var bounds = this._getExpandedVisibleBounds(); //Animate all of the markers in the clusters to move to their cluster center point cluster._recursivelyAnimateChildrenInAndAddSelfToMap(bounds, previousZoomLevel + 1, newZoomLevel); var me = this; //Update the opacity (If we immediately set it they won't animate) this._forceLayout(); cluster._recursivelyBecomeVisible(bounds, newZoomLevel); //TODO: Maybe use the transition timing stuff to make this more reliable //When the animations are done, tidy up this._enqueue(function () { //This cluster stopped being a cluster before the timeout fired if (cluster._childCount === 1) { var m = cluster._markers[0]; //If we were in a cluster animation at the time then the opacity and position of our child could be wrong now, so fix it m.setLatLng(m.getLatLng()); if (m.setOpacity) { m.setOpacity(1); } } else { cluster._recursively(bounds, newZoomLevel, 0, function (c) { c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel + 1); }); } me._animationEnd(); }); }, _animationAddLayer: function (layer, newCluster) { var me = this, fg = this._featureGroup; fg.addLayer(layer); if (newCluster !== layer) { if (newCluster._childCount > 2) { //Was already a cluster newCluster._updateIcon(); this._forceLayout(); this._animationStart(); layer._setPos(this._map.latLngToLayerPoint(newCluster.getLatLng())); layer.setOpacity(0); this._enqueue(function () { fg.removeLayer(layer); layer.setOpacity(1); me._animationEnd(); }); } else { //Just became a cluster this._forceLayout(); me._animationStart(); me._animationZoomOutSingle(newCluster, this._map.getMaxZoom(), this._map.getZoom()); } } }, //Force a browser layout of stuff in the map // Should apply the current opacity and location to all elements so we can update them again for an animation _forceLayout: function () { //In my testing this works, infact offsetWidth of any element seems to work. //Could loop all this._layers and do this for each _icon if it stops working L.Util.falseFn(document.body.offsetWidth); } }); L.markerClusterGroup = function (options) { return new L.MarkerClusterGroup(options); }; L.MarkerCluster = L.Marker.extend({ initialize: function (group, zoom, a, b) { L.Marker.prototype.initialize.call(this, a ? (a._cLatLng || a.getLatLng()) : new L.LatLng(0, 0), { icon: this }); this._group = group; this._zoom = zoom; this._markers = []; this._childClusters = []; this._childCount = 0; this._iconNeedsUpdate = true; this._bounds = new L.LatLngBounds(); if (a) { this._addChild(a); } if (b) { this._addChild(b); } }, //Recursively retrieve all child markers of this cluster getAllChildMarkers: function (storageArray) { storageArray = storageArray || []; for (var i = this._childClusters.length - 1; i >= 0; i--) { this._childClusters[i].getAllChildMarkers(storageArray); } for (var j = this._markers.length - 1; j >= 0; j--) { storageArray.push(this._markers[j]); } return storageArray; }, //Returns the count of how many child markers we have getChildCount: function () { return this._childCount; }, //Zoom to the minimum of showing all of the child markers, or the extents of this cluster zoomToBounds: function () { var childClusters = this._childClusters.slice(), map = this._group._map, boundsZoom = map.getBoundsZoom(this._bounds), zoom = this._zoom + 1, mapZoom = map.getZoom(), i; //calculate how fare we need to zoom down to see all of the markers while (childClusters.length > 0 && boundsZoom > zoom) { zoom++; var newClusters = []; for (i = 0; i < childClusters.length; i++) { newClusters = newClusters.concat(childClusters[i]._childClusters); } childClusters = newClusters; } if (boundsZoom > zoom) { this._group._map.setView(this._latlng, zoom); } else if (boundsZoom <= mapZoom) { //If fitBounds wouldn't zoom us down, zoom us down instead this._group._map.setView(this._latlng, mapZoom + 1); } else { this._group._map.fitBounds(this._bounds); } }, getBounds: function () { var bounds = new L.LatLngBounds(); bounds.extend(this._bounds); return bounds; }, _updateIcon: function () { this._iconNeedsUpdate = true; if (this._icon) { this.setIcon(this); } }, //Cludge for Icon, we pretend to be an icon for performance createIcon: function () { if (this._iconNeedsUpdate) { this._iconObj = this._group.options.iconCreateFunction(this); this._iconNeedsUpdate = false; } return this._iconObj.createIcon(); }, createShadow: function () { return this._iconObj.createShadow(); }, _addChild: function (new1, isNotificationFromChild) { this._iconNeedsUpdate = true; this._expandBounds(new1); if (new1 instanceof L.MarkerCluster) { if (!isNotificationFromChild) { this._childClusters.push(new1); new1.__parent = this; } this._childCount += new1._childCount; } else { if (!isNotificationFromChild) { this._markers.push(new1); } this._childCount++; } if (this.__parent) { this.__parent._addChild(new1, true); } }, //Expand our bounds and tell our parent to _expandBounds: function (marker) { var addedCount, addedLatLng = marker._wLatLng || marker._latlng; if (marker instanceof L.MarkerCluster) { this._bounds.extend(marker._bounds); addedCount = marker._childCount; } else { this._bounds.extend(addedLatLng); addedCount = 1; } if (!this._cLatLng) { // when clustering, take position of the first point as the cluster center this._cLatLng = marker._cLatLng || addedLatLng; } // when showing clusters, take weighted average of all points as cluster center var totalCount = this._childCount + addedCount; //Calculate weighted latlng for display if (!this._wLatLng) { this._latlng = this._wLatLng = new L.LatLng(addedLatLng.lat, addedLatLng.lng); } else { this._wLatLng.lat = (addedLatLng.lat * addedCount + this._wLatLng.lat * this._childCount) / totalCount; this._wLatLng.lng = (addedLatLng.lng * addedCount + this._wLatLng.lng * this._childCount) / totalCount; } }, //Set our markers position as given and add it to the map _addToMap: function (startPos) { if (startPos) { this._backupLatlng = this._latlng; this.setLatLng(startPos); } this._group._featureGroup.addLayer(this); }, _recursivelyAnimateChildrenIn: function (bounds, center, maxZoom) { this._recursively(bounds, 0, maxZoom - 1, function (c) { var markers = c._markers, i, m; for (i = markers.length - 1; i >= 0; i--) { m = markers[i]; //Only do it if the icon is still on the map if (m._icon) { m._setPos(center); m.setOpacity(0); } } }, function (c) { var childClusters = c._childClusters, j, cm; for (j = childClusters.length - 1; j >= 0; j--) { cm = childClusters[j]; if (cm._icon) { cm._setPos(center); cm.setOpacity(0); } } } ); }, _recursivelyAnimateChildrenInAndAddSelfToMap: function (bounds, previousZoomLevel, newZoomLevel) { this._recursively(bounds, newZoomLevel, 0, function (c) { c._recursivelyAnimateChildrenIn(bounds, c._group._map.latLngToLayerPoint(c.getLatLng()).round(), previousZoomLevel); //TODO: depthToAnimateIn affects _isSingleParent, if there is a multizoom we may/may not be. //As a hack we only do a animation free zoom on a single level zoom, if someone does multiple levels then we always animate if (c._isSingleParent() && previousZoomLevel - 1 === newZoomLevel) { c.setOpacity(1); c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel); //Immediately remove our children as we are replacing them. TODO previousBounds not bounds } else { c.setOpacity(0); } c._addToMap(); } ); }, _recursivelyBecomeVisible: function (bounds, zoomLevel) { this._recursively(bounds, 0, zoomLevel, null, function (c) { c.setOpacity(1); }); }, _recursivelyAddChildrenToMap: function (startPos, zoomLevel, bounds) { this._recursively(bounds, -1, zoomLevel, function (c) { if (zoomLevel === c._zoom) { return; } //Add our child markers at startPos (so they can be animated out) for (var i = c._markers.length - 1; i >= 0; i--) { var nm = c._markers[i]; if (!bounds.contains(nm._latlng)) { continue; } if (startPos) { nm._backupLatlng = nm.getLatLng(); nm.setLatLng(startPos); if (nm.setOpacity) { nm.setOpacity(0); } } c._group._featureGroup.addLayer(nm); } }, function (c) { c._addToMap(startPos); } ); }, _recursivelyRestoreChildPositions: function (zoomLevel) { //Fix positions of child markers for (var i = this._markers.length - 1; i >= 0; i--) { var nm = this._markers[i]; if (nm._backupLatlng) { nm.setLatLng(nm._backupLatlng); delete nm._backupLatlng; } } if (zoomLevel - 1 === this._zoom) { //Reposition child clusters for (var j = this._childClusters.length - 1; j >= 0; j--) { this._childClusters[j]._restorePosition(); } } else { for (var k = this._childClusters.length - 1; k >= 0; k--) { this._childClusters[k]._recursivelyRestoreChildPositions(zoomLevel); } } }, _restorePosition: function () { if (this._backupLatlng) { this.setLatLng(this._backupLatlng); delete this._backupLatlng; } }, //exceptBounds: If set, don't remove any markers/clusters in it _recursivelyRemoveChildrenFromMap: function (previousBounds, zoomLevel, exceptBounds) { var m, i; this._recursively(previousBounds, -1, zoomLevel - 1, function (c) { //Remove markers at every level for (i = c._markers.length - 1; i >= 0; i--) { m = c._markers[i]; if (!exceptBounds || !exceptBounds.contains(m._latlng)) { c._group._featureGroup.removeLayer(m); if (m.setOpacity) { m.setOpacity(1); } } } }, function (c) { //Remove child clusters at just the bottom level for (i = c._childClusters.length - 1; i >= 0; i--) { m = c._childClusters[i]; if (!exceptBounds || !exceptBounds.contains(m._latlng)) { c._group._featureGroup.removeLayer(m); if (m.setOpacity) { m.setOpacity(1); } } } } ); }, //Run the given functions recursively to this and child clusters // boundsToApplyTo: a L.LatLngBounds representing the bounds of what clusters to recurse in to // zoomLevelToStart: zoom level to start running functions (inclusive) // zoomLevelToStop: zoom level to stop running functions (inclusive) // runAtEveryLevel: function that takes an L.MarkerCluster as an argument that should be applied on every level // runAtBottomLevel: function that takes an L.MarkerCluster as an argument that should be applied at only the bottom level _recursively: function (boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel) { var childClusters = this._childClusters, zoom = this._zoom, i, c; if (zoomLevelToStart > zoom) { //Still going down to required depth, just recurse to child clusters for (i = childClusters.length - 1; i >= 0; i--) { c = childClusters[i]; if (boundsToApplyTo.intersects(c._bounds)) { c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel); } } } else { //In required depth if (runAtEveryLevel) { runAtEveryLevel(this); } if (runAtBottomLevel && this._zoom === zoomLevelToStop) { runAtBottomLevel(this); } //TODO: This loop is almost the same as above if (zoomLevelToStop > zoom) { for (i = childClusters.length - 1; i >= 0; i--) { c = childClusters[i]; if (boundsToApplyTo.intersects(c._bounds)) { c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel); } } } } }, _recalculateBounds: function () { var markers = this._markers, childClusters = this._childClusters, i; this._bounds = new L.LatLngBounds(); delete this._wLatLng; for (i = markers.length - 1; i >= 0; i--) { this._expandBounds(markers[i]); } for (i = childClusters.length - 1; i >= 0; i--) { this._expandBounds(childClusters[i]); } }, //Returns true if we are the parent of only one cluster and that cluster is the same as us _isSingleParent: function () { //Don't need to check this._markers as the rest won't work if there are any return this._childClusters.length > 0 && this._childClusters[0]._childCount === this._childCount; } }); L.DistanceGrid = function (cellSize) { this._cellSize = cellSize; this._sqCellSize = cellSize * cellSize; this._grid = {}; this._objectPoint = { }; }; L.DistanceGrid.prototype = { addObject: function (obj, point) { var x = this._getCoord(point.x), y = this._getCoord(point.y), grid = this._grid, row = grid[y] = grid[y] || {}, cell = row[x] = row[x] || [], stamp = L.Util.stamp(obj); this._objectPoint[stamp] = point; cell.push(obj); }, updateObject: function (obj, point) { this.removeObject(obj); this.addObject(obj, point); }, //Returns true if the object was found removeObject: function (obj, point) { var x = this._getCoord(point.x), y = this._getCoord(point.y), grid = this._grid, row = grid[y] = grid[y] || {}, cell = row[x] = row[x] || [], i, len; delete this._objectPoint[L.Util.stamp(obj)]; for (i = 0, len = cell.length; i < len; i++) { if (cell[i] === obj) { cell.splice(i, 1); if (len === 1) { delete row[x]; } return true; } } }, eachObject: function (fn, context) { var i, j, k, len, row, cell, removed, grid = this._grid; for (i in grid) { row = grid[i]; for (j in row) { cell = row[j]; for (k = 0, len = cell.length; k < len; k++) { removed = fn.call(context, cell[k]); if (removed) { k--; len--; } } } } }, getNearObject: function (point) { var x = this._getCoord(point.x), y = this._getCoord(point.y), i, j, k, row, cell, len, obj, dist, objectPoint = this._objectPoint, closestDistSq = this._sqCellSize, closest = null; for (i = y - 1; i <= y + 1; i++) { row = this._grid[i]; if (row) { for (j = x - 1; j <= x + 1; j++) { cell = row[j]; if (cell) { for (k = 0, len = cell.length; k < len; k++) { obj = cell[k]; dist = this._sqDist(objectPoint[L.Util.stamp(obj)], point); if (dist < closestDistSq) { closestDistSq = dist; closest = obj; } } } } } } return closest; }, _getCoord: function (x) { return Math.floor(x / this._cellSize); }, _sqDist: function (p, p2) { var dx = p2.x - p.x, dy = p2.y - p.y; return dx * dx + dy * dy; } }; /* Copyright (c) 2012 the authors listed at the following URL, and/or the authors of referenced articles or incorporated external code: http://en.literateprograms.org/Quickhull_(Javascript)?action=history&offset=20120410175256 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. Retrieved from: http://en.literateprograms.org/Quickhull_(Javascript)?oldid=18434 */ (function () { L.QuickHull = { /* * @param {Object} cpt a point to be measured from the baseline * @param {Array} bl the baseline, as represented by a two-element * array of latlng objects. * @returns {Number} an approximate distance measure */ getDistant: function (cpt, bl) { var vY = bl[1].lat - bl[0].lat, vX = bl[0].lng - bl[1].lng; return (vX * (cpt.lat - bl[0].lat) + vY * (cpt.lng - bl[0].lng)); }, /* * @param {Array} baseLine a two-element array of latlng objects * representing the baseline to project from * @param {Array} latLngs an array of latlng objects * @returns {Object} the maximum point and all new points to stay * in consideration for the hull. */ findMostDistantPointFromBaseLine: function (baseLine, latLngs) { var maxD = 0, maxPt = null, newPoints = [], i, pt, d; for (i = latLngs.length - 1; i >= 0; i--) { pt = latLngs[i]; d = this.getDistant(pt, baseLine); if (d > 0) { newPoints.push(pt); } else { continue; } if (d > maxD) { maxD = d; maxPt = pt; } } return { maxPoint: maxPt, newPoints: newPoints }; }, /* * Given a baseline, compute the convex hull of latLngs as an array * of latLngs. * * @param {Array} latLngs * @returns {Array} */ buildConvexHull: function (baseLine, latLngs) { var convexHullBaseLines = [], t = this.findMostDistantPointFromBaseLine(baseLine, latLngs); if (t.maxPoint) { // if there is still a point "outside" the base line convexHullBaseLines = convexHullBaseLines.concat( this.buildConvexHull([baseLine[0], t.maxPoint], t.newPoints) ); convexHullBaseLines = convexHullBaseLines.concat( this.buildConvexHull([t.maxPoint, baseLine[1]], t.newPoints) ); return convexHullBaseLines; } else { // if there is no more point "outside" the base line, the current base line is part of the convex hull return [baseLine[0]]; } }, /* * Given an array of latlngs, compute a convex hull as an array * of latlngs * * @param {Array} latLngs * @returns {Array} */ getConvexHull: function (latLngs) { // find first baseline var maxLat = false, minLat = false, maxPt = null, minPt = null, i; for (i = latLngs.length - 1; i >= 0; i--) { var pt = latLngs[i]; if (maxLat === false || pt.lat > maxLat) { maxPt = pt; maxLat = pt.lat; } if (minLat === false || pt.lat < minLat) { minPt = pt; minLat = pt.lat; } } var ch = [].concat(this.buildConvexHull([minPt, maxPt], latLngs), this.buildConvexHull([maxPt, minPt], latLngs)); return ch; } }; }()); L.MarkerCluster.include({ getConvexHull: function () { var childMarkers = this.getAllChildMarkers(), points = [], p, i; for (i = childMarkers.length - 1; i >= 0; i--) { p = childMarkers[i].getLatLng(); points.push(p); } return L.QuickHull.getConvexHull(points); } }); //This code is 100% based on https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet //Huge thanks to jawj for implementing it first to make my job easy :-) L.MarkerCluster.include({ _2PI: Math.PI * 2, _circleFootSeparation: 25, //related to circumference of circle _circleStartAngle: Math.PI / 6, _spiralFootSeparation: 28, //related to size of spiral (experiment!) _spiralLengthStart: 11, _spiralLengthFactor: 5, _circleSpiralSwitchover: 9, //show spiral instead of circle from this marker count upwards. // 0 -> always spiral; Infinity -> always circle spiderfy: function () { if (this._group._spiderfied === this || this._group._inZoomAnimation) { return; } var childMarkers = this.getAllChildMarkers(), group = this._group, map = group._map, center = map.latLngToLayerPoint(this._latlng), positions; this._group._unspiderfy(); this._group._spiderfied = this; //TODO Maybe: childMarkers order by distance to center if (childMarkers.length >= this._circleSpiralSwitchover) { positions = this._generatePointsSpiral(childMarkers.length, center); } else { center.y += 10; //Otherwise circles look wrong positions = this._generatePointsCircle(childMarkers.length, center); } this._animationSpiderfy(childMarkers, positions); }, unspiderfy: function (zoomDetails) { /// <param Name="zoomDetails">Argument from zoomanim if being called in a zoom animation or null otherwise</param> if (this._group._inZoomAnimation) { return; } this._animationUnspiderfy(zoomDetails); this._group._spiderfied = null; }, _generatePointsCircle: function (count, centerPt) { var circumference = this._group.options.spiderfyDistanceMultiplier * this._circleFootSeparation * (2 + count), legLength = circumference / this._2PI, //radius from circumference angleStep = this._2PI / count, res = [], i, angle; res.length = count; for (i = count - 1; i >= 0; i--) { angle = this._circleStartAngle + i * angleStep; res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round(); } return res; }, _generatePointsSpiral: function (count, centerPt) { var legLength = this._group.options.spiderfyDistanceMultiplier * this._spiralLengthStart, separation = this._group.options.spiderfyDistanceMultiplier * this._spiralFootSeparation, lengthFactor = this._group.options.spiderfyDistanceMultiplier * this._spiralLengthFactor, angle = 0, res = [], i; res.length = count; for (i = count - 1; i >= 0; i--) { angle += separation / legLength + i * 0.0005; res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round(); legLength += this._2PI * lengthFactor / angle; } return res; }, _noanimationUnspiderfy: function () { var group = this._group, map = group._map, fg = group._featureGroup, childMarkers = this.getAllChildMarkers(), m, i; this.setOpacity(1); for (i = childMarkers.length - 1; i >= 0; i--) { m = childMarkers[i]; fg.removeLayer(m); if (m._preSpiderfyLatlng) { m.setLatLng(m._preSpiderfyLatlng); delete m._preSpiderfyLatlng; } if (m.setZIndexOffset) { m.setZIndexOffset(0); } if (m._spiderLeg) { map.removeLayer(m._spiderLeg); delete m._spiderLeg; } } group._spiderfied = null; } }); L.MarkerCluster.include(!L.DomUtil.TRANSITION ? { //Non Animated versions of everything _animationSpiderfy: function (childMarkers, positions) { var group = this._group, map = group._map, fg = group._featureGroup, i, m, leg, newPos; for (i = childMarkers.length - 1; i >= 0; i--) { newPos = map.layerPointToLatLng(positions[i]); m = childMarkers[i]; m._preSpiderfyLatlng = m._latlng; m.setLatLng(newPos); if (m.setZIndexOffset) { m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING } fg.addLayer(m); leg = new L.Polyline([this._latlng, newPos], { weight: 1.5, color: '#222' }); map.addLayer(leg); m._spiderLeg = leg; } this.setOpacity(0.3); group.fire('spiderfied'); }, _animationUnspiderfy: function () { this._noanimationUnspiderfy(); } } : { //Animated versions here SVG_ANIMATION: (function () { return document.createElementNS('http://www.w3.org/2000/svg', 'animate').toString().indexOf('SVGAnimate') > -1; }()), _animationSpiderfy: function (childMarkers, positions) { var me = this, group = this._group, map = group._map, fg = group._featureGroup, thisLayerPos = map.latLngToLayerPoint(this._latlng), i, m, leg, newPos; //Add markers to map hidden at our center point for (i = childMarkers.length - 1; i >= 0; i--) { m = childMarkers[i]; //If it is a marker, add it now and we'll animate it out if (m.setOpacity) { m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING m.setOpacity(0); fg.addLayer(m); m._setPos(thisLayerPos); } else { //Vectors just get immediately added fg.addLayer(m); } } group._forceLayout(); group._animationStart(); var initialLegOpacity = L.Path.SVG ? 0 : 0.3, xmlns = L.Path.SVG_NS; for (i = childMarkers.length - 1; i >= 0; i--) { newPos = map.layerPointToLatLng(positions[i]); m = childMarkers[i]; //Move marker to new position m._preSpiderfyLatlng = m._latlng; m.setLatLng(newPos); if (m.setOpacity) { m.setOpacity(1); } //Add Legs. leg = new L.Polyline([me._latlng, newPos], { weight: 1.5, color: '#222', opacity: initialLegOpacity }); map.addLayer(leg); m._spiderLeg = leg; //Following animations don't work for canvas if (!L.Path.SVG || !this.SVG_ANIMATION) { continue; } //How this works: //http://stackoverflow.com/questions/5924238/how-do-you-animate-an-svg-path-in-ios //http://dev.opera.com/articles/view/advanced-svg-animation-techniques/ //Animate length var length = leg._path.getTotalLength(); leg._path.setAttribute("stroke-dasharray", length + "," + length); var anim = document.createElementNS(xmlns, "animate"); anim.setAttribute("attributeName", "stroke-dashoffset"); anim.setAttribute("begin", "indefinite"); anim.setAttribute("from", length); anim.setAttribute("to", 0); anim.setAttribute("dur", 0.25); leg._path.appendChild(anim); anim.beginElement(); //Animate opacity anim = document.createElementNS(xmlns, "animate"); anim.setAttribute("attributeName", "stroke-opacity"); anim.setAttribute("attributeName", "stroke-opacity"); anim.setAttribute("begin", "indefinite"); anim.setAttribute("from", 0); anim.setAttribute("to", 0.5); anim.setAttribute("dur", 0.25); leg._path.appendChild(anim); anim.beginElement(); } me.setOpacity(0.3); //Set the opacity of the spiderLegs back to their correct value // The animations above override this until they complete. // If the initial opacity of the spiderlegs isn't 0 then they appear before the animation starts. if (L.Path.SVG) { this._group._forceLayout(); for (i = childMarkers.length - 1; i >= 0; i--) { m = childMarkers[i]._spiderLeg; m.options.opacity = 0.5; m._path.setAttribute('stroke-opacity', 0.5); } } setTimeout(function () { group._animationEnd(); group.fire('spiderfied'); }, 200); }, _animationUnspiderfy: function (zoomDetails) { var group = this._group, map = group._map, fg = group._featureGroup, thisLayerPos = zoomDetails ? map._latLngToNewLayerPoint(this._latlng, zoomDetails.zoom, zoomDetails.center) : map.latLngToLayerPoint(this._latlng), childMarkers = this.getAllChildMarkers(), svg = L.Path.SVG && this.SVG_ANIMATION, m, i, a; group._animationStart(); //Make us visible and bring the child markers back in this.setOpacity(1); for (i = childMarkers.length - 1; i >= 0; i--) { m = childMarkers[i]; //Marker was added to us after we were spidified if (!m._preSpiderfyLatlng) { continue; } //Fix up the location to the real one m.setLatLng(m._preSpiderfyLatlng); delete m._preSpiderfyLatlng; //Hack override the location to be our center if (m.setOpacity) { m._setPos(thisLayerPos); m.setOpacity(0); } else { fg.removeLayer(m); } //Animate the spider legs back in if (svg) { a = m._spiderLeg._path.childNodes[0]; a.setAttribute('to', a.getAttribute('from')); a.setAttribute('from', 0); a.beginElement(); a = m._spiderLeg._path.childNodes[1]; a.setAttribute('from', 0.5); a.setAttribute('to', 0); a.setAttribute('stroke-opacity', 0); a.beginElement(); m._spiderLeg._path.setAttribute('stroke-opacity', 0); } } setTimeout(function () { //If we have only <= one child left then that marker will be shown on the map so don't remove it! var stillThereChildCount = 0; for (i = childMarkers.length - 1; i >= 0; i--) { m = childMarkers[i]; if (m._spiderLeg) { stillThereChildCount++; } } for (i = childMarkers.length - 1; i >= 0; i--) { m = childMarkers[i]; if (!m._spiderLeg) { //Has already been unspiderfied continue; } if (m.setOpacity) { m.setOpacity(1); m.setZIndexOffset(0); } if (stillThereChildCount > 1) { fg.removeLayer(m); } map.removeLayer(m._spiderLeg); delete m._spiderLeg; } group._animationEnd(); }, 200); } }); L.MarkerClusterGroup.include({ //The MarkerCluster currently spiderfied (if any) _spiderfied: null, _spiderfierOnAdd: function () { this._map.on('click', this._unspiderfyWrapper, this); if (this._map.options.zoomAnimation) { this._map.on('zoomstart', this._unspiderfyZoomStart, this); } //Browsers without zoomAnimation or a big zoom don't fire zoomstart this._map.on('zoomend', this._noanimationUnspiderfy, this); if (L.Path.SVG && !L.Browser.touch) { this._map._initPathRoot(); //Needs to happen in the pageload, not after, or animations don't work in webkit // http://stackoverflow.com/questions/8455200/svg-animate-with-dynamically-added-elements //Disable on touch browsers as the animation messes up on a touch zoom and isn't very noticable } }, _spiderfierOnRemove: function () { this._map.off('click', this._unspiderfyWrapper, this); this._map.off('zoomstart', this._unspiderfyZoomStart, this); this._map.off('zoomanim', this._unspiderfyZoomAnim, this); this._unspiderfy(); //Ensure that markers are back where they should be }, //On zoom start we add a zoomanim handler so that we are guaranteed to be last (after markers are animated) //This means we can define the animation they do rather than Markers doing an animation to their actual location _unspiderfyZoomStart: function () { if (!this._map) { //May have been removed from the map by a zoomEnd handler return; } this._map.on('zoomanim', this._unspiderfyZoomAnim, this); }, _unspiderfyZoomAnim: function (zoomDetails) { //Wait until the first zoomanim after the user has finished touch-zooming before running the animation if (L.DomUtil.hasClass(this._map._mapPane, 'leaflet-touching')) { return; } this._map.off('zoomanim', this._unspiderfyZoomAnim, this); this._unspiderfy(zoomDetails); }, _unspiderfyWrapper: function () { /// <summary>_unspiderfy but passes no arguments</summary> this._unspiderfy(); }, _unspiderfy: function (zoomDetails) { if (this._spiderfied) { this._spiderfied.unspiderfy(zoomDetails); } }, _noanimationUnspiderfy: function () { if (this._spiderfied) { this._spiderfied._noanimationUnspiderfy(); } }, //If the given layer is currently being spiderfied then we unspiderfy it so it isn't on the map anymore etc _unspiderfyLayer: function (layer) { if (layer._spiderLeg) { this._featureGroup.removeLayer(layer); layer.setOpacity(1); //Position will be fixed up immediately in _animationUnspiderfy layer.setZIndexOffset(0); this._map.removeLayer(layer._spiderLeg); delete layer._spiderLeg; } } }); }(window, document));
/** * $Id: editor_plugin_src.js 917 2008-09-03 19:08:38Z spocke $ * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ (function() { var DOM = tinymce.DOM, Element = tinymce.dom.Element, Event = tinymce.dom.Event, each = tinymce.each, is = tinymce.is; tinymce.create('tinymce.plugins.InlinePopups', { init : function(ed, url) { // Replace window manager ed.onBeforeRenderUI.add(function() { ed.windowManager = new tinymce.InlineWindowManager(ed); DOM.loadCSS(url + '/skins/' + (ed.settings.inlinepopups_skin || 'clearlooks2') + "/window.css"); }); }, getInfo : function() { return { longname : 'InlinePopups', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/inlinepopups', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); tinymce.create('tinymce.InlineWindowManager:tinymce.WindowManager', { InlineWindowManager : function(ed) { var t = this; t.parent(ed); t.zIndex = 300000; t.count = 0; t.windows = {}; }, open : function(f, p) { var t = this, id, opt = '', ed = t.editor, dw = 0, dh = 0, vp, po, mdf, clf, we, w, u; f = f || {}; p = p || {}; // Run native windows if (!f.inline) return t.parent(f, p); // Only store selection if the type is a normal window if (!f.type) t.bookmark = ed.selection.getBookmark('simple'); id = DOM.uniqueId(); vp = DOM.getViewPort(); f.width = parseInt(f.width || 320); f.height = parseInt(f.height || 240) + (tinymce.isIE ? 8 : 0); f.min_width = parseInt(f.min_width || 150); f.min_height = parseInt(f.min_height || 100); f.max_width = parseInt(f.max_width || 2000); f.max_height = parseInt(f.max_height || 2000); f.left = f.left || Math.round(Math.max(vp.x, vp.x + (vp.w / 2.0) - (f.width / 2.0))); f.top = f.top || Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (f.height / 2.0))); f.movable = f.resizable = true; p.mce_width = f.width; p.mce_height = f.height; p.mce_inline = true; p.mce_window_id = id; p.mce_auto_focus = f.auto_focus; // Transpose // po = DOM.getPos(ed.getContainer()); // f.left -= po.x; // f.top -= po.y; t.features = f; t.params = p; t.onOpen.dispatch(t, f, p); if (f.type) { opt += ' mceModal'; if (f.type) opt += ' mce' + f.type.substring(0, 1).toUpperCase() + f.type.substring(1); f.resizable = false; } if (f.statusbar) opt += ' mceStatusbar'; if (f.resizable) opt += ' mceResizable'; if (f.minimizable) opt += ' mceMinimizable'; if (f.maximizable) opt += ' mceMaximizable'; if (f.movable) opt += ' mceMovable'; // Create DOM objects t._addAll(DOM.doc.body, ['div', {id : id, 'class' : ed.settings.inlinepopups_skin || 'clearlooks2', style : 'width:100px;height:100px'}, ['div', {id : id + '_wrapper', 'class' : 'mceWrapper' + opt}, ['div', {id : id + '_top', 'class' : 'mceTop'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_title'}, f.title || ''] ], ['div', {id : id + '_middle', 'class' : 'mceMiddle'}, ['div', {id : id + '_left', 'class' : 'mceLeft'}], ['span', {id : id + '_content'}], ['div', {id : id + '_right', 'class' : 'mceRight'}] ], ['div', {id : id + '_bottom', 'class' : 'mceBottom'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_status'}, 'Content'] ], ['a', {'class' : 'mceMove', tabindex : '-1', href : 'javascript:;'}], ['a', {'class' : 'mceMin', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMax', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMed', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceClose', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {id : id + '_resize_n', 'class' : 'mceResize mceResizeN', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_s', 'class' : 'mceResize mceResizeS', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_w', 'class' : 'mceResize mceResizeW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_e', 'class' : 'mceResize mceResizeE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_nw', 'class' : 'mceResize mceResizeNW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_ne', 'class' : 'mceResize mceResizeNE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_sw', 'class' : 'mceResize mceResizeSW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_se', 'class' : 'mceResize mceResizeSE', tabindex : '-1', href : 'javascript:;'}] ] ] ); DOM.setStyles(id, {top : -10000, left : -10000}); // Fix gecko rendering bug, where the editors iframe messed with window contents if (tinymce.isGecko) DOM.setStyle(id, 'overflow', 'auto'); // Measure borders if (!f.type) { dw += DOM.get(id + '_left').clientWidth; dw += DOM.get(id + '_right').clientWidth; dh += DOM.get(id + '_top').clientHeight; dh += DOM.get(id + '_bottom').clientHeight; } // Resize window DOM.setStyles(id, {top : f.top, left : f.left, width : f.width + dw, height : f.height + dh}); u = f.url || f.file; if (u) { if (tinymce.relaxedDomain) u += (u.indexOf('?') == -1 ? '?' : '&') + 'mce_rdomain=' + tinymce.relaxedDomain; u = tinymce._addVer(u); } if (!f.type) { DOM.add(id + '_content', 'iframe', {id : id + '_ifr', src : 'javascript:""', frameBorder : 0, style : 'border:0;width:10px;height:10px'}); DOM.setStyles(id + '_ifr', {width : f.width, height : f.height}); DOM.setAttrib(id + '_ifr', 'src', u); } else { DOM.add(id + '_wrapper', 'a', {id : id + '_ok', 'class' : 'mceButton mceOk', href : 'javascript:;', onmousedown : 'return false;'}, 'Ok'); if (f.type == 'confirm') DOM.add(id + '_wrapper', 'a', {'class' : 'mceButton mceCancel', href : 'javascript:;', onmousedown : 'return false;'}, 'Cancel'); DOM.add(id + '_middle', 'div', {'class' : 'mceIcon'}); DOM.setHTML(id + '_content', f.content.replace('\n', '<br />')); } // Register events mdf = Event.add(id, 'mousedown', function(e) { var n = e.target, w, vp; w = t.windows[id]; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { if (n.className == 'mceMax') { w.oldPos = w.element.getXY(); w.oldSize = w.element.getSize(); vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars vp.w -= 2; vp.h -= 2; w.element.moveTo(vp.x, vp.y); w.element.resizeTo(vp.w, vp.h); DOM.setStyles(id + '_ifr', {width : vp.w - w.deltaWidth, height : vp.h - w.deltaHeight}); DOM.addClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMed') { // Reset to old size w.element.moveTo(w.oldPos.x, w.oldPos.y); w.element.resizeTo(w.oldSize.w, w.oldSize.h); w.iframeElement.resizeTo(w.oldSize.w - w.deltaWidth, w.oldSize.h - w.deltaHeight); DOM.removeClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMove') return t._startDrag(id, e, n.className); else if (DOM.hasClass(n, 'mceResize')) return t._startDrag(id, e, n.className.substring(13)); } }); clf = Event.add(id, 'click', function(e) { var n = e.target; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { switch (n.className) { case 'mceClose': t.close(null, id); return Event.cancel(e); case 'mceButton mceOk': case 'mceButton mceCancel': f.button_func(n.className == 'mceButton mceOk'); return Event.cancel(e); } } }); // Add window w = t.windows[id] = { id : id, mousedown_func : mdf, click_func : clf, element : new Element(id, {blocker : 1, container : ed.getContainer()}), iframeElement : new Element(id + '_ifr'), features : f, deltaWidth : dw, deltaHeight : dh }; w.iframeElement.on('focus', function() { t.focus(id); }); // Setup blocker if (t.count == 0 && t.editor.getParam('dialog_type', 'modal') == 'modal') { DOM.add(DOM.doc.body, 'div', { id : 'mceModalBlocker', 'class' : (t.editor.settings.inlinepopups_skin || 'clearlooks2') + '_modalBlocker', style : {zIndex : t.zIndex - 1} }); DOM.show('mceModalBlocker'); // Reduces flicker in IE } else DOM.setStyle('mceModalBlocker', 'z-index', t.zIndex - 1); if (tinymce.isIE6 || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceModalBlocker', {position : 'absolute', width : vp.w - 2, height : vp.h - 2}); t.focus(id); t._fixIELayout(id, 1); // Focus ok button if (DOM.get(id + '_ok')) DOM.get(id + '_ok').focus(); t.count++; return w; }, focus : function(id) { var t = this, w; if (w = t.windows[id]) { w.zIndex = this.zIndex++; w.element.setStyle('zIndex', w.zIndex); w.element.update(); id = id + '_wrapper'; DOM.removeClass(t.lastId, 'mceFocus'); DOM.addClass(id, 'mceFocus'); t.lastId = id; } }, _addAll : function(te, ne) { var i, n, t = this, dom = tinymce.DOM; if (is(ne, 'string')) te.appendChild(dom.doc.createTextNode(ne)); else if (ne.length) { te = te.appendChild(dom.create(ne[0], ne[1])); for (i=2; i<ne.length; i++) t._addAll(te, ne[i]); } }, _startDrag : function(id, se, ac) { var t = this, mu, mm, d = DOM.doc, eb, w = t.windows[id], we = w.element, sp = we.getXY(), p, sz, ph, cp, vp, sx, sy, sex, sey, dx, dy, dw, dh; // Get positons and sizes // cp = DOM.getPos(t.editor.getContainer()); cp = {x : 0, y : 0}; vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars while dragging vp.w -= 2; vp.h -= 2; sex = se.screenX; sey = se.screenY; dx = dy = dw = dh = 0; // Handle mouse up mu = Event.add(d, 'mouseup', function(e) { Event.remove(d, 'mouseup', mu); Event.remove(d, 'mousemove', mm); if (eb) eb.remove(); we.moveBy(dx, dy); we.resizeBy(dw, dh); sz = we.getSize(); DOM.setStyles(id + '_ifr', {width : sz.w - w.deltaWidth, height : sz.h - w.deltaHeight}); t._fixIELayout(id, 1); return Event.cancel(e); }); if (ac != 'Move') startMove(); function startMove() { if (eb) return; t._fixIELayout(id, 0); // Setup event blocker DOM.add(d.body, 'div', { id : 'mceEventBlocker', 'class' : 'mceEventBlocker ' + (t.editor.settings.inlinepopups_skin || 'clearlooks2'), style : {zIndex : t.zIndex + 1} }); if (tinymce.isIE6 || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceEventBlocker', {position : 'absolute', width : vp.w - 2, height : vp.h - 2}); eb = new Element('mceEventBlocker'); eb.update(); // Setup placeholder p = we.getXY(); sz = we.getSize(); sx = cp.x + p.x - vp.x; sy = cp.y + p.y - vp.y; DOM.add(eb.get(), 'div', {id : 'mcePlaceHolder', 'class' : 'mcePlaceHolder', style : {left : sx, top : sy, width : sz.w, height : sz.h}}); ph = new Element('mcePlaceHolder'); }; // Handle mouse move/drag mm = Event.add(d, 'mousemove', function(e) { var x, y, v; startMove(); x = e.screenX - sex; y = e.screenY - sey; switch (ac) { case 'ResizeW': dx = x; dw = 0 - x; break; case 'ResizeE': dw = x; break; case 'ResizeN': case 'ResizeNW': case 'ResizeNE': if (ac == "ResizeNW") { dx = x; dw = 0 - x; } else if (ac == "ResizeNE") dw = x; dy = y; dh = 0 - y; break; case 'ResizeS': case 'ResizeSW': case 'ResizeSE': if (ac == "ResizeSW") { dx = x; dw = 0 - x; } else if (ac == "ResizeSE") dw = x; dh = y; break; case 'mceMove': dx = x; dy = y; break; } // Boundary check if (dw < (v = w.features.min_width - sz.w)) { if (dx !== 0) dx += dw - v; dw = v; } if (dh < (v = w.features.min_height - sz.h)) { if (dy !== 0) dy += dh - v; dh = v; } dw = Math.min(dw, w.features.max_width - sz.w); dh = Math.min(dh, w.features.max_height - sz.h); dx = Math.max(dx, vp.x - (sx + vp.x)); dy = Math.max(dy, vp.y - (sy + vp.y)); dx = Math.min(dx, (vp.w + vp.x) - (sx + sz.w + vp.x)); dy = Math.min(dy, (vp.h + vp.y) - (sy + sz.h + vp.y)); // Move if needed if (dx + dy !== 0) { if (sx + dx < 0) dx = 0; if (sy + dy < 0) dy = 0; ph.moveTo(sx + dx, sy + dy); } // Resize if needed if (dw + dh !== 0) ph.resizeTo(sz.w + dw, sz.h + dh); return Event.cancel(e); }); return Event.cancel(se); }, resizeBy : function(dw, dh, id) { var w = this.windows[id]; if (w) { w.element.resizeBy(dw, dh); w.iframeElement.resizeBy(dw, dh); } }, close : function(win, id) { var t = this, w, d = DOM.doc, ix = 0, fw, id; id = t._findId(id || win); // Probably not inline if (!t.windows[id]) { t.parent(win); return; } t.count--; if (t.count == 0) DOM.remove('mceModalBlocker'); if (w = t.windows[id]) { t.onClose.dispatch(t); Event.remove(d, 'mousedown', w.mousedownFunc); Event.remove(d, 'click', w.clickFunc); Event.clear(id); Event.clear(id + '_ifr'); DOM.setAttrib(id + '_ifr', 'src', 'javascript:""'); // Prevent leak w.element.remove(); delete t.windows[id]; // Find front most window and focus that each (t.windows, function(w) { if (w.zIndex > ix) { fw = w; ix = w.zIndex; } }); if (fw) t.focus(fw.id); } }, setTitle : function(w, ti) { var e; w = this._findId(w); if (e = DOM.get(w + '_title')) e.innerHTML = DOM.encode(ti); }, alert : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'alert', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, confirm : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'confirm', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, // Internal functions _findId : function(w) { var t = this; if (typeof(w) == 'string') return w; each(t.windows, function(wo) { var ifr = DOM.get(wo.id + '_ifr'); if (ifr && w == ifr.contentWindow) { w = wo.id; return false; } }); return w; }, _fixIELayout : function(id, s) { var w, img; if (!tinymce.isIE6) return; // Fixes the bug where hover flickers and does odd things in IE6 each(['n','s','w','e','nw','ne','sw','se'], function(v) { var e = DOM.get(id + '_resize_' + v); DOM.setStyles(e, { width : s ? e.clientWidth : '', height : s ? e.clientHeight : '', cursor : DOM.getStyle(e, 'cursor', 1) }); DOM.setStyle(id + "_bottom", 'bottom', '-1px'); e = 0; }); // Fixes graphics glitch if (w = this.windows[id]) { // Fixes rendering bug after resize w.element.hide(); w.element.show(); // Forced a repaint of the window //DOM.get(id).style.filter = ''; // IE has a bug where images used in CSS won't get loaded // sometimes when the cache in the browser is disabled // This fix tries to solve it by loading the images using the image object each(DOM.select('div,a', id), function(e, i) { if (e.currentStyle.backgroundImage != 'none') { img = new Image(); img.src = e.currentStyle.backgroundImage.replace(/url\(\"(.+)\"\)/, '$1'); } }); DOM.get(id).style.filter = ''; } } }); // Register plugin tinymce.PluginManager.add('inlinepopups', tinymce.plugins.InlinePopups); })();
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'specialchar', 'ru', { options: 'Выбор специального символа', title: 'Выберите специальный символ', toolbar: 'Вставить специальный символ' } );
'use strict'; var Utils = require('../../utils'); /** Returns an object that treats SQLite's inabilities to do certain queries. @class QueryInterface @static */ var QueryInterface = module.exports = { /** A wrapper that fixes SQLite's inability to remove columns from existing tables. It will create a backup of the table, drop the table afterwards and create a new table with the same name but without the obsolete column. @method removeColumn @for QueryInterface @param {String} tableName The name of the table. @param {String} attributeName The name of the attribute that we want to remove. @param {CustomEventEmitter} emitter The EventEmitter from outside. @param {Function} queryAndEmit The function from outside that triggers some events to get triggered. @since 1.6.0 */ removeColumn: function(tableName, attributeName) { var self = this; return this.describeTable(tableName).then(function(fields) { delete fields[attributeName]; var sql = self.QueryGenerator.removeColumnQuery(tableName, fields) , subQueries = sql.split(';').filter(function(q) { return q !== ''; }); return Utils.Promise.reduce(subQueries, function(total, subQuery) { return self.sequelize.query(subQuery + ';', null, { raw: true}); }, null); }); }, /** A wrapper that fixes SQLite's inability to change columns from existing tables. It will create a backup of the table, drop the table afterwards and create a new table with the same name but with a modified version of the respective column. @method changeColumn @for QueryInterface @param {String} tableName The name of the table. @param {Object} attributes An object with the attribute's name as key and it's options as value object. @param {CustomEventEmitter} emitter The EventEmitter from outside. @param {Function} queryAndEmit The function from outside that triggers some events to get triggered. @since 1.6.0 */ changeColumn: function(tableName, attributes) { var attributeName = Utils._.keys(attributes)[0] , self = this; return this.describeTable(tableName).then(function(fields) { fields[attributeName] = attributes[attributeName]; var sql = self.QueryGenerator.removeColumnQuery(tableName, fields) , subQueries = sql.split(';').filter(function(q) { return q !== ''; }); return Utils.Promise.reduce(subQueries, function(total, subQuery) { return self.sequelize.query(subQuery + ';', null, { raw: true}); }, null); }); }, /** A wrapper that fixes SQLite's inability to rename columns from existing tables. It will create a backup of the table, drop the table afterwards and create a new table with the same name but with a renamed version of the respective column. @method renameColumn @for QueryInterface @param {String} tableName The name of the table. @param {String} attrNameBefore The name of the attribute before it was renamed. @param {String} attrNameAfter The name of the attribute after it was renamed. @param {CustomEventEmitter} emitter The EventEmitter from outside. @param {Function} queryAndEmit The function from outside that triggers some events to get triggered. @since 1.6.0 */ renameColumn: function(tableName, attrNameBefore, attrNameAfter) { var self = this; return this.describeTable(tableName).then(function(fields) { fields[attrNameAfter] = Utils._.clone(fields[attrNameBefore]); delete fields[attrNameBefore]; var sql = self.QueryGenerator.renameColumnQuery(tableName, attrNameBefore, attrNameAfter, fields) , subQueries = sql.split(';').filter(function(q) { return q !== ''; }); return Utils.Promise.reduce(subQueries, function(total, subQuery) { return self.sequelize.query(subQuery + ';', null, { raw: true}); }, null); }); } };
//>>built define("dojox/widget/nls/id/FilePicker",({name:"Nama",path:"Jalur",size:"Ukuran (dalam byte)"}));
$(function() { $("#modal-1").on("change", function() { if ($(this).is(":checked")) { $("body").addClass("modal-open"); } else { $("body").removeClass("modal-open"); } }); $(".modal-fade-screen, .modal-close").on("click", function() { $(".modal-state:checked").prop("checked", false).change(); }); $(".modal-inner").on("click", function(e) { e.stopPropagation(); }); });
/*! * Vue.js v2.6.11 * (c) 2014-2019 Evan You * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.Vue = factory()); }(this, function () { 'use strict'; /* */ var emptyObject = Object.freeze({}); // These helpers produce better VM code in JS engines due to their // explicitness and function inlining. function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive. */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || // $flow-disable-line typeof value === 'symbol' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value, e.g., [object Object]. */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } function isPromise (val) { return ( isDef(val) && typeof val.then === 'function' && typeof val.catch === 'function' ) } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) ? JSON.stringify(val, null, 2) : String(val) } /** * Convert an input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if an attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array. */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether an object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase() }); /** * Simple bind polyfill for environments that do not support it, * e.g., PhantomJS 1.x. Technically, we don't need this anymore * since native bind is now performant enough in most browsers. * But removing it would mean breaking code that was able to run in * PhantomJS 1.x, so this must be kept for backward compatibility. */ /* istanbul ignore next */ function polyfillBind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } boundFn._length = fn.length; return boundFn } function nativeBind (fn, ctx) { return fn.bind(ctx) } var bind = Function.prototype.bind ? nativeBind : polyfillBind; /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /* eslint-disable no-unused-vars */ /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/). */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /* eslint-enable no-unused-vars */ /** * Return the same value. */ var identity = function (_) { return _; }; /** * Generate a string containing static keys from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime() } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } /** * Return the first index at which a loosely equal value can be * found in the array (if value is a plain object, the array must * contain an object of the same shape), or -1 if it is not present. */ function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured', 'serverPrefetch' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ // $flow-disable-line optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: "development" !== 'production', /** * Whether to enable devtools */ devtools: "development" !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ // $flow-disable-line keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Perform updates asynchronously. Intended to be used by Vue Test Utils * This will significantly reduce performance if set to false. */ async: true, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }); /* */ /** * unicode letters used for parsing html tags, component names and property paths. * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname * skipping \u10000-\uEFFFF due to it freezing up PhantomJS */ var unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/; /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]")); function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android'); var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; var isPhantomJS = UA && /phantomjs/.test(UA); var isFF = UA && UA.match(/firefox\/(\d+)/); // Firefox has a "watch" function on Object.prototype... var nativeWatch = ({}).watch; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && !inWeex && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'] && global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); var _Set; /* istanbul ignore if */ // $flow-disable-line if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = /*@__PURE__*/(function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var warn = noop; var tip = noop; var generateComponentTrace = (noop); // work around flow check var formatComponentName = (noop); { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { var trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(("[Vue warn]: " + msg + trace)); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '<Root>' } var options = typeof vm === 'function' && vm.cid != null ? vm.options : vm._isVue ? vm.$options || vm.constructor.options : vm; var name = options.name || options._componentTag; var file = options.__file; if (!name && file) { var match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ("<" + (classify(name)) + ">") : "<Anonymous>") + (file && includeFile !== false ? (" at " + file) : '') ) }; var repeat = function (str, n) { var res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res }; generateComponentTrace = function (vm) { if (vm._isVue && vm.$parent) { var tree = []; var currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { var last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); if (!config.async) { // subs aren't sorted in scheduler if not running async // we need to sort them now to make sure they fire in correct // order subs.sort(function (a, b) { return a.id - b.id; }); } for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // The current target watcher being evaluated. // This is globally unique because only one watcher // can be evaluated at a time. Dep.target = null; var targetStack = []; function pushTarget (target) { targetStack.push(target); Dep.target = target; } function popTarget () { targetStack.pop(); Dep.target = targetStack[targetStack.length - 1]; } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.fnContext = undefined; this.fnOptions = undefined; this.fnScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function (text) { if ( text === void 0 ) text = ''; var node = new VNode(); node.text = text; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, // #7975 // clone children array to avoid mutating original in case of cloning // a child. vnode.children && vnode.children.slice(), vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.fnContext = vnode.fnContext; cloned.fnOptions = vnode.fnOptions; cloned.fnScopeId = vnode.fnScopeId; cloned.asyncMeta = vnode.asyncMeta; cloned.isCloned = true; return cloned } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto); var methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ]; /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * In some cases we may want to disable observation inside a component's * update computation. */ var shouldObserve = true; function toggleObserving (value) { shouldObserve = value; } /** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { if (hasProto) { protoAugment(value, arrayMethods); } else { copyAugment(value, arrayMethods, arrayKeys); } this.observeArray(value); } else { this.walk(value); } }; /** * Walk through all properties and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment a target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment a target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive$$1 ( obj, key, val, customSetter, shallow ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; if ((!getter || setter) && arguments.length === 2) { val = obj[key]; } var childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (customSetter) { customSetter(); } // #7981: for accessor properties without setter if (getter && !setter) { return } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (isUndef(target) || isPrimitive(target) ) { warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (key in target && !(key in Object.prototype)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (isUndef(target) || isPrimitive(target) ) { warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = hasSymbol ? Reflect.ownKeys(from) : Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; // in case the object is already observed... if (key === '__ob__') { continue } toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if ( toVal !== fromVal && isPlainObject(toVal) && isPlainObject(fromVal) ) { mergeData(toVal, fromVal); } } return to } /** * Data */ function mergeDataOrFn ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this, this) : childVal, typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal ) } } else { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm, vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm, vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } strats.data = function ( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } return mergeDataOrFn(parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { var res = childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal; return res ? dedupeHooks(res) : res } function dedupeHooks (hooks) { var res = []; for (var i = 0; i < hooks.length; i++) { if (res.indexOf(hooks[i]) === -1) { res.push(hooks[i]); } } return res } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets ( parentVal, childVal, vm, key ) { var res = Object.create(parentVal || null); if (childVal) { assertObjectType(key, childVal, vm); return extend(res, childVal) } else { return res } } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function ( parentVal, childVal, vm, key ) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key$1 in childVal) { var parent = ret[key$1]; var child = childVal[key$1]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function ( parentVal, childVal, vm, key ) { if (childVal && "development" !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); if (childVal) { extend(ret, childVal); } return ret }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { validateComponentName(key); } } function validateComponentName (name) { if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'should conform to valid custom element name in html5 specification.' ); } if (isBuiltInTag(name) || config.isReservedTag(name)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + name ); } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else { warn( "Invalid value for option \"props\": expected an Array or an Object, " + "but got " + (toRawType(props)) + ".", vm ); } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options, vm) { var inject = options.inject; if (!inject) { return } var normalized = options.inject = {}; if (Array.isArray(inject)) { for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = { from: inject[i] }; } } else if (isPlainObject(inject)) { for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else { warn( "Invalid value for option \"inject\": expected an Array or an Object, " + "but got " + (toRawType(inject)) + ".", vm ); } } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def$$1 = dirs[key]; if (typeof def$$1 === 'function') { dirs[key] = { bind: def$$1, update: def$$1 }; } } } } function assertObjectType (name, value, vm) { if (!isPlainObject(value)) { warn( "Invalid value for option \"" + name + "\": expected an Object, " + "but got " + (toRawType(value)) + ".", vm ); } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); normalizeDirectives(child); // Apply extends and mixins on the child options, // but only if it is a raw options object that isn't // the result of another mergeOptions call. // Only merged options has the _base property. if (!child._base) { if (child.extends) { parent = mergeOptions(parent, child.extends, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // boolean casting var booleanIndex = getTypeIndex(Boolean, prop.type); if (booleanIndex > -1) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (value === '' || value === hyphenate(key)) { // only cast empty string / same name to boolean if // boolean has higher priority var stringIndex = getTypeIndex(String, prop.type); if (stringIndex < 0 || booleanIndex < stringIndex) { value = true; } } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldObserve = shouldObserve; toggleObserving(true); observe(value); toggleObserving(prevShouldObserve); } { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( getInvalidTypeMessage(name, value, expectedTypes), vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { var t = typeof value; valid = t === expectedType.toLowerCase(); // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type; } } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isSameType (a, b) { return getType(a) === getType(b) } function getTypeIndex (type, expectedTypes) { if (!Array.isArray(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1 } for (var i = 0, len = expectedTypes.length; i < len; i++) { if (isSameType(expectedTypes[i], type)) { return i } } return -1 } function getInvalidTypeMessage (name, value, expectedTypes) { var message = "Invalid prop: type check failed for prop \"" + name + "\"." + " Expected " + (expectedTypes.map(capitalize).join(', ')); var expectedType = expectedTypes[0]; var receivedType = toRawType(value); var expectedValue = styleValue(value, expectedType); var receivedValue = styleValue(value, receivedType); // check if we need to specify expected value if (expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType)) { message += " with value " + expectedValue; } message += ", got " + receivedType + " "; // check if we need to specify received value if (isExplicable(receivedType)) { message += "with value " + receivedValue + "."; } return message } function styleValue (value, type) { if (type === 'String') { return ("\"" + value + "\"") } else if (type === 'Number') { return ("" + (Number(value))) } else { return ("" + value) } } function isExplicable (value) { var explicitTypes = ['string', 'number', 'boolean']; return explicitTypes.some(function (elem) { return value.toLowerCase() === elem; }) } function isBoolean () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; }) } /* */ function handleError (err, vm, info) { // Deactivate deps tracking while processing error handler to avoid possible infinite rendering. // See: https://github.com/vuejs/vuex/issues/1505 pushTarget(); try { if (vm) { var cur = vm; while ((cur = cur.$parent)) { var hooks = cur.$options.errorCaptured; if (hooks) { for (var i = 0; i < hooks.length; i++) { try { var capture = hooks[i].call(cur, err, vm, info) === false; if (capture) { return } } catch (e) { globalHandleError(e, cur, 'errorCaptured hook'); } } } } } globalHandleError(err, vm, info); } finally { popTarget(); } } function invokeWithErrorHandling ( handler, context, args, vm, info ) { var res; try { res = args ? handler.apply(context, args) : handler.call(context); if (res && !res._isVue && isPromise(res) && !res._handled) { res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); }); // issue #9511 // avoid catch triggering multiple times when nested calls res._handled = true; } } catch (e) { handleError(e, vm, info); } return res } function globalHandleError (err, vm, info) { if (config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { // if the user intentionally throws the original error in the handler, // do not log it twice if (e !== err) { logError(e, null, 'config.errorHandler'); } } } logError(err, vm, info); } function logError (err, vm, info) { { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ if ((inBrowser || inWeex) && typeof console !== 'undefined') { console.error(err); } else { throw err } } /* */ var isUsingMicroTask = false; var callbacks = []; var pending = false; function flushCallbacks () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // Here we have async deferring wrappers using microtasks. // In 2.5 we used (macro) tasks (in combination with microtasks). // However, it has subtle problems when state is changed right before repaint // (e.g. #6813, out-in transitions). // Also, using (macro) tasks in event handler would cause some weird behaviors // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109). // So we now use microtasks everywhere, again. // A major drawback of this tradeoff is that there are some scenarios // where microtasks have too high a priority and fire in between supposedly // sequential events (e.g. #4521, #6690, which have workarounds) // or even between bubbling of the same event (#6566). var timerFunc; // The nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore next, $flow-disable-line */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); timerFunc = function () { p.then(flushCallbacks); // In problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; isUsingMicroTask = true; } else if (!isIE && typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // Use MutationObserver where native Promise is not available, // e.g. PhantomJS, iOS7, Android 4.4 // (#6466 MutationObserver is unreliable in IE11) var counter = 1; var observer = new MutationObserver(flushCallbacks); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; isUsingMicroTask = true; } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { // Fallback to setImmediate. // Technically it leverages the (macro) task queue, // but it is still a better choice than setTimeout. timerFunc = function () { setImmediate(flushCallbacks); }; } else { // Fallback to setTimeout. timerFunc = function () { setTimeout(flushCallbacks, 0); }; } function nextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } /* */ var mark; var measure; { var perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function (tag) { return perf.mark(tag); }; measure = function (name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); // perf.clearMeasures(name) }; } } /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + 'referenced during render. Make sure that this property is reactive, ' + 'either in the data option, or for class-based components, by ' + 'initializing the property. ' + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target ); }; var warnReservedPrefix = function (target, key) { warn( "Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " + 'properties starting with "$" or "_" are not proxied in the Vue instance to ' + 'prevent conflicts with Vue internals. ' + 'See: https://vuejs.org/v2/api/#data', target ); }; var hasProxy = typeof Proxy !== 'undefined' && isNative(Proxy); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data)); if (!has && !isAllowed) { if (key in target.$data) { warnReservedPrefix(target, key); } else { warnNonPresent(target, key); } } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { if (key in target.$data) { warnReservedPrefix(target, key); } else { warnNonPresent(target, key); } } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var seenObjects = new _Set(); /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ function traverse (val) { _traverse(val, seenObjects); seenObjects.clear(); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns, vm) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { var cloned = fns.slice(); for (var i = 0; i < cloned.length; i++) { invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler"); } } else { // return handler return value for single handlers return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler") } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, createOnceHandler, vm ) { var name, def$$1, cur, old, event; for (name in on) { def$$1 = cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur, vm); } if (isTrue(event.once)) { cur = on[name] = createOnceHandler(event.name, cur, event.capture); } add(event.name, cur, event.capture, event.passive, event.params); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { if (def instanceof VNode) { def = def.data.hook || (def.data.hook = {}); } var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); { var keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( "Prop \"" + keyInLowerCase + "\" is passed to component " + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + " \"" + key + "\". " + "Note that HTML attributes are case-insensitive and camelCased " + "props need to use their kebab-case equivalents when using in-DOM " + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function isTextNode (node) { return isDef(node) && isDef(node.text) && isFalse(node.isComment) } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, lastIndex, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue } lastIndex = res.length - 1; last = res[lastIndex]; // nested if (Array.isArray(c)) { if (c.length > 0) { c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)); // merge adjacent text nodes if (isTextNode(c[0]) && isTextNode(last)) { res[lastIndex] = createTextVNode(last.text + (c[0]).text); c.shift(); } res.push.apply(res, c); } } else if (isPrimitive(c)) { if (isTextNode(last)) { // merge adjacent text nodes // this is necessary for SSR hydration because text nodes are // essentially merged when rendered to HTML strings res[lastIndex] = createTextVNode(last.text + c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[lastIndex] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function initProvide (vm) { var provide = vm.$options.provide; if (provide) { vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } } function initInjections (vm) { var result = resolveInject(vm.$options.inject, vm); if (result) { toggleObserving(false); Object.keys(result).forEach(function (key) { /* istanbul ignore else */ { defineReactive$$1(vm, key, result[key], function () { warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + "injection being mutated: \"" + key + "\"", vm ); }); } }); toggleObserving(true); } } function resolveInject (inject, vm) { if (inject) { // inject is :any because flow is not smart enough to figure out cached var result = Object.create(null); var keys = hasSymbol ? Reflect.ownKeys(inject) : Object.keys(inject); for (var i = 0; i < keys.length; i++) { var key = keys[i]; // #6574 in case the inject object is observed... if (key === '__ob__') { continue } var provideKey = inject[key].from; var source = vm; while (source) { if (source._provided && hasOwn(source._provided, provideKey)) { result[key] = source._provided[provideKey]; break } source = source.$parent; } if (!source) { if ('default' in inject[key]) { var provideDefault = inject[key].default; result[key] = typeof provideDefault === 'function' ? provideDefault.call(vm) : provideDefault; } else { warn(("Injection \"" + key + "\" not found"), vm); } } } return result } } /* */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ function resolveSlots ( children, context ) { if (!children || !children.length) { return {} } var slots = {}; for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var data = child.data; // remove slot attribute if the node is resolved as a Vue slot node if (data && data.attrs && data.attrs.slot) { delete data.attrs.slot; } // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.fnContext === context) && data && data.slot != null ) { var name = data.slot; var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children || []); } else { slot.push(child); } } else { (slots.default || (slots.default = [])).push(child); } } // ignore slots that contains only whitespace for (var name$1 in slots) { if (slots[name$1].every(isWhitespace)) { delete slots[name$1]; } } return slots } function isWhitespace (node) { return (node.isComment && !node.asyncFactory) || node.text === ' ' } /* */ function normalizeScopedSlots ( slots, normalSlots, prevSlots ) { var res; var hasNormalSlots = Object.keys(normalSlots).length > 0; var isStable = slots ? !!slots.$stable : !hasNormalSlots; var key = slots && slots.$key; if (!slots) { res = {}; } else if (slots._normalized) { // fast path 1: child component re-render only, parent did not change return slots._normalized } else if ( isStable && prevSlots && prevSlots !== emptyObject && key === prevSlots.$key && !hasNormalSlots && !prevSlots.$hasNormal ) { // fast path 2: stable scoped slots w/ no normal slots to proxy, // only need to normalize once return prevSlots } else { res = {}; for (var key$1 in slots) { if (slots[key$1] && key$1[0] !== '$') { res[key$1] = normalizeScopedSlot(normalSlots, key$1, slots[key$1]); } } } // expose normal slots on scopedSlots for (var key$2 in normalSlots) { if (!(key$2 in res)) { res[key$2] = proxyNormalSlot(normalSlots, key$2); } } // avoriaz seems to mock a non-extensible $scopedSlots object // and when that is passed down this would cause an error if (slots && Object.isExtensible(slots)) { (slots)._normalized = res; } def(res, '$stable', isStable); def(res, '$key', key); def(res, '$hasNormal', hasNormalSlots); return res } function normalizeScopedSlot(normalSlots, key, fn) { var normalized = function () { var res = arguments.length ? fn.apply(null, arguments) : fn({}); res = res && typeof res === 'object' && !Array.isArray(res) ? [res] // single vnode : normalizeChildren(res); return res && ( res.length === 0 || (res.length === 1 && res[0].isComment) // #9658 ) ? undefined : res }; // this is a slot using the new v-slot syntax without scope. although it is // compiled as a scoped slot, render fn users would expect it to be present // on this.$slots because the usage is semantically a normal slot. if (fn.proxy) { Object.defineProperty(normalSlots, key, { get: normalized, enumerable: true, configurable: true }); } return normalized } function proxyNormalSlot(slots, key) { return function () { return slots[key]; } } /* */ /** * Runtime helper for rendering v-for lists. */ function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { if (hasSymbol && val[Symbol.iterator]) { ret = []; var iterator = val[Symbol.iterator](); var result = iterator.next(); while (!result.done) { ret.push(render(result.value, ret.length)); result = iterator.next(); } } else { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } } if (!isDef(ret)) { ret = []; } (ret)._isVList = true; return ret } /* */ /** * Runtime helper for rendering <slot> */ function renderSlot ( name, fallback, props, bindObject ) { var scopedSlotFn = this.$scopedSlots[name]; var nodes; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { if (!isObject(bindObject)) { warn( 'slot v-bind without argument expects an Object', this ); } props = extend(extend({}, bindObject), props); } nodes = scopedSlotFn(props) || fallback; } else { nodes = this.$slots[name] || fallback; } var target = props && props.slot; if (target) { return this.$createElement('template', { slot: target }, nodes) } else { return nodes } } /* */ /** * Runtime helper for resolving filters */ function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } /* */ function isKeyNotMatch (expect, actual) { if (Array.isArray(expect)) { return expect.indexOf(actual) === -1 } else { return expect !== actual } } /** * Runtime helper for checking keyCodes from config. * exposed as Vue.prototype._k * passing in eventKeyName as last argument separately for backwards compat */ function checkKeyCodes ( eventKeyCode, key, builtInKeyCode, eventKeyName, builtInKeyName ) { var mappedKeyCode = config.keyCodes[key] || builtInKeyCode; if (builtInKeyName && eventKeyName && !config.keyCodes[key]) { return isKeyNotMatch(builtInKeyName, eventKeyName) } else if (mappedKeyCode) { return isKeyNotMatch(mappedKeyCode, eventKeyCode) } else if (eventKeyName) { return hyphenate(eventKeyName) !== key } } /* */ /** * Runtime helper for merging v-bind="object" into a VNode's data. */ function bindObjectProps ( data, tag, value, asProp, isSync ) { if (value) { if (!isObject(value)) { warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } var hash; var loop = function ( key ) { if ( key === 'class' || key === 'style' || isReservedAttribute(key) ) { hash = data; } else { var type = data.attrs && data.attrs.type; hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); } var camelizedKey = camelize(key); var hyphenatedKey = hyphenate(key); if (!(camelizedKey in hash) && !(hyphenatedKey in hash)) { hash[key] = value[key]; if (isSync) { var on = data.on || (data.on = {}); on[("update:" + key)] = function ($event) { value[key] = $event; }; } } }; for (var key in value) loop( key ); } } return data } /* */ /** * Runtime helper for rendering static trees. */ function renderStatic ( index, isInFor ) { var cached = this._staticTrees || (this._staticTrees = []); var tree = cached[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree. if (tree && !isInFor) { return tree } // otherwise, render a fresh tree. tree = cached[index] = this.$options.staticRenderFns[index].call( this._renderProxy, null, this // for render fns generated for functional component templates ); markStatic(tree, ("__static__" + index), false); return tree } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree } function markStatic ( tree, key, isOnce ) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } /* */ function bindObjectListeners (data, value) { if (value) { if (!isPlainObject(value)) { warn( 'v-on without argument expects an Object value', this ); } else { var on = data.on = data.on ? extend({}, data.on) : {}; for (var key in value) { var existing = on[key]; var ours = value[key]; on[key] = existing ? [].concat(existing, ours) : ours; } } } return data } /* */ function resolveScopedSlots ( fns, // see flow/vnode res, // the following are added in 2.6 hasDynamicKeys, contentHashKey ) { res = res || { $stable: !hasDynamicKeys }; for (var i = 0; i < fns.length; i++) { var slot = fns[i]; if (Array.isArray(slot)) { resolveScopedSlots(slot, res, hasDynamicKeys); } else if (slot) { // marker for reverse proxying v-slot without scope on this.$slots if (slot.proxy) { slot.fn.proxy = true; } res[slot.key] = slot.fn; } } if (contentHashKey) { (res).$key = contentHashKey; } return res } /* */ function bindDynamicKeys (baseObj, values) { for (var i = 0; i < values.length; i += 2) { var key = values[i]; if (typeof key === 'string' && key) { baseObj[values[i]] = values[i + 1]; } else if (key !== '' && key !== null) { // null is a special value for explicitly removing a binding warn( ("Invalid value for dynamic directive argument (expected string or null): " + key), this ); } } return baseObj } // helper to dynamically append modifier runtime markers to event names. // ensure only append when value is already string, otherwise it will be cast // to string and cause the type check to miss. function prependModifier (value, symbol) { return typeof value === 'string' ? symbol + value : value } /* */ function installRenderHelpers (target) { target._o = markOnce; target._n = toNumber; target._s = toString; target._l = renderList; target._t = renderSlot; target._q = looseEqual; target._i = looseIndexOf; target._m = renderStatic; target._f = resolveFilter; target._k = checkKeyCodes; target._b = bindObjectProps; target._v = createTextVNode; target._e = createEmptyVNode; target._u = resolveScopedSlots; target._g = bindObjectListeners; target._d = bindDynamicKeys; target._p = prependModifier; } /* */ function FunctionalRenderContext ( data, props, children, parent, Ctor ) { var this$1 = this; var options = Ctor.options; // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var contextVm; if (hasOwn(parent, '_uid')) { contextVm = Object.create(parent); // $flow-disable-line contextVm._original = parent; } else { // the context vm passed in is a functional context as well. // in this case we want to make sure we are able to get a hold to the // real context instance. contextVm = parent; // $flow-disable-line parent = parent._original; } var isCompiled = isTrue(options._compiled); var needNormalization = !isCompiled; this.data = data; this.props = props; this.children = children; this.parent = parent; this.listeners = data.on || emptyObject; this.injections = resolveInject(options.inject, parent); this.slots = function () { if (!this$1.$slots) { normalizeScopedSlots( data.scopedSlots, this$1.$slots = resolveSlots(children, parent) ); } return this$1.$slots }; Object.defineProperty(this, 'scopedSlots', ({ enumerable: true, get: function get () { return normalizeScopedSlots(data.scopedSlots, this.slots()) } })); // support for compiled functional template if (isCompiled) { // exposing $options for renderStatic() this.$options = options; // pre-resolve slots for renderSlot() this.$slots = this.slots(); this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots); } if (options._scopeId) { this._c = function (a, b, c, d) { var vnode = createElement(contextVm, a, b, c, d, needNormalization); if (vnode && !Array.isArray(vnode)) { vnode.fnScopeId = options._scopeId; vnode.fnContext = parent; } return vnode }; } else { this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); }; } } installRenderHelpers(FunctionalRenderContext.prototype); function createFunctionalComponent ( Ctor, propsData, data, contextVm, children ) { var options = Ctor.options; var props = {}; var propOptions = options.props; if (isDef(propOptions)) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData || emptyObject); } } else { if (isDef(data.attrs)) { mergeProps(props, data.attrs); } if (isDef(data.props)) { mergeProps(props, data.props); } } var renderContext = new FunctionalRenderContext( data, props, children, contextVm, Ctor ); var vnode = options.render.call(null, renderContext._c, renderContext); if (vnode instanceof VNode) { return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext) } else if (Array.isArray(vnode)) { var vnodes = normalizeChildren(vnode) || []; var res = new Array(vnodes.length); for (var i = 0; i < vnodes.length; i++) { res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext); } return res } } function cloneAndMarkFunctionalResult (vnode, data, contextVm, options, renderContext) { // #7817 clone node before setting fnContext, otherwise if the node is reused // (e.g. it was from a cached normal slot) the fnContext causes named slots // that should not be matched to match. var clone = cloneVNode(vnode); clone.fnContext = contextVm; clone.fnOptions = options; { (clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext; } if (data.slot) { (clone.data || (clone.data = {})).slot = data.slot; } return clone } function mergeProps (to, from) { for (var key in from) { to[camelize(key)] = from[key]; } } /* */ /* */ /* */ /* */ // inline hooks to be invoked on component VNodes during patch var componentVNodeHooks = { init: function init (vnode, hydrating) { if ( vnode.componentInstance && !vnode.componentInstance._isDestroyed && vnode.data.keepAlive ) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode); } else { var child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } }, prepatch: function prepatch (oldVnode, vnode) { var options = vnode.componentOptions; var child = vnode.componentInstance = oldVnode.componentInstance; updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); }, insert: function insert (vnode) { var context = vnode.context; var componentInstance = vnode.componentInstance; if (!componentInstance._isMounted) { componentInstance._isMounted = true; callHook(componentInstance, 'mounted'); } if (vnode.data.keepAlive) { if (context._isMounted) { // vue-router#1212 // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance); } else { activateChildComponent(componentInstance, true /* direct */); } } }, destroy: function destroy (vnode) { var componentInstance = vnode.componentInstance; if (!componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { componentInstance.$destroy(); } else { deactivateChildComponent(componentInstance, true /* direct */); } } } }; var hooksToMerge = Object.keys(componentVNodeHooks); function createComponent ( Ctor, data, context, children, tag ) { if (isUndef(Ctor)) { return } var baseCtor = context.$options._base; // plain options object: turn it into a constructor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component var asyncFactory; if (isUndef(Ctor.cid)) { asyncFactory = Ctor; Ctor = resolveAsyncComponent(asyncFactory, baseCtor); if (Ctor === undefined) { // return a placeholder node for async component, which is rendered // as a comment node but preserves all the raw information for the node. // the information will be used for async server-rendering and hydration. return createAsyncPlaceholder( asyncFactory, data, context, children, tag ) } } data = data || {}; // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data); } // extract props var propsData = extractPropsFromVNodeData(data, Ctor, tag); // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier // so it gets processed during parent component patch. data.on = data.nativeOn; if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners & slot // work around flow var slot = data.slot; data = {}; if (slot) { data.slot = slot; } } // install component management hooks onto the placeholder node installComponentHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }, asyncFactory ); return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent // activeInstance in lifecycle state ) { var options = { _isComponent: true, _parentVnode: vnode, parent: parent }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (isDef(inlineTemplate)) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnode.componentOptions.Ctor(options) } function installComponentHooks (data) { var hooks = data.hook || (data.hook = {}); for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var existing = hooks[key]; var toMerge = componentVNodeHooks[key]; if (existing !== toMerge && !(existing && existing._merged)) { hooks[key] = existing ? mergeHook$1(toMerge, existing) : toMerge; } } } function mergeHook$1 (f1, f2) { var merged = function (a, b) { // flow complains about extra args which is why we use any f1(a, b); f2(a, b); }; merged._merged = true; return merged } // transform component v-model info (value and callback) into // prop and event handler respectively. function transformModel (options, data) { var prop = (options.model && options.model.prop) || 'value'; var event = (options.model && options.model.event) || 'input' ;(data.attrs || (data.attrs = {}))[prop] = data.model.value; var on = data.on || (data.on = {}); var existing = on[event]; var callback = data.model.callback; if (isDef(existing)) { if ( Array.isArray(existing) ? existing.indexOf(callback) === -1 : existing !== callback ) { on[event] = [callback].concat(existing); } } else { on[event] = callback; } } /* */ var SIMPLE_NORMALIZE = 1; var ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (isTrue(alwaysNormalize)) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType) } function _createElement ( context, tag, data, children, normalizationType ) { if (isDef(data) && isDef((data).__ob__)) { warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } // object syntax in v-bind if (isDef(data) && isDef(data.is)) { tag = data.is; } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // warn against non-primitive key if (isDef(data) && isDef(data.key) && !isPrimitive(data.key) ) { { warn( 'Avoid using non-primitive value as key, ' + 'use string/number value instead.', context ); } } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements if (isDef(data) && isDef(data.nativeOn)) { warn( ("The .native modifier for v-on is only valid on components but it was used on <" + tag + ">."), context ); } vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (Array.isArray(vnode)) { return vnode } else if (isDef(vnode)) { if (isDef(ns)) { applyNS(vnode, ns); } if (isDef(data)) { registerDeepBindings(data); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns, force) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject ns = undefined; force = true; } if (isDef(vnode.children)) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (isDef(child.tag) && ( isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) { applyNS(child, ns, force); } } } } // ref #5318 // necessary to ensure parent re-render when deep bindings like :style and // :class are used on slot nodes function registerDeepBindings (data) { if (isObject(data.style)) { traverse(data.style); } if (isObject(data.class)) { traverse(data.class); } } /* */ function initRender (vm) { vm._vnode = null; // the root of the child tree vm._staticTrees = null; // v-once cached trees var options = vm.$options; var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(options._renderChildren, renderContext); vm.$scopedSlots = emptyObject; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; // $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated var parentData = parentVnode && parentVnode.data; /* istanbul ignore else */ { defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () { !isUpdatingChildComponent && warn("$attrs is readonly.", vm); }, true); defineReactive$$1(vm, '$listeners', options._parentListeners || emptyObject, function () { !isUpdatingChildComponent && warn("$listeners is readonly.", vm); }, true); } } var currentRenderingInstance = null; function renderMixin (Vue) { // install runtime convenience helpers installRenderHelpers(Vue.prototype); Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var _parentVnode = ref._parentVnode; if (_parentVnode) { vm.$scopedSlots = normalizeScopedSlots( _parentVnode.data.scopedSlots, vm.$slots, vm.$scopedSlots ); } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { // There's no need to maintain a stack because all render fns are called // separately from one another. Nested component's render fns are called // when parent component is patched. currentRenderingInstance = vm; vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { handleError(e, vm, "render"); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e); } catch (e) { handleError(e, vm, "renderError"); vnode = vm._vnode; } } else { vnode = vm._vnode; } } finally { currentRenderingInstance = null; } // if the returned array contains only a single node, allow it if (Array.isArray(vnode) && vnode.length === 1) { vnode = vnode[0]; } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; } /* */ function ensureCtor (comp, base) { if ( comp.__esModule || (hasSymbol && comp[Symbol.toStringTag] === 'Module') ) { comp = comp.default; } return isObject(comp) ? base.extend(comp) : comp } function createAsyncPlaceholder ( factory, data, context, children, tag ) { var node = createEmptyVNode(); node.asyncFactory = factory; node.asyncMeta = { data: data, context: context, children: children, tag: tag }; return node } function resolveAsyncComponent ( factory, baseCtor ) { if (isTrue(factory.error) && isDef(factory.errorComp)) { return factory.errorComp } if (isDef(factory.resolved)) { return factory.resolved } var owner = currentRenderingInstance; if (owner && isDef(factory.owners) && factory.owners.indexOf(owner) === -1) { // already pending factory.owners.push(owner); } if (isTrue(factory.loading) && isDef(factory.loadingComp)) { return factory.loadingComp } if (owner && !isDef(factory.owners)) { var owners = factory.owners = [owner]; var sync = true; var timerLoading = null; var timerTimeout = null ;(owner).$on('hook:destroyed', function () { return remove(owners, owner); }); var forceRender = function (renderCompleted) { for (var i = 0, l = owners.length; i < l; i++) { (owners[i]).$forceUpdate(); } if (renderCompleted) { owners.length = 0; if (timerLoading !== null) { clearTimeout(timerLoading); timerLoading = null; } if (timerTimeout !== null) { clearTimeout(timerTimeout); timerTimeout = null; } } }; var resolve = once(function (res) { // cache resolved factory.resolved = ensureCtor(res, baseCtor); // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { forceRender(true); } else { owners.length = 0; } }); var reject = once(function (reason) { warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); if (isDef(factory.errorComp)) { factory.error = true; forceRender(true); } }); var res = factory(resolve, reject); if (isObject(res)) { if (isPromise(res)) { // () => Promise if (isUndef(factory.resolved)) { res.then(resolve, reject); } } else if (isPromise(res.component)) { res.component.then(resolve, reject); if (isDef(res.error)) { factory.errorComp = ensureCtor(res.error, baseCtor); } if (isDef(res.loading)) { factory.loadingComp = ensureCtor(res.loading, baseCtor); if (res.delay === 0) { factory.loading = true; } else { timerLoading = setTimeout(function () { timerLoading = null; if (isUndef(factory.resolved) && isUndef(factory.error)) { factory.loading = true; forceRender(false); } }, res.delay || 200); } } if (isDef(res.timeout)) { timerTimeout = setTimeout(function () { timerTimeout = null; if (isUndef(factory.resolved)) { reject( "timeout (" + (res.timeout) + "ms)" ); } }, res.timeout); } } } sync = false; // return in case resolved synchronously return factory.loading ? factory.loadingComp : factory.resolved } } /* */ function isAsyncPlaceholder (node) { return node.isComment && node.asyncFactory } /* */ function getFirstComponentChild (children) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var c = children[i]; if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) { return c } } } } /* */ /* */ function initEvents (vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events var listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } var target; function add (event, fn) { target.$on(event, fn); } function remove$1 (event, fn) { target.$off(event, fn); } function createOnceHandler (event, fn) { var _target = target; return function onceHandler () { var res = fn.apply(null, arguments); if (res !== null) { _target.$off(event, onceHandler); } } } function updateComponentListeners ( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm); target = undefined; } function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { var vm = this; if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { vm.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } } return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // array of events if (Array.isArray(event)) { for (var i$1 = 0, l = event.length; i$1 < l; i$1++) { vm.$off(event[i$1], fn); } return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (!fn) { vm._events[event] = null; return vm } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; { var lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) { tip( "Event \"" + lowerCaseEvent + "\" is emitted in component " + (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " + "Note that HTML attributes are case-insensitive and you cannot use " + "v-on to listen to camelCase events when using in-DOM templates. " + "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"." ); } } var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); var info = "event handler for \"" + event + "\""; for (var i = 0, l = cbs.length; i < l; i++) { invokeWithErrorHandling(cbs[i], vm, args, vm, info); } } return vm }; } /* */ var activeInstance = null; var isUpdatingChildComponent = false; function setActiveInstance(vm) { var prevActiveInstance = activeInstance; activeInstance = vm; return function () { activeInstance = prevActiveInstance; } } function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = null; vm._directInactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._update = function (vnode, hydrating) { var vm = this; var prevEl = vm.$el; var prevVnode = vm._vnode; var restoreActiveInstance = setActiveInstance(vm); vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */); } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } restoreActiveInstance(); // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); // fire destroyed hook callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // release circular reference (#6759) if (vm.$vnode) { vm.$vnode.parent = null; } }; } function mountComponent ( vm, el, hydrating ) { vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; { /* istanbul ignore if */ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) { warn( 'You are using the runtime-only build of Vue where the template ' + 'compiler is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); var updateComponent; /* istanbul ignore if */ if (config.performance && mark) { updateComponent = function () { var name = vm._name; var id = vm._uid; var startTag = "vue-perf-start:" + id; var endTag = "vue-perf-end:" + id; mark(startTag); var vnode = vm._render(); mark(endTag); measure(("vue " + name + " render"), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure(("vue " + name + " patch"), startTag, endTag); }; } else { updateComponent = function () { vm._update(vm._render(), hydrating); }; } // we set this to vm._watcher inside the watcher's constructor // since the watcher's initial patch may call $forceUpdate (e.g. inside child // component's mounted hook), which relies on vm._watcher being already defined new Watcher(vm, updateComponent, noop, { before: function before () { if (vm._isMounted && !vm._isDestroyed) { callHook(vm, 'beforeUpdate'); } } }, true /* isRenderWatcher */); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm } function updateChildComponent ( vm, propsData, listeners, parentVnode, renderChildren ) { { isUpdatingChildComponent = true; } // determine whether component has slot children // we need to do this before overwriting $options._renderChildren. // check if there are dynamic scopedSlots (hand-written or compiled but with // dynamic slot names). Static scoped slots compiled from template has the // "$stable" marker. var newScopedSlots = parentVnode.data.scopedSlots; var oldScopedSlots = vm.$scopedSlots; var hasDynamicScopedSlot = !!( (newScopedSlots && !newScopedSlots.$stable) || (oldScopedSlots !== emptyObject && !oldScopedSlots.$stable) || (newScopedSlots && vm.$scopedSlots.$key !== newScopedSlots.$key) ); // Any static slot children from the parent may have changed during parent's // update. Dynamic scoped slots may also have changed. In such cases, a forced // update is necessary to ensure correctness. var needsForceUpdate = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots hasDynamicScopedSlot ); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update $attrs and $listeners hash // these are also reactive so they may trigger child update if the child // used them during render vm.$attrs = parentVnode.data.attrs || emptyObject; vm.$listeners = listeners || emptyObject; // update props if (propsData && vm.$options.props) { toggleObserving(false); var props = vm._props; var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; var propOptions = vm.$options.props; // wtf flow? props[key] = validateProp(key, propOptions, propsData, vm); } toggleObserving(true); // keep a copy of raw propsData vm.$options.propsData = propsData; } // update listeners listeners = listeners || emptyObject; var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); // resolve slots + force update if has children if (needsForceUpdate) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } { isUpdatingChildComponent = false; } } function isInInactiveTree (vm) { while (vm && (vm = vm.$parent)) { if (vm._inactive) { return true } } return false } function activateChildComponent (vm, direct) { if (direct) { vm._directInactive = false; if (isInInactiveTree(vm)) { return } } else if (vm._directInactive) { return } if (vm._inactive || vm._inactive === null) { vm._inactive = false; for (var i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]); } callHook(vm, 'activated'); } } function deactivateChildComponent (vm, direct) { if (direct) { vm._directInactive = true; if (isInInactiveTree(vm)) { return } } if (!vm._inactive) { vm._inactive = true; for (var i = 0; i < vm.$children.length; i++) { deactivateChildComponent(vm.$children[i]); } callHook(vm, 'deactivated'); } } function callHook (vm, hook) { // #7573 disable dep collection when invoking lifecycle hooks pushTarget(); var handlers = vm.$options[hook]; var info = hook + " hook"; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { invokeWithErrorHandling(handlers[i], vm, null, vm, info); } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } popTarget(); } /* */ var MAX_UPDATE_COUNT = 100; var queue = []; var activatedChildren = []; var has = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { index = queue.length = activatedChildren.length = 0; has = {}; { circular = {}; } waiting = flushing = false; } // Async edge case #6566 requires saving the timestamp when event listeners are // attached. However, calling performance.now() has a perf overhead especially // if the page has thousands of event listeners. Instead, we take a timestamp // every time the scheduler flushes and use that for all event listeners // attached during that flush. var currentFlushTimestamp = 0; // Async edge case fix requires storing an event listener's attach timestamp. var getNow = Date.now; // Determine what event timestamp the browser is using. Annoyingly, the // timestamp can either be hi-res (relative to page load) or low-res // (relative to UNIX epoch), so in order to compare time we have to use the // same timestamp type when saving the flush timestamp. // All IE versions use low-res event timestamps, and have problematic clock // implementations (#9632) if (inBrowser && !isIE) { var performance = window.performance; if ( performance && typeof performance.now === 'function' && getNow() > document.createEvent('Event').timeStamp ) { // if the event timestamp, although evaluated AFTER the Date.now(), is // smaller than it, it means the event is using a hi-res timestamp, // and we need to use the hi-res version for event listener timestamps as // well. getNow = function () { return performance.now(); }; } } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { currentFlushTimestamp = getNow(); flushing = true; var watcher, id; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; if (watcher.before) { watcher.before(); } id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > MAX_UPDATE_COUNT) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // keep copies of post queues before resetting state var activatedQueue = activatedChildren.slice(); var updatedQueue = queue.slice(); resetSchedulerState(); // call component updated and activated hooks callActivatedHooks(activatedQueue); callUpdatedHooks(updatedQueue); // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } } function callUpdatedHooks (queue) { var i = queue.length; while (i--) { var watcher = queue[i]; var vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) { callHook(vm, 'updated'); } } } /** * Queue a kept-alive component that was activated during patch. * The queue will be processed after the entire tree has been patched. */ function queueActivatedComponent (vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); } function callActivatedHooks (queue) { for (var i = 0; i < queue.length; i++) { queue[i]._inactive = true; activateChildComponent(queue[i], true /* true */); } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has[id] == null) { has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i > index && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; if (!config.async) { flushSchedulerQueue(); return } nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options, isRenderWatcher ) { this.vm = vm; if (isRenderWatcher) { vm._watcher = this; } vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; this.before = options.before; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = expOrFn.toString(); // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = noop; warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value; var vm = this.vm; try { value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\"")); } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var i = this.deps.length; while (i--) { var dep = this.deps[i]; if (!this.newDepIds.has(dep.id)) { dep.removeSub(this); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\"")); } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var i = this.deps.length; while (i--) { this.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this.deps[i].removeSub(this); } this.active = false; } }; /* */ var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function proxy (target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter () { return this[sourceKey][key] }; sharedPropertyDefinition.set = function proxySetter (val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); } } function initProps (vm, propsOptions) { var propsData = vm.$options.propsData || {}; var props = vm._props = {}; // cache prop keys so that future props updates can iterate using Array // instead of dynamic object key enumeration. var keys = vm.$options._propKeys = []; var isRoot = !vm.$parent; // root instance props should be converted if (!isRoot) { toggleObserving(false); } var loop = function ( key ) { keys.push(key); var value = validateProp(key, propsOptions, propsData, vm); /* istanbul ignore else */ { var hyphenatedKey = hyphenate(key); if (isReservedAttribute(hyphenatedKey) || config.isReservedAttr(hyphenatedKey)) { warn( ("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive$$1(props, key, value, function () { if (!isRoot && !isUpdatingChildComponent) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at // instantiation here. if (!(key in vm)) { proxy(vm, "_props", key); } }; for (var key in propsOptions) loop( key ); toggleObserving(true); } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {}; if (!isPlainObject(data)) { data = {}; warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var methods = vm.$options.methods; var i = keys.length; while (i--) { var key = keys[i]; { if (methods && hasOwn(methods, key)) { warn( ("Method \"" + key + "\" has already been defined as a data property."), vm ); } } if (props && hasOwn(props, key)) { warn( "The data property \"" + key + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else if (!isReserved(key)) { proxy(vm, "_data", key); } } // observe data observe(data, true /* asRootData */); } function getData (data, vm) { // #7573 disable dep collection when invoking data getters pushTarget(); try { return data.call(vm, vm) } catch (e) { handleError(e, vm, "data()"); return {} } finally { popTarget(); } } var computedWatcherOptions = { lazy: true }; function initComputed (vm, computed) { // $flow-disable-line var watchers = vm._computedWatchers = Object.create(null); // computed properties are just getters during SSR var isSSR = isServerRendering(); for (var key in computed) { var userDef = computed[key]; var getter = typeof userDef === 'function' ? userDef : userDef.get; if (getter == null) { warn( ("Getter is missing for computed property \"" + key + "\"."), vm ); } if (!isSSR) { // create internal watcher for the computed property. watchers[key] = new Watcher( vm, getter || noop, noop, computedWatcherOptions ); } // component-defined computed properties are already defined on the // component prototype. We only need to define computed properties defined // at instantiation here. if (!(key in vm)) { defineComputed(vm, key, userDef); } else { if (key in vm.$data) { warn(("The computed property \"" + key + "\" is already defined in data."), vm); } else if (vm.$options.props && key in vm.$options.props) { warn(("The computed property \"" + key + "\" is already defined as a prop."), vm); } } } } function defineComputed ( target, key, userDef ) { var shouldCache = !isServerRendering(); if (typeof userDef === 'function') { sharedPropertyDefinition.get = shouldCache ? createComputedGetter(key) : createGetterInvoker(userDef); sharedPropertyDefinition.set = noop; } else { sharedPropertyDefinition.get = userDef.get ? shouldCache && userDef.cache !== false ? createComputedGetter(key) : createGetterInvoker(userDef.get) : noop; sharedPropertyDefinition.set = userDef.set || noop; } if (sharedPropertyDefinition.set === noop) { sharedPropertyDefinition.set = function () { warn( ("Computed property \"" + key + "\" was assigned to but it has no setter."), this ); }; } Object.defineProperty(target, key, sharedPropertyDefinition); } function createComputedGetter (key) { return function computedGetter () { var watcher = this._computedWatchers && this._computedWatchers[key]; if (watcher) { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } } function createGetterInvoker(fn) { return function computedGetter () { return fn.call(this, this) } } function initMethods (vm, methods) { var props = vm.$options.props; for (var key in methods) { { if (typeof methods[key] !== 'function') { warn( "Method \"" + key + "\" has type \"" + (typeof methods[key]) + "\" in the component definition. " + "Did you reference the function correctly?", vm ); } if (props && hasOwn(props, key)) { warn( ("Method \"" + key + "\" has already been defined as a prop."), vm ); } if ((key in vm) && isReserved(key)) { warn( "Method \"" + key + "\" conflicts with an existing Vue instance method. " + "Avoid defining component methods that start with _ or $." ); } } vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm); } } function initWatch (vm, watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher ( vm, expOrFn, handler, options ) { if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } return vm.$watch(expOrFn, handler, options) } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; var propsDef = {}; propsDef.get = function () { return this._props }; { dataDef.set = function () { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; propsDef.set = function () { warn("$props is readonly.", this); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Object.defineProperty(Vue.prototype, '$props', propsDef); Vue.prototype.$set = set; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options) } options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { try { cb.call(vm, watcher.value); } catch (error) { handleError(error, vm, ("callback for immediate watcher \"" + (watcher.expression) + "\"")); } } return function unwatchFn () { watcher.teardown(); } }; } /* */ var uid$3 = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid$3++; var startTag, endTag; /* istanbul ignore if */ if (config.performance && mark) { startTag = "vue-perf-start:" + (vm._uid); endTag = "vue-perf-end:" + (vm._uid); mark(startTag); } // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ { initProxy(vm); } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initInjections(vm); // resolve injections before data/props initState(vm); initProvide(vm); // resolve provide after data/props callHook(vm, 'created'); /* istanbul ignore if */ if (config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(("vue " + (vm._name) + " init"), startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. var parentVnode = options._parentVnode; opts.parent = options.parent; opts._parentVnode = parentVnode; var vnodeComponentOptions = parentVnode.componentOptions; opts.propsData = vnodeComponentOptions.propsData; opts._parentListeners = vnodeComponentOptions.listeners; opts._renderChildren = vnodeComponentOptions.children; opts._componentTag = vnodeComponentOptions.tag; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = resolveConstructorOptions(Ctor.super); var cachedSuperOptions = Ctor.superOptions; if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions; // check if there are any late-modified/attached options (#4976) var modifiedOptions = resolveModifiedOptions(Ctor); // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions); } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function resolveModifiedOptions (Ctor) { var modified; var latest = Ctor.options; var sealed = Ctor.sealedOptions; for (var key in latest) { if (latest[key] !== sealed[key]) { if (!modified) { modified = {}; } modified[key] = latest[key]; } } return modified } function Vue (options) { if (!(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue); stateMixin(Vue); eventsMixin(Vue); lifecycleMixin(Vue); renderMixin(Vue); /* */ function initUse (Vue) { Vue.use = function (plugin) { var installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') { plugin.apply(null, args); } installedPlugins.push(plugin); return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); return this }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (name) { validateComponentName(name); } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids Object.defineProperty calls for each instance created. if (Sub.options.props) { initProps$1(Sub); } if (Sub.options.computed) { initComputed$1(Sub); } // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; Sub.sealedOptions = extend({}, Sub.options); // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } function initProps$1 (Comp) { var props = Comp.options.props; for (var key in props) { proxy(Comp.prototype, "_props", key); } } function initComputed$1 (Comp) { var computed = Comp.options.computed; for (var key in computed) { defineComputed(Comp.prototype, key, computed[key]); } } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ ASSET_TYPES.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (type === 'component') { validateComponentName(id); } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ function getComponentName (opts) { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern, name) { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } function pruneCache (keepAliveInstance, filter) { var cache = keepAliveInstance.cache; var keys = keepAliveInstance.keys; var _vnode = keepAliveInstance._vnode; for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode); } } } } function pruneCacheEntry ( cache, key, keys, current ) { var cached$$1 = cache[key]; if (cached$$1 && (!current || cached$$1.tag !== current.tag)) { cached$$1.componentInstance.$destroy(); } cache[key] = null; remove(keys, key); } var patternTypes = [String, RegExp, Array]; var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created: function created () { this.cache = Object.create(null); this.keys = []; }, destroyed: function destroyed () { for (var key in this.cache) { pruneCacheEntry(this.cache, key, this.keys); } }, mounted: function mounted () { var this$1 = this; this.$watch('include', function (val) { pruneCache(this$1, function (name) { return matches(val, name); }); }); this.$watch('exclude', function (val) { pruneCache(this$1, function (name) { return !matches(val, name); }); }); }, render: function render () { var slot = this.$slots.default; var vnode = getFirstComponentChild(slot); var componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern var name = getComponentName(componentOptions); var ref = this; var include = ref.include; var exclude = ref.exclude; if ( // not included (include && (!name || !matches(include, name))) || // excluded (exclude && name && matches(exclude, name)) ) { return vnode } var ref$1 = this; var cache = ref$1.cache; var keys = ref$1.keys; var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '') : vnode.key; if (cache[key]) { vnode.componentInstance = cache[key].componentInstance; // make current key freshest remove(keys, key); keys.push(key); } else { cache[key] = vnode; keys.push(key); // prune oldest entry if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode); } } vnode.data.keepAlive = true; } return vnode || (slot && slot[0]) } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn: warn, extend: extend, mergeOptions: mergeOptions, defineReactive: defineReactive$$1 }; Vue.set = set; Vue.delete = del; Vue.nextTick = nextTick; // 2.6 explicit observable API Vue.observable = function (obj) { observe(obj); return obj }; Vue.options = Object.create(null); ASSET_TYPES.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue); Object.defineProperty(Vue.prototype, '$isServer', { get: isServerRendering }); Object.defineProperty(Vue.prototype, '$ssrContext', { get: function get () { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext } }); // expose FunctionalRenderContext for ssr runtime helper installation Object.defineProperty(Vue, 'FunctionalRenderContext', { value: FunctionalRenderContext }); Vue.version = '2.6.11'; /* */ // these are reserved for web because they are directly compiled away // during template compilation var isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select,progress'); var mustUseProp = function (tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isValidContentEditableValue = makeMap('events,caret,typing,plaintext-only'); var convertEnumeratedValue = function (key, value) { return isFalsyAttrValue(value) || value === 'false' ? 'false' // allow arbitrary string value for contenteditable : key === 'contenteditable' && isValidContentEditableValue(value) ? value : 'true' }; var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (isDef(childNode.componentInstance)) { childNode = childNode.componentInstance._vnode; if (childNode && childNode.data) { data = mergeClassData(childNode.data, data); } } while (isDef(parentNode = parentNode.parent)) { if (parentNode && parentNode.data) { data = mergeClassData(data, parentNode.data); } } return renderClass(data.staticClass, data.class) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: isDef(child.class) ? [child.class, parent.class] : parent.class } } function renderClass ( staticClass, dynamicClass ) { if (isDef(staticClass) || isDef(dynamicClass)) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { if (Array.isArray(value)) { return stringifyArray(value) } if (isObject(value)) { return stringifyObject(value) } if (typeof value === 'string') { return value } /* istanbul ignore next */ return '' } function stringifyArray (value) { var res = ''; var stringified; for (var i = 0, l = value.length; i < l; i++) { if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') { if (res) { res += ' '; } res += stringified; } } return res } function stringifyObject (value) { var res = ''; for (var key in value) { if (value[key]) { if (res) { res += ' '; } res += key; } } return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template,blockquote,iframe,tfoot' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } var isTextInputType = makeMap('text,number,password,search,email,tel,url'); /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selected = document.querySelector(el); if (!selected) { warn( 'Cannot find element: ' + el ); return document.createElement('div') } return selected } else { return el } } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } // false or null will remove the attribute but undefined will not if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setStyleScope (node, scopeId) { node.setAttribute(scopeId, ''); } var nodeOps = /*#__PURE__*/Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setStyleScope: setStyleScope }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!isDef(key)) { return } var vm = vnode.context; var ref = vnode.componentInstance || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (!Array.isArray(refs[key])) { refs[key] = [ref]; } else if (refs[key].indexOf(ref) < 0) { // $flow-disable-line refs[key].push(ref); } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks = ['create', 'activate', 'update', 'remove', 'destroy']; function sameVnode (a, b) { return ( a.key === b.key && ( ( a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) || ( isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error) ) ) ) } function sameInputType (a, b) { if (a.tag !== 'input') { return true } var i; var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type; var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type; return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove$$1 () { if (--remove$$1.listeners === 0) { removeNode(childElm); } } remove$$1.listeners = listeners; return remove$$1 } function removeNode (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el); } } function isUnknownElement$$1 (vnode, inVPre) { return ( !inVPre && !vnode.ns && !( config.ignoredElements.length && config.ignoredElements.some(function (ignore) { return isRegExp(ignore) ? ignore.test(vnode.tag) : ignore === vnode.tag }) ) && config.isUnknownElement(vnode.tag) ) } var creatingElmInVPre = 0; function createElm ( vnode, insertedVnodeQueue, parentElm, refElm, nested, ownerArray, index ) { if (isDef(vnode.elm) && isDef(ownerArray)) { // This vnode was used in a previous render! // now it's used as a new node, overwriting its elm would cause // potential patch errors down the road when it's used as an insertion // reference node. Instead, we clone the node on-demand before creating // associated DOM element for it. vnode = ownerArray[index] = cloneVNode(vnode); } vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { { if (data && data.pre) { creatingElmInVPre++; } if (isUnknownElement$$1(vnode, creatingElmInVPre)) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (data && data.pre) { creatingElmInVPre--; } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); insert(parentElm, vnode.elm, refElm); if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); vnode.data.pendingInsert = null; } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref$$1) { if (isDef(parent)) { if (isDef(ref$$1)) { if (nodeOps.parentNode(ref$$1) === parent) { nodeOps.insertBefore(parent, elm, ref$$1); } } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { { checkDuplicateKeys(children); } for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text))); } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (isDef(i.create)) { i.create(emptyNode, vnode); } if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.fnScopeId)) { nodeOps.setStyleScope(vnode.elm, i); } else { var ancestor = vnode; while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setStyleScope(vnode.elm, i); } ancestor = ancestor.parent; } } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.fnContext && isDef(i = i.$options._scopeId) ) { nodeOps.setStyleScope(vnode.elm, i); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, false, vnodes, startIdx); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { var i; var listeners = cbs.remove.length + 1; if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } else { // directly removing rm = createRmCb(vnode.elm, listeners); } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, vnodeToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; { checkDuplicateKeys(newCh); } while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx); if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx); } else { vnodeToMove = oldCh[idxInOld]; if (sameVnode(vnodeToMove, newStartVnode)) { patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm); } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx); } } newStartVnode = newCh[++newStartIdx]; } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(oldCh, oldStartIdx, oldEndIdx); } } function checkDuplicateKeys (children) { var seenKeys = {}; for (var i = 0; i < children.length; i++) { var vnode = children[i]; var key = vnode.key; if (isDef(key)) { if (seenKeys[key]) { warn( ("Duplicate keys detected: '" + key + "'. This may cause an update error."), vnode.context ); } else { seenKeys[key] = true; } } } } function findIdxInOld (node, oldCh, start, end) { for (var i = start; i < end; i++) { var c = oldCh[i]; if (isDef(c) && sameVnode(node, c)) { return i } } } function patchVnode ( oldVnode, vnode, insertedVnodeQueue, ownerArray, index, removeOnly ) { if (oldVnode === vnode) { return } if (isDef(vnode.elm) && isDef(ownerArray)) { // clone reused vnode vnode = ownerArray[index] = cloneVNode(vnode); } var elm = vnode.elm = oldVnode.elm; if (isTrue(oldVnode.isAsyncPlaceholder)) { if (isDef(vnode.asyncFactory.resolved)) { hydrate(oldVnode.elm, vnode, insertedVnodeQueue); } else { vnode.isAsyncPlaceholder = true; } return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.componentInstance = oldVnode.componentInstance; return } var i; var data = vnode.data; if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var oldCh = oldVnode.children; var ch = vnode.children; if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { { checkDuplicateKeys(ch); } if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var hydrationBailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization // Note: style is excluded because it relies on initial clone for future // deep updates (#7063). var isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue, inVPre) { var i; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; inVPre = inVPre || (data && data.pre); vnode.elm = elm; if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) { vnode.isAsyncPlaceholder = true; return true } // assert node match { if (!assertNodeMatch(elm, vnode, inVPre)) { return false } } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { // v-html and domProps: innerHTML if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) { if (i !== elm.innerHTML) { /* istanbul ignore if */ if (typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('server innerHTML: ', i); console.warn('client innerHTML: ', elm.innerHTML); } return false } } else { // iterate and compare children lists var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue, inVPre)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { /* istanbul ignore if */ if (typeof console !== 'undefined' && !hydrationBailed ) { hydrationBailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } } if (isDef(data)) { var fullInvoke = false; for (var key in data) { if (!isRenderedModule(key)) { fullInvoke = true; invokeCreateHooks(vnode, insertedVnodeQueue); break } } if (!fullInvoke && data['class']) { // ensure collecting deps for deep class bindings for future updates traverse(data['class']); } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true } function assertNodeMatch (node, vnode, inVPre) { if (isDef(vnode.tag)) { return vnode.tag.indexOf('vue-component') === 0 || ( !isUnknownElement$$1(vnode, inVPre) && vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly) { if (isUndef(vnode)) { if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); } return } var isInitialPatch = false; var insertedVnodeQueue = []; if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR); hydrating = true; } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element var oldElm = oldVnode.elm; var parentElm = nodeOps.parentNode(oldElm); // create new node createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm, nodeOps.nextSibling(oldElm) ); // update parent placeholder node element, recursively if (isDef(vnode.parent)) { var ancestor = vnode.parent; var patchable = isPatchable(vnode); while (ancestor) { for (var i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](ancestor); } ancestor.elm = vnode.elm; if (patchable) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, ancestor); } // #6513 // invoke insert hooks that may have been merged by create hooks. // e.g. for directives that uses the "inserted" hook. var insert = ancestor.data.hook.insert; if (insert.merged) { // start at index 1 to avoid re-invoking component mounted hook for (var i$2 = 1; i$2 < insert.fns.length; i$2++) { insert.fns[i$2](); } } } else { registerRef(ancestor); } ancestor = ancestor.parent; } } // destroy old node if (isDef(parentElm)) { removeVnodes([oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var isDestroy = vnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; dir.oldArg = oldDir.arg; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode, 'insert', callInsert); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode, 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { // $flow-disable-line return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { // $flow-disable-line dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } // $flow-disable-line return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) { var fn = dir.def && dir.def[hook]; if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } catch (e) { handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook")); } } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { var opts = vnode.componentOptions; if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) { return } if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(attrs.__ob__)) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] // #6666: IE/Edge forces progress value down to 1 before setting a max /* istanbul ignore if */ if ((isIE || isEdge) && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (isUndef(attrs[key])) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (el.tagName.indexOf('-') > -1) { baseSetAttr(el, key, value); } else if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // technically allowfullscreen is a boolean attribute for <iframe>, // but Flash expects a value of "true" when used on <embed> tag value = key === 'allowfullscreen' && el.tagName === 'EMBED' ? 'true' : key; el.setAttribute(key, value); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, convertEnumeratedValue(key, value)); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { baseSetAttr(el, key, value); } } function baseSetAttr (el, key, value) { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // #7138: IE10 & 11 fires input event when setting placeholder on // <textarea>... block the first input event and remove the blocker // immediately. /* istanbul ignore if */ if ( isIE && !isIE9 && el.tagName === 'TEXTAREA' && key === 'placeholder' && value !== '' && !el.__ieph ) { var blocker = function (e) { e.stopImmediatePropagation(); el.removeEventListener('input', blocker); }; el.addEventListener('input', blocker); // $flow-disable-line el.__ieph = true; /* IE placeholder patched */ } el.setAttribute(key, value); } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if ( isUndef(data.staticClass) && isUndef(data.class) && ( isUndef(oldData) || ( isUndef(oldData.staticClass) && isUndef(oldData.class) ) ) ) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (isDef(transitionClass)) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; /* */ var validDivisionCharRE = /[\w).+\-_$\]]/; function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } if (c === 0x2f) { // / var j = i - 1; var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + (args !== ')' ? ',' + args : args)) } } /* */ /* eslint-disable no-unused-vars */ function baseWarn (msg, range) { console.error(("[Vue compiler]: " + msg)); } /* eslint-enable no-unused-vars */ function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value, range, dynamic) { (el.props || (el.props = [])).push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range)); el.plain = false; } function addAttr (el, name, value, range, dynamic) { var attrs = dynamic ? (el.dynamicAttrs || (el.dynamicAttrs = [])) : (el.attrs || (el.attrs = [])); attrs.push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range)); el.plain = false; } // add a raw attr (use this in preTransforms) function addRawAttr (el, name, value, range) { el.attrsMap[name] = value; el.attrsList.push(rangeSetItem({ name: name, value: value }, range)); } function addDirective ( el, name, rawName, value, arg, isDynamicArg, modifiers, range ) { (el.directives || (el.directives = [])).push(rangeSetItem({ name: name, rawName: rawName, value: value, arg: arg, isDynamicArg: isDynamicArg, modifiers: modifiers }, range)); el.plain = false; } function prependModifierMarker (symbol, name, dynamic) { return dynamic ? ("_p(" + name + ",\"" + symbol + "\")") : symbol + name // mark the event as captured } function addHandler ( el, name, value, modifiers, important, warn, range, dynamic ) { modifiers = modifiers || emptyObject; // warn prevent and passive modifier /* istanbul ignore if */ if ( warn && modifiers.prevent && modifiers.passive ) { warn( 'passive and prevent can\'t be used together. ' + 'Passive handler can\'t prevent default event.', range ); } // normalize click.right and click.middle since they don't actually fire // this is technically browser-specific, but at least for now browsers are // the only target envs that have right/middle clicks. if (modifiers.right) { if (dynamic) { name = "(" + name + ")==='click'?'contextmenu':(" + name + ")"; } else if (name === 'click') { name = 'contextmenu'; delete modifiers.right; } } else if (modifiers.middle) { if (dynamic) { name = "(" + name + ")==='click'?'mouseup':(" + name + ")"; } else if (name === 'click') { name = 'mouseup'; } } // check capture modifier if (modifiers.capture) { delete modifiers.capture; name = prependModifierMarker('!', name, dynamic); } if (modifiers.once) { delete modifiers.once; name = prependModifierMarker('~', name, dynamic); } /* istanbul ignore if */ if (modifiers.passive) { delete modifiers.passive; name = prependModifierMarker('&', name, dynamic); } var events; if (modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = rangeSetItem({ value: value.trim(), dynamic: dynamic }, range); if (modifiers !== emptyObject) { newHandler.modifiers = modifiers; } var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } el.plain = false; } function getRawBindingAttr ( el, name ) { return el.rawAttrsMap[':' + name] || el.rawAttrsMap['v-bind:' + name] || el.rawAttrsMap[name] } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } // note: this only removes the attr from the Array (attrsList) so that it // doesn't get processed by processAttrs. // By default it does NOT remove it from the map (attrsMap) because the map is // needed during codegen. function getAndRemoveAttr ( el, name, removeFromMap ) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } if (removeFromMap) { delete el.attrsMap[name]; } return val } function getAndRemoveAttrByRegex ( el, name ) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { var attr = list[i]; if (name.test(attr.name)) { list.splice(i, 1); return attr } } } function rangeSetItem ( item, range ) { if (range) { if (range.start != null) { item.start = range.start; } if (range.end != null) { item.end = range.end; } } return item } /* */ /** * Cross-platform code generation for component v-model */ function genComponentModel ( el, value, modifiers ) { var ref = modifiers || {}; var number = ref.number; var trim = ref.trim; var baseValueExpression = '$$v'; var valueExpression = baseValueExpression; if (trim) { valueExpression = "(typeof " + baseValueExpression + " === 'string'" + "? " + baseValueExpression + ".trim()" + ": " + baseValueExpression + ")"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var assignment = genAssignmentCode(value, valueExpression); el.model = { value: ("(" + value + ")"), expression: JSON.stringify(value), callback: ("function (" + baseValueExpression + ") {" + assignment + "}") }; } /** * Cross-platform codegen helper for generating v-model value assignment code. */ function genAssignmentCode ( value, assignment ) { var res = parseModel(value); if (res.key === null) { return (value + "=" + assignment) } else { return ("$set(" + (res.exp) + ", " + (res.key) + ", " + assignment + ")") } } /** * Parse a v-model expression into a base path and a final key segment. * Handles both dot-path and possible square brackets. * * Possible cases: * * - test * - test[key] * - test[test1[key]] * - test["a"][key] * - xxx.test[a[a].test1[key]] * - test.xxx.a["asa"][test1[key]] * */ var len, str, chr, index$1, expressionPos, expressionEndPos; function parseModel (val) { // Fix https://github.com/vuejs/vue/pull/7730 // allow v-model="obj.val " (trailing whitespace) val = val.trim(); len = val.length; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { index$1 = val.lastIndexOf('.'); if (index$1 > -1) { return { exp: val.slice(0, index$1), key: '"' + val.slice(index$1 + 1) + '"' } } else { return { exp: val, key: null } } } str = val; index$1 = expressionPos = expressionEndPos = 0; while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.slice(0, expressionPos), key: val.slice(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var warn$1; // in some cases, the event used has to be determined at runtime // so we used some reserved tokens during compile. var RANGE_TOKEN = '__r'; var CHECKBOX_RADIO_TOKEN = '__c'; function model ( el, dir, _warn ) { warn$1 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; { // inputs with type="file" are read only and setting the input's // value will throw an error. if (tag === 'input' && type === 'file') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead.", el.rawAttrsMap['v-model'] ); } } if (el.component) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else if (tag === 'input' || tag === 'textarea') { genDefaultModel(el, value, modifiers); } else if (!config.isReservedTag(tag)) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "v-model is not supported on this element type. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.', el.rawAttrsMap['v-model'] ); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ( trueValueBinding === 'true' ? (":(" + value + ")") : (":_q(" + value + "," + trueValueBinding + ")") ) ); addHandler(el, 'change', "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$el.checked){$$i<0&&(" + (genAssignmentCode(value, '$$a.concat([$$v])')) + ")}" + "else{$$i>-1&&(" + (genAssignmentCode(value, '$$a.slice(0,$$i).concat($$a.slice($$i+1))')) + ")}" + "}else{" + (genAssignmentCode(value, '$$c')) + "}", null, true ); } function genRadioModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true); } function genSelect ( el, value, modifiers ) { var number = modifiers && modifiers.number; var selectedVal = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})"; var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'; var code = "var $$selectedVal = " + selectedVal + ";"; code = code + " " + (genAssignmentCode(value, assignment)); addHandler(el, 'change', code, null, true); } function genDefaultModel ( el, value, modifiers ) { var type = el.attrsMap.type; // warn if v-bind:value conflicts with v-model // except for inputs with v-bind:type { var value$1 = el.attrsMap['v-bind:value'] || el.attrsMap[':value']; var typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type']; if (value$1 && !typeBinding) { var binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value'; warn$1( binding + "=\"" + value$1 + "\" conflicts with v-model on the same element " + 'because the latter already expands to a value binding internally', el.rawAttrsMap[binding] ); } } var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var needCompositionGuard = !lazy && type !== 'range'; var event = lazy ? 'change' : type === 'range' ? RANGE_TOKEN : 'input'; var valueExpression = '$event.target.value'; if (trim) { valueExpression = "$event.target.value.trim()"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var code = genAssignmentCode(value, valueExpression); if (needCompositionGuard) { code = "if($event.target.composing)return;" + code; } addProp(el, 'value', ("(" + value + ")")); addHandler(el, event, code, null, true); if (trim || number) { addHandler(el, 'blur', '$forceUpdate()'); } } /* */ // normalize v-model event tokens that can only be determined at runtime. // it's important to place the event as the first in the array because // the whole point is ensuring the v-model callback gets called before // user-attached handlers. function normalizeEvents (on) { /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event var event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } // This was originally intended to fix #4521 but no longer necessary // after 2.5. Keeping it for backwards compat with generated code from < 2.4 /* istanbul ignore if */ if (isDef(on[CHECKBOX_RADIO_TOKEN])) { on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []); delete on[CHECKBOX_RADIO_TOKEN]; } } var target$1; function createOnceHandler$1 (event, handler, capture) { var _target = target$1; // save current target element in closure return function onceHandler () { var res = handler.apply(null, arguments); if (res !== null) { remove$2(event, onceHandler, capture, _target); } } } // #9446: Firefox <= 53 (in particular, ESR 52) has incorrect Event.timeStamp // implementation and does not fire microtasks in between event propagation, so // safe to exclude. var useMicrotaskFix = isUsingMicroTask && !(isFF && Number(isFF[1]) <= 53); function add$1 ( name, handler, capture, passive ) { // async edge case #6566: inner click event triggers patch, event handler // attached to outer element during patch, and triggered again. This // happens because browsers fire microtask ticks between event propagation. // the solution is simple: we save the timestamp when a handler is attached, // and the handler would only fire if the event passed to it was fired // AFTER it was attached. if (useMicrotaskFix) { var attachedTimestamp = currentFlushTimestamp; var original = handler; handler = original._wrapper = function (e) { if ( // no bubbling, should always fire. // this is just a safety net in case event.timeStamp is unreliable in // certain weird environments... e.target === e.currentTarget || // event is fired after handler attachment e.timeStamp >= attachedTimestamp || // bail for environments that have buggy event.timeStamp implementations // #9462 iOS 9 bug: event.timeStamp is 0 after history.pushState // #9681 QtWebEngine event.timeStamp is negative value e.timeStamp <= 0 || // #9448 bail if event is fired in another document in a multi-page // electron/nw.js app, since event.timeStamp will be using a different // starting reference e.target.ownerDocument !== document ) { return original.apply(this, arguments) } }; } target$1.addEventListener( name, handler, supportsPassive ? { capture: capture, passive: passive } : capture ); } function remove$2 ( name, handler, capture, _target ) { (_target || target$1).removeEventListener( name, handler._wrapper || handler, capture ); } function updateDOMListeners (oldVnode, vnode) { if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target$1 = vnode.elm; normalizeEvents(on); updateListeners(on, oldOn, add$1, remove$2, createOnceHandler$1, vnode.context); target$1 = undefined; } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ var svgContainer; function updateDOMProps (oldVnode, vnode) { if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(props.__ob__)) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (!(key in props)) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } // #6601 work around Chrome version <= 55 bug where single textNode // replaced by innerHTML/textContent retains its parentNode property if (elm.childNodes.length === 1) { elm.removeChild(elm.childNodes[0]); } } if (key === 'value' && elm.tagName !== 'PROGRESS') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = isUndef(cur) ? '' : String(cur); if (shouldUpdateValue(elm, strCur)) { elm.value = strCur; } } else if (key === 'innerHTML' && isSVG(elm.tagName) && isUndef(elm.innerHTML)) { // IE doesn't support innerHTML for SVG elements svgContainer = svgContainer || document.createElement('div'); svgContainer.innerHTML = "<svg>" + cur + "</svg>"; var svg = svgContainer.firstChild; while (elm.firstChild) { elm.removeChild(elm.firstChild); } while (svg.firstChild) { elm.appendChild(svg.firstChild); } } else if ( // skip the update if old and new VDOM state is the same. // `value` is handled separately because the DOM value may be temporarily // out of sync with VDOM state due to focus, composition and modifiers. // This #4521 by skipping the unnecesarry `checked` update. cur !== oldProps[key] ) { // some property updates can throw // e.g. `value` on <progress> w/ non-finite value try { elm[key] = cur; } catch (e) {} } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue (elm, checkVal) { return (!elm.composing && ( elm.tagName === 'OPTION' || isNotInFocusAndDirty(elm, checkVal) || isDirtyWithModifiers(elm, checkVal) )) } function isNotInFocusAndDirty (elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is // not equal to the updated value var notInFocus = true; // #6157 // work around IE bug when accessing document.activeElement in an iframe try { notInFocus = document.activeElement !== elm; } catch (e) {} return notInFocus && elm.value !== checkVal } function isDirtyWithModifiers (elm, newVal) { var value = elm.value; var modifiers = elm._vModifiers; // injected by v-model runtime if (isDef(modifiers)) { if (modifiers.number) { return toNumber(value) !== toNumber(newVal) } if (modifiers.trim) { return value.trim() !== newVal.trim() } } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if ( childNode && childNode.data && (styleData = normalizeStyleData(childNode.data)) ) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(hyphenate(name), val.replace(importantRE, ''), 'important'); } else { var normalizedName = normalize(name); if (Array.isArray(val)) { // Support values array created by autoprefixer, e.g. // {display: ["-webkit-box", "-ms-flexbox", "flex"]} // Set them one by one, and the browser will only set those it can recognize for (var i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i]; } } else { el.style[normalizedName] = val; } } }; var vendorNames = ['Webkit', 'Moz', 'ms']; var emptyStyle; var normalize = cached(function (prop) { emptyStyle = emptyStyle || document.createElement('div').style; prop = camelize(prop); if (prop !== 'filter' && (prop in emptyStyle)) { return prop } var capName = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < vendorNames.length; i++) { var name = vendorNames[i] + capName; if (name in emptyStyle) { return name } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldData.staticStyle; var oldStyleBinding = oldData.normalizedStyle || oldData.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; // store normalized style under a different key for next diff // make sure to clone it if it's reactive, since the user likely wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (isUndef(newStyle[name])) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ var whitespaceRE = /\s+/; /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(whitespaceRE).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(whitespaceRE).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } if (!el.classList.length) { el.removeAttribute('class'); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } cur = cur.trim(); if (cur) { el.setAttribute('class', cur); } else { el.removeAttribute('class'); } } } /* */ function resolveTransition (def$$1) { if (!def$$1) { return } /* istanbul ignore else */ if (typeof def$$1 === 'object') { var res = {}; if (def$$1.css !== false) { extend(res, autoCssTransition(def$$1.name || 'v')); } extend(res, def$$1); return res } else if (typeof def$$1 === 'string') { return autoCssTransition(def$$1) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), enterToClass: (name + "-enter-to"), enterActiveClass: (name + "-enter-active"), leaveClass: (name + "-leave"), leaveToClass: (name + "-leave-to"), leaveActiveClass: (name + "-leave-active") } }); var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined ) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined ) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode var raf = inBrowser ? window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout : /* istanbul ignore next */ function (fn) { return fn(); }; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { var transitionClasses = el._transitionClasses || (el._transitionClasses = []); if (transitionClasses.indexOf(cls) < 0) { transitionClasses.push(cls); addClass(el, cls); } } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); // JSDOM may return undefined for transition properties var transitionDelays = (styles[transitionProp + 'Delay'] || '').split(', '); var transitionDurations = (styles[transitionProp + 'Duration'] || '').split(', '); var transitionTimeout = getTimeout(transitionDelays, transitionDurations); var animationDelays = (styles[animationProp + 'Delay'] || '').split(', '); var animationDurations = (styles[animationProp + 'Duration'] || '').split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } // Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers // in a locale-dependent way, using a comma instead of a dot. // If comma is not replaced with a dot, the input will be rounded down (i.e. acting // as a floor function) causing unexpected behaviors function toMs (s) { return Number(s.slice(0, -1).replace(',', '.')) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (isDef(el._leaveCb)) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return } /* istanbul ignore if */ if (isDef(el._enterCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterToClass = data.enterToClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearToClass = data.appearToClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; var duration = data.duration; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { context = transitionNode.context; transitionNode = transitionNode.parent; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear && appearClass ? appearClass : enterClass; var activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; var toClass = isAppear && appearToClass ? appearToClass : enterToClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var explicitEnterDuration = toNumber( isObject(duration) ? duration.enter : duration ); if (explicitEnterDuration != null) { checkDuration(explicitEnterDuration, 'enter', vnode); } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(enterHook); var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode, 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb ) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { removeTransitionClass(el, startClass); if (!cb.cancelled) { addTransitionClass(el, toClass); if (!userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(cb, explicitEnterDuration); } else { whenTransitionEnds(el, type, cb); } } } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (isDef(el._enterCb)) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data) || el.nodeType !== 1) { return rm() } /* istanbul ignore if */ if (isDef(el._leaveCb)) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveToClass = data.leaveToClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var duration = data.duration; var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(leave); var explicitLeaveDuration = toNumber( isObject(duration) ? duration.leave : duration ); if (isDef(explicitLeaveDuration)) { checkDuration(explicitLeaveDuration, 'leave', vnode); } var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show && el.parentNode) { (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { removeTransitionClass(el, leaveClass); if (!cb.cancelled) { addTransitionClass(el, leaveToClass); if (!userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(cb, explicitLeaveDuration); } else { whenTransitionEnds(el, type, cb); } } } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } // only used in dev mode function checkDuration (val, name, vnode) { if (typeof val !== 'number') { warn( "<transition> explicit " + name + " duration is not a valid number - " + "got " + (JSON.stringify(val)) + ".", vnode.context ); } else if (isNaN(val)) { warn( "<transition> explicit " + name + " duration is NaN - " + 'the duration expression might be incorrect.', vnode.context ); } } function isValidDuration (val) { return typeof val === 'number' && !isNaN(val) } /** * Normalize a transition hook's argument length. The hook may be: * - a merged hook (invoker) with the original in .fns * - a wrapped component method (check ._length) * - a plain function (.length) */ function getHookArgumentsLength (fn) { if (isUndef(fn)) { return false } var invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( Array.isArray(invokerFns) ? invokerFns[0] : invokerFns ) } else { return (fn._length || fn.length) > 1 } } function _enter (_, vnode) { if (vnode.data.show !== true) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove$$1 (vnode, rm) { /* istanbul ignore else */ if (vnode.data.show !== true) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var directive = { inserted: function inserted (el, binding, vnode, oldVnode) { if (vnode.tag === 'select') { // #6903 if (oldVnode.elm && !oldVnode.elm._vOptions) { mergeVNodeHook(vnode, 'postpatch', function () { directive.componentUpdated(el, binding, vnode); }); } else { setSelected(el, binding, vnode.context); } el._vOptions = [].map.call(el.options, getValue); } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. el.addEventListener('change', onCompositionEnd); /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var prevOptions = el._vOptions; var curOptions = el._vOptions = [].map.call(el.options, getValue); if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) { // trigger change event if // no matching option found for at least one value var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions); if (needReset) { trigger(el, 'change'); } } } } }; function setSelected (el, binding, vm) { actuallySetSelected(el, binding, vm); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(function () { actuallySetSelected(el, binding, vm); }, 0); } } function actuallySetSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { return options.every(function (o) { return !looseEqual(o, value); }) } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { // prevent triggering an input event for no reason if (!e.target.composing) { return } e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition$$1) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (!value === !oldValue) { return } vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; if (transition$$1) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind ( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } } }; var platformDirectives = { model: directive, show: show }; /* */ var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String, duration: [Number, String, Object] }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1]; } return data } function placeholder (h, rawChild) { if (/\d-keep-alive$/.test(rawChild.tag)) { return h('keep-alive', { props: rawChild.componentOptions.propsData }) } } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } function isSameChild (child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag } var isNotTextNode = function (c) { return c.tag || isAsyncPlaceholder(c); }; var isVShowDirective = function (d) { return d.name === 'show'; }; var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$slots.default; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(isNotTextNode); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (mode && mode !== 'in-out' && mode !== 'out-in' ) { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. var id = "__transition-" + (this._uid) + "-"; child.key = child.key == null ? child.isComment ? id + 'comment' : id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(isVShowDirective)) { child.data.show = true; } if ( oldChild && oldChild.data && !isSameChild(child, oldChild) && !isAsyncPlaceholder(oldChild) && // #6687 component root is a comment node !(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment) ) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild.data.transition = extend({}, data); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }); return placeholder(h, rawChild) } else if (mode === 'in-out') { if (isAsyncPlaceholder(child)) { return oldRawChild } var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave); mergeVNodeHook(data, 'enterCancelled', performLeave); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }); } } return rawChild } }; /* */ var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, beforeMount: function beforeMount () { var this$1 = this; var update = this._update; this._update = function (vnode, hydrating) { var restoreActiveInstance = setActiveInstance(this$1); // force removing pass this$1.__patch__( this$1._vnode, this$1.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this$1._vnode = this$1.kept; restoreActiveInstance(); update.call(this$1, vnode, hydrating); }; }, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position // assign to this to avoid being removed in tree-shaking // $flow-disable-line this._reflow = document.body.offsetHeight; children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (e && e.target !== el) { return } if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } /* istanbul ignore if */ if (this._hasMove) { return this._hasMove } // Detect whether an element with the move class applied has // CSS transitions. Since the element may be inside an entering // transition at this very moment, we make a clone of it and remove // all other transition classes applied to ensure only the move class // is applied. var clone = el.cloneNode(); if (el._transitionClasses) { el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); }); } addClass(clone, moveClass); clone.style.display = 'none'; this.$el.appendChild(clone); var info = getTransitionInfo(clone); this.$el.removeChild(clone); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue.config.mustUseProp = mustUseProp; Vue.config.isReservedTag = isReservedTag; Vue.config.isReservedAttr = isReservedAttr; Vue.config.getTagNamespace = getTagNamespace; Vue.config.isUnknownElement = isUnknownElement; // install platform runtime directives & components extend(Vue.options.directives, platformDirectives); extend(Vue.options.components, platformComponents); // install platform patch function Vue.prototype.__patch__ = inBrowser ? patch : noop; // public mount method Vue.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return mountComponent(this, el, hydrating) }; // devtools global hook /* istanbul ignore next */ if (inBrowser) { setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue); } else { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } if (config.productionTip !== false && typeof console !== 'undefined' ) { console[console.info ? 'info' : 'log']( "You are running Vue in development mode.\n" + "Make sure to turn on production mode when deploying for production.\n" + "See more tips at https://vuejs.org/guide/deployment.html" ); } }, 0); } /* */ var defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var rawTokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index, tokenValue; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { rawTokens.push(tokenValue = text.slice(lastIndex, index)); tokens.push(JSON.stringify(tokenValue)); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); rawTokens.push({ '@binding': exp }); lastIndex = index + match[0].length; } if (lastIndex < text.length) { rawTokens.push(tokenValue = text.slice(lastIndex)); tokens.push(JSON.stringify(tokenValue)); } return { expression: tokens.join('+'), tokens: rawTokens } } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if (staticClass) { var res = parseText(staticClass, options.delimiters); if (res) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.', el.rawAttrsMap['class'] ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData }; /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ { var res = parseText(staticStyle, options.delimiters); if (res) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.', el.rawAttrsMap['style'] ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$1 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$1 }; /* */ var decoder; var he = { decode: function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } }; /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /** * Not type-checking this file because it's mostly vendor code. */ // Regular Expressions for parsing tags and attributes var attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; var dynamicArgAttribute = /^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; var ncname = "[a-zA-Z_][\\-\\.0-9_a-zA-Z" + (unicodeRegExp.source) + "]*"; var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")"; var startTagOpen = new RegExp(("^<" + qnameCapture)); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp(("^<\\/" + qnameCapture + "[^>]*>")); var doctype = /^<!DOCTYPE [^>]+>/i; // #7298: escape - to avoid being passed as HTML comment when inlined in page var comment = /^<!\--/; var conditionalComment = /^<!\[/; // Special Elements (can contain anything) var isPlainTextElement = makeMap('script,style,textarea', true); var reCache = {}; var decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n', '&#9;': '\t', '&#39;': "'" }; var encodedAttr = /&(?:lt|gt|quot|amp|#39);/g; var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#39|#10|#9);/g; // #5992 var isIgnoreNewlineTag = makeMap('pre,textarea', true); var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; }; function decodeAttr (value, shouldDecodeNewlines) { var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function (match) { return decodingMap[match]; }) } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment) { options.comment(html.substring(4, commentEnd), index, index + commentEnd + 3); } advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); if (shouldIgnoreFirstNewline(startTagMatch.tagName, html)) { advance(1); } continue } } var text = (void 0), rest = (void 0), next = (void 0); if (textEnd >= 0) { rest = html.slice(textEnd); while ( !endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) ) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); } if (textEnd < 0) { text = html; } if (text) { advance(text.length); } if (options.chars && text) { options.chars(text, index - text.length, index); } } else { var endTagLength = 0; var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var rest$1 = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298 .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest$1.length; html = rest$1; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if (!stack.length && options.warn) { options.warn(("Mal-formatted tag at end of template: \"" + html + "\""), { start: index + html.length }); } break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute))) { attr.start = index; advance(attr[0].length); attr.end = index; match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; var value = args[3] || args[4] || args[5] || ''; var shouldDecodeNewlines = tagName === 'a' && args[1] === 'href' ? options.shouldDecodeNewlinesForHref : options.shouldDecodeNewlines; attrs[i] = { name: args[1], value: decodeAttr(value, shouldDecodeNewlines) }; if (options.outputSourceRange) { attrs[i].start = args.start + args[0].match(/^\s*/).length; attrs[i].end = args.end; } } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs, start: match.start, end: match.end }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } // Find the closest opened tag of the same type if (tagName) { lowerCasedTagName = tagName.toLowerCase(); for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (i > pos || !tagName && options.warn ) { options.warn( ("tag <" + (stack[i].tag) + "> has no matching end tag."), { start: stack[i].start, end: stack[i].end } ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ var onRE = /^@|^v-on:/; var dirRE = /^v-|^@|^:|^#/; var forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; var forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; var stripParensRE = /^\(|\)$/g; var dynamicArgRE = /^\[.*\]$/; var argRE = /:(.*)$/; var bindRE = /^:|^\.|^v-bind:/; var modifierRE = /\.[^.\]]+(?=[^\]]*$)/g; var slotRE = /^v-slot(:|$)|^#/; var lineBreakRE = /[\r\n]/; var whitespaceRE$1 = /\s+/g; var invalidAttributeRE = /[\s"'<>\/=]/; var decodeHTMLCached = cached(he.decode); var emptySlotScopeToken = "_empty_"; // configurable state var warn$2; var delimiters; var transforms; var preTransforms; var postTransforms; var platformIsPreTag; var platformMustUseProp; var platformGetTagNamespace; var maybeComponent; function createASTElement ( tag, attrs, parent ) { return { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), rawAttrsMap: {}, parent: parent, children: [] } } /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$2 = options.warn || baseWarn; platformIsPreTag = options.isPreTag || no; platformMustUseProp = options.mustUseProp || no; platformGetTagNamespace = options.getTagNamespace || no; var isReservedTag = options.isReservedTag || no; maybeComponent = function (el) { return !!el.component || !isReservedTag(el.tag); }; transforms = pluckModuleFunction(options.modules, 'transformNode'); preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var whitespaceOption = options.whitespace; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; function warnOnce (msg, range) { if (!warned) { warned = true; warn$2(msg, range); } } function closeElement (element) { trimEndingWhitespace(element); if (!inVPre && !element.processed) { element = processElement(element, options); } // tree management if (!stack.length && element !== root) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { { checkRootConstraints(element); } addIfCondition(root, { exp: element.elseif, block: element }); } else { warnOnce( "Component template should contain exactly one root element. " + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead.", { start: element.start } ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else { if (element.slotScope) { // scoped slot // keep it in the children list so that v-else(-if) conditions can // find it as the prev node. var name = element.slotTarget || '"default"' ;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } currentParent.children.push(element); element.parent = currentParent; } } // final children cleanup // filter out scoped slots element.children = element.children.filter(function (c) { return !(c).slotScope; }); // remove trailing whitespace node again trimEndingWhitespace(element); // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } // apply post-transforms for (var i = 0; i < postTransforms.length; i++) { postTransforms[i](element, options); } } function trimEndingWhitespace (el) { // remove trailing whitespace node if (!inPre) { var lastNode; while ( (lastNode = el.children[el.children.length - 1]) && lastNode.type === 3 && lastNode.text === ' ' ) { el.children.pop(); } } } function checkRootConstraints (el) { if (el.tag === 'slot' || el.tag === 'template') { warnOnce( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes.', { start: el.start } ); } if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements.', el.rawAttrsMap['v-for'] ); } } parseHTML(template, { warn: warn$2, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref, shouldKeepComment: options.comments, outputSourceRange: options.outputSourceRange, start: function start (tag, attrs, unary, start$1, end) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = createASTElement(tag, attrs, currentParent); if (ns) { element.ns = ns; } { if (options.outputSourceRange) { element.start = start$1; element.end = end; element.rawAttrsMap = element.attrsList.reduce(function (cumulated, attr) { cumulated[attr.name] = attr; return cumulated }, {}); } attrs.forEach(function (attr) { if (invalidAttributeRE.test(attr.name)) { warn$2( "Invalid dynamic argument expression: attribute names cannot contain " + "spaces, quotes, <, >, / or =.", { start: attr.start + attr.name.indexOf("["), end: attr.start + attr.name.length } ); } }); } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; warn$2( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">" + ', as they will not be parsed.', { start: element.start } ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { element = preTransforms[i](element, options) || element; } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else if (!element.processed) { // structural directives processFor(element); processIf(element); processOnce(element); } if (!root) { root = element; { checkRootConstraints(root); } } if (!unary) { currentParent = element; stack.push(element); } else { closeElement(element); } }, end: function end (tag, start, end$1) { var element = stack[stack.length - 1]; // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; if (options.outputSourceRange) { element.end = end$1; } closeElement(element); }, chars: function chars (text, start, end) { if (!currentParent) { { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.', { start: start } ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored."), { start: start } ); } } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } var children = currentParent.children; if (inPre || text.trim()) { text = isTextTag(currentParent) ? text : decodeHTMLCached(text); } else if (!children.length) { // remove the whitespace-only node right after an opening tag text = ''; } else if (whitespaceOption) { if (whitespaceOption === 'condense') { // in condense mode, remove the whitespace node if it contains // line break, otherwise condense to a single space text = lineBreakRE.test(text) ? '' : ' '; } else { text = ' '; } } else { text = preserveWhitespace ? ' ' : ''; } if (text) { if (!inPre && whitespaceOption === 'condense') { // condense consecutive whitespaces into single space text = text.replace(whitespaceRE$1, ' '); } var res; var child; if (!inVPre && text !== ' ' && (res = parseText(text, delimiters))) { child = { type: 2, expression: res.expression, tokens: res.tokens, text: text }; } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { child = { type: 3, text: text }; } if (child) { if (options.outputSourceRange) { child.start = start; child.end = end; } children.push(child); } } }, comment: function comment (text, start, end) { // adding anyting as a sibling to the root node is forbidden // comments should still be allowed, but ignored if (currentParent) { var child = { type: 3, text: text, isComment: true }; if (options.outputSourceRange) { child.start = start; child.end = end; } currentParent.children.push(child); } } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var list = el.attrsList; var len = list.length; if (len) { var attrs = el.attrs = new Array(len); for (var i = 0; i < len; i++) { attrs[i] = { name: list[i].name, value: JSON.stringify(list[i].value) }; if (list[i].start != null) { attrs[i].start = list[i].start; attrs[i].end = list[i].end; } } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processElement ( element, options ) { processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = ( !element.key && !element.scopedSlots && !element.attrsList.length ); processRef(element); processSlotContent(element); processSlotOutlet(element); processComponent(element); for (var i = 0; i < transforms.length; i++) { element = transforms[i](element, options) || element; } processAttrs(element); return element } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { { if (el.tag === 'template') { warn$2( "<template> cannot be keyed. Place the key on real elements instead.", getRawBindingAttr(el, 'key') ); } if (el.for) { var iterator = el.iterator2 || el.iterator1; var parent = el.parent; if (iterator && iterator === exp && parent && parent.tag === 'transition-group') { warn$2( "Do not use v-for index as key on <transition-group> children, " + "this is the same as not using keys.", getRawBindingAttr(el, 'key'), true /* tip */ ); } } } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var res = parseFor(exp); if (res) { extend(el, res); } else { warn$2( ("Invalid v-for expression: " + exp), el.rawAttrsMap['v-for'] ); } } } function parseFor (exp) { var inMatch = exp.match(forAliasRE); if (!inMatch) { return } var res = {}; res.for = inMatch[2].trim(); var alias = inMatch[1].trim().replace(stripParensRE, ''); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { res.alias = alias.replace(forIteratorRE, '').trim(); res.iterator1 = iteratorMatch[1].trim(); if (iteratorMatch[2]) { res.iterator2 = iteratorMatch[2].trim(); } } else { res.alias = alias; } return res } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else { warn$2( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if.", el.rawAttrsMap[el.elseif ? 'v-else-if' : 'v-else'] ); } } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].type === 1) { return children[i] } else { if (children[i].text !== ' ') { warn$2( "text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " + "will be ignored.", children[i] ); } children.pop(); } } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once$$1 = getAndRemoveAttr(el, 'v-once'); if (once$$1 != null) { el.once = true; } } // handle content being passed to a component as slot, // e.g. <template slot="xxx">, <div slot-scope="xxx"> function processSlotContent (el) { var slotScope; if (el.tag === 'template') { slotScope = getAndRemoveAttr(el, 'scope'); /* istanbul ignore if */ if (slotScope) { warn$2( "the \"scope\" attribute for scoped slots have been deprecated and " + "replaced by \"slot-scope\" since 2.5. The new \"slot-scope\" attribute " + "can also be used on plain elements in addition to <template> to " + "denote scoped slots.", el.rawAttrsMap['scope'], true ); } el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope'); } else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) { /* istanbul ignore if */ if (el.attrsMap['v-for']) { warn$2( "Ambiguous combined usage of slot-scope and v-for on <" + (el.tag) + "> " + "(v-for takes higher priority). Use a wrapper <template> for the " + "scoped slot to make it clearer.", el.rawAttrsMap['slot-scope'], true ); } el.slotScope = slotScope; } // slot="xxx" var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; el.slotTargetDynamic = !!(el.attrsMap[':slot'] || el.attrsMap['v-bind:slot']); // preserve slot as an attribute for native shadow DOM compat // only for non-scoped slots. if (el.tag !== 'template' && !el.slotScope) { addAttr(el, 'slot', slotTarget, getRawBindingAttr(el, 'slot')); } } // 2.6 v-slot syntax { if (el.tag === 'template') { // v-slot on <template> var slotBinding = getAndRemoveAttrByRegex(el, slotRE); if (slotBinding) { { if (el.slotTarget || el.slotScope) { warn$2( "Unexpected mixed usage of different slot syntaxes.", el ); } if (el.parent && !maybeComponent(el.parent)) { warn$2( "<template v-slot> can only appear at the root level inside " + "the receiving component", el ); } } var ref = getSlotName(slotBinding); var name = ref.name; var dynamic = ref.dynamic; el.slotTarget = name; el.slotTargetDynamic = dynamic; el.slotScope = slotBinding.value || emptySlotScopeToken; // force it into a scoped slot for perf } } else { // v-slot on component, denotes default slot var slotBinding$1 = getAndRemoveAttrByRegex(el, slotRE); if (slotBinding$1) { { if (!maybeComponent(el)) { warn$2( "v-slot can only be used on components or <template>.", slotBinding$1 ); } if (el.slotScope || el.slotTarget) { warn$2( "Unexpected mixed usage of different slot syntaxes.", el ); } if (el.scopedSlots) { warn$2( "To avoid scope ambiguity, the default slot should also use " + "<template> syntax when there are other named slots.", slotBinding$1 ); } } // add the component's children to its default slot var slots = el.scopedSlots || (el.scopedSlots = {}); var ref$1 = getSlotName(slotBinding$1); var name$1 = ref$1.name; var dynamic$1 = ref$1.dynamic; var slotContainer = slots[name$1] = createASTElement('template', [], el); slotContainer.slotTarget = name$1; slotContainer.slotTargetDynamic = dynamic$1; slotContainer.children = el.children.filter(function (c) { if (!c.slotScope) { c.parent = slotContainer; return true } }); slotContainer.slotScope = slotBinding$1.value || emptySlotScopeToken; // remove children as they are returned from scopedSlots now el.children = []; // mark el non-plain so data gets generated el.plain = false; } } } } function getSlotName (binding) { var name = binding.name.replace(slotRE, ''); if (!name) { if (binding.name[0] !== '#') { name = 'default'; } else { warn$2( "v-slot shorthand syntax requires a slot name.", binding ); } } return dynamicArgRE.test(name) // dynamic [name] ? { name: name.slice(1, -1), dynamic: true } // static name : { name: ("\"" + name + "\""), dynamic: false } } // handle <slot/> outlets function processSlotOutlet (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if (el.key) { warn$2( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead.", getRawBindingAttr(el, 'key') ); } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, modifiers, syncGen, isDynamic; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name.replace(dirRE, '')); // support .foo shorthand syntax for the .prop modifier if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isDynamic = dynamicArgRE.test(name); if (isDynamic) { name = name.slice(1, -1); } if ( value.trim().length === 0 ) { warn$2( ("The value for a v-bind expression cannot be empty. Found in \"v-bind:" + name + "\"") ); } if (modifiers) { if (modifiers.prop && !isDynamic) { name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel && !isDynamic) { name = camelize(name); } if (modifiers.sync) { syncGen = genAssignmentCode(value, "$event"); if (!isDynamic) { addHandler( el, ("update:" + (camelize(name))), syncGen, null, false, warn$2, list[i] ); if (hyphenate(name) !== camelize(name)) { addHandler( el, ("update:" + (hyphenate(name))), syncGen, null, false, warn$2, list[i] ); } } else { // handler w/ dynamic event name addHandler( el, ("\"update:\"+(" + name + ")"), syncGen, null, false, warn$2, list[i], true // dynamic ); } } } if ((modifiers && modifiers.prop) || ( !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name) )) { addProp(el, name, value, list[i], isDynamic); } else { addAttr(el, name, value, list[i], isDynamic); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); isDynamic = dynamicArgRE.test(name); if (isDynamic) { name = name.slice(1, -1); } addHandler(el, name, value, modifiers, false, warn$2, list[i], isDynamic); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); var arg = argMatch && argMatch[1]; isDynamic = false; if (arg) { name = name.slice(0, -(arg.length + 1)); if (dynamicArgRE.test(arg)) { arg = arg.slice(1, -1); isDynamic = true; } } addDirective(el, name, rawName, value, arg, isDynamic, modifiers, list[i]); if (name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute { var res = parseText(value, delimiters); if (res) { warn$2( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.', list[i] ); } } addAttr(el, name, JSON.stringify(value), list[i]); // #6887 firefox doesn't update muted state if set via attribute // even immediately after element creation if (!el.component && name === 'muted' && platformMustUseProp(el.tag, el.attrsMap.type, name)) { addProp(el, name, 'true', list[i]); } } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if ( map[attrs[i].name] && !isIE && !isEdge ) { warn$2('duplicate attribute: ' + attrs[i].name, attrs[i]); } map[attrs[i].name] = attrs[i].value; } return map } // for script (e.g. type="x/template") or style, do not decode content function isTextTag (el) { return el.tag === 'script' || el.tag === 'style' } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$2( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead.", el.rawAttrsMap['v-model'] ); } _el = _el.parent; } } /* */ function preTransformNode (el, options) { if (el.tag === 'input') { var map = el.attrsMap; if (!map['v-model']) { return } var typeBinding; if (map[':type'] || map['v-bind:type']) { typeBinding = getBindingAttr(el, 'type'); } if (!map.type && !typeBinding && map['v-bind']) { typeBinding = "(" + (map['v-bind']) + ").type"; } if (typeBinding) { var ifCondition = getAndRemoveAttr(el, 'v-if', true); var ifConditionExtra = ifCondition ? ("&&(" + ifCondition + ")") : ""; var hasElse = getAndRemoveAttr(el, 'v-else', true) != null; var elseIfCondition = getAndRemoveAttr(el, 'v-else-if', true); // 1. checkbox var branch0 = cloneASTElement(el); // process for on the main node processFor(branch0); addRawAttr(branch0, 'type', 'checkbox'); processElement(branch0, options); branch0.processed = true; // prevent it from double-processed branch0.if = "(" + typeBinding + ")==='checkbox'" + ifConditionExtra; addIfCondition(branch0, { exp: branch0.if, block: branch0 }); // 2. add radio else-if condition var branch1 = cloneASTElement(el); getAndRemoveAttr(branch1, 'v-for', true); addRawAttr(branch1, 'type', 'radio'); processElement(branch1, options); addIfCondition(branch0, { exp: "(" + typeBinding + ")==='radio'" + ifConditionExtra, block: branch1 }); // 3. other var branch2 = cloneASTElement(el); getAndRemoveAttr(branch2, 'v-for', true); addRawAttr(branch2, ':type', typeBinding); processElement(branch2, options); addIfCondition(branch0, { exp: ifCondition, block: branch2 }); if (hasElse) { branch0.else = true; } else if (elseIfCondition) { branch0.elseif = elseIfCondition; } return branch0 } } } function cloneASTElement (el) { return createASTElement(el.tag, el.attrsList.slice(), el.parent) } var model$1 = { preTransformNode: preTransformNode }; var modules$1 = [ klass$1, style$1, model$1 ]; /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")"), dir); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"), dir); } } var directives$1 = { model: model, text: text, html: html }; /* */ var baseOptions = { expectHTML: true, modules: modules$1, directives: directives$1, isPreTag: isPreTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, canBeLeftOpenTag: canBeLeftOpenTag, isReservedTag: isReservedTag, getTagNamespace: getTagNamespace, staticKeys: genStaticKeys(modules$1) }; /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic$1(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap' + (keys ? ',' + keys : '') ) } function markStatic$1 (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic$1(child); if (!child.static) { node.static = false; } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { var block = node.ifConditions[i$1].block; markStatic$1(block); if (!block.static) { node.static = false; } } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { markStaticRoots(node.ifConditions[i$1].block, isInFor); } } } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function(?:\s+[\w$]+)?\s*\(/; var fnInvokeRE = /\([^)]*?\);*$/; var simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // KeyboardEvent.keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; // KeyboardEvent.key aliases var keyNames = { // #7880: IE11 and Edge use `Esc` for Escape key name. esc: ['Esc', 'Escape'], tab: 'Tab', enter: 'Enter', // #9112: IE11 uses `Spacebar` for Space key name. space: [' ', 'Spacebar'], // #7806: IE11 uses key names without `Arrow` prefix for arrow keys. up: ['Up', 'ArrowUp'], left: ['Left', 'ArrowLeft'], right: ['Right', 'ArrowRight'], down: ['Down', 'ArrowDown'], // #9112: IE11 uses `Del` for Delete key name. 'delete': ['Backspace', 'Delete', 'Del'] }; // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once var genGuard = function (condition) { return ("if(" + condition + ")return null;"); }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: genGuard("$event.target !== $event.currentTarget"), ctrl: genGuard("!$event.ctrlKey"), shift: genGuard("!$event.shiftKey"), alt: genGuard("!$event.altKey"), meta: genGuard("!$event.metaKey"), left: genGuard("'button' in $event && $event.button !== 0"), middle: genGuard("'button' in $event && $event.button !== 1"), right: genGuard("'button' in $event && $event.button !== 2") }; function genHandlers ( events, isNative ) { var prefix = isNative ? 'nativeOn:' : 'on:'; var staticHandlers = ""; var dynamicHandlers = ""; for (var name in events) { var handlerCode = genHandler(events[name]); if (events[name] && events[name].dynamic) { dynamicHandlers += name + "," + handlerCode + ","; } else { staticHandlers += "\"" + name + "\":" + handlerCode + ","; } } staticHandlers = "{" + (staticHandlers.slice(0, -1)) + "}"; if (dynamicHandlers) { return prefix + "_d(" + staticHandlers + ",[" + (dynamicHandlers.slice(0, -1)) + "])" } else { return prefix + staticHandlers } } function genHandler (handler) { if (!handler) { return 'function(){}' } if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(handler); }).join(',')) + "]") } var isMethodPath = simplePathRE.test(handler.value); var isFunctionExpression = fnExpRE.test(handler.value); var isFunctionInvocation = simplePathRE.test(handler.value.replace(fnInvokeRE, '')); if (!handler.modifiers) { if (isMethodPath || isFunctionExpression) { return handler.value } return ("function($event){" + (isFunctionInvocation ? ("return " + (handler.value)) : handler.value) + "}") // inline statement } else { var code = ''; var genModifierCode = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key]; // left/right if (keyCodes[key]) { keys.push(key); } } else if (key === 'exact') { var modifiers = (handler.modifiers); genModifierCode += genGuard( ['ctrl', 'shift', 'alt', 'meta'] .filter(function (keyModifier) { return !modifiers[keyModifier]; }) .map(function (keyModifier) { return ("$event." + keyModifier + "Key"); }) .join('||') ); } else { keys.push(key); } } if (keys.length) { code += genKeyFilter(keys); } // Make sure modifiers like prevent and stop get executed after key filtering if (genModifierCode) { code += genModifierCode; } var handlerCode = isMethodPath ? ("return " + (handler.value) + "($event)") : isFunctionExpression ? ("return (" + (handler.value) + ")($event)") : isFunctionInvocation ? ("return " + (handler.value)) : handler.value; return ("function($event){" + code + handlerCode + "}") } } function genKeyFilter (keys) { return ( // make sure the key filters only apply to KeyboardEvents // #9441: can't use 'keyCode' in $event because Chrome autofill fires fake // key events that do not have keyCode property... "if(!$event.type.indexOf('key')&&" + (keys.map(genFilterCode).join('&&')) + ")return null;" ) } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var keyCode = keyCodes[key]; var keyName = keyNames[key]; return ( "_k($event.keyCode," + (JSON.stringify(key)) + "," + (JSON.stringify(keyCode)) + "," + "$event.key," + "" + (JSON.stringify(keyName)) + ")" ) } /* */ function on (el, dir) { if (dir.modifiers) { warn("v-on without argument does not support modifiers."); } el.wrapListeners = function (code) { return ("_g(" + code + "," + (dir.value) + ")"); }; } /* */ function bind$1 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + "," + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ")") }; } /* */ var baseDirectives = { on: on, bind: bind$1, cloak: noop }; /* */ var CodegenState = function CodegenState (options) { this.options = options; this.warn = options.warn || baseWarn; this.transforms = pluckModuleFunction(options.modules, 'transformCode'); this.dataGenFns = pluckModuleFunction(options.modules, 'genData'); this.directives = extend(extend({}, baseDirectives), options.directives); var isReservedTag = options.isReservedTag || no; this.maybeComponent = function (el) { return !!el.component || !isReservedTag(el.tag); }; this.onceId = 0; this.staticRenderFns = []; this.pre = false; }; function generate ( ast, options ) { var state = new CodegenState(options); var code = ast ? genElement(ast, state) : '_c("div")'; return { render: ("with(this){return " + code + "}"), staticRenderFns: state.staticRenderFns } } function genElement (el, state) { if (el.parent) { el.pre = el.pre || el.parent.pre; } if (el.staticRoot && !el.staticProcessed) { return genStatic(el, state) } else if (el.once && !el.onceProcessed) { return genOnce(el, state) } else if (el.for && !el.forProcessed) { return genFor(el, state) } else if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.tag === 'template' && !el.slotTarget && !state.pre) { return genChildren(el, state) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el, state) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el, state); } else { var data; if (!el.plain || (el.pre && state.maybeComponent(el))) { data = genData$2(el, state); } var children = el.inlineTemplate ? null : genChildren(el, state, true); code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < state.transforms.length; i++) { code = state.transforms[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el, state) { el.staticProcessed = true; // Some elements (templates) need to behave differently inside of a v-pre // node. All pre nodes are static roots, so we can use this as a location to // wrap a state change and reset it upon exiting the pre node. var originalPreState = state.pre; if (el.pre) { state.pre = el.pre; } state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}")); state.pre = originalPreState; return ("_m(" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")") } // v-once function genOnce (el, state) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { state.warn( "v-once can only be used inside v-for that is keyed. ", el.rawAttrsMap['v-once'] ); return genElement(el, state) } return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + "," + key + ")") } else { return genStatic(el, state) } } function genIf ( el, state, altGen, altEmpty ) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty) } function genIfConditions ( conditions, state, altGen, altEmpty ) { if (!conditions.length) { return altEmpty || '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions, state, altGen, altEmpty))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return altGen ? altGen(el, state) : el.once ? genOnce(el, state) : genElement(el, state) } } function genFor ( el, state, altGen, altHelper ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; if (state.maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key ) { state.warn( "<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " + "v-for should have explicit keys. " + "See https://vuejs.org/guide/list.html#key for more info.", el.rawAttrsMap['v-for'], true /* tip */ ); } el.forProcessed = true; // avoid recursion return (altHelper || '_l') + "((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + ((altGen || genElement)(el, state)) + '})' } function genData$2 (el, state) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el, state); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < state.dataGenFns.length; i++) { data += state.dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:" + (genProps(el.attrs)) + ","; } // DOM props if (el.props) { data += "domProps:" + (genProps(el.props)) + ","; } // event handlers if (el.events) { data += (genHandlers(el.events, false)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true)) + ","; } // slot target // only for non-scoped slots if (el.slotTarget && !el.slotScope) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el, el.scopedSlots, state)) + ","; } // component v-model if (el.model) { data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},"; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el, state); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind dynamic argument wrap // v-bind with dynamic arguments must be applied using the same v-bind object // merge helper so that class/style/mustUseProp attrs are handled correctly. if (el.dynamicAttrs) { data = "_b(" + data + ",\"" + (el.tag) + "\"," + (genProps(el.dynamicAttrs)) + ")"; } // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } // v-on data wrap if (el.wrapListeners) { data = el.wrapListeners(data); } return data } function genDirectives (el, state) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = state.directives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, state.warn); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:" + (dir.isDynamicArg ? dir.arg : ("\"" + (dir.arg) + "\""))) : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el, state) { var ast = el.children[0]; if (el.children.length !== 1 || ast.type !== 1) { state.warn( 'Inline-template components must have exactly one child element.', { start: el.start } ); } if (ast && ast.type === 1) { var inlineRenderFns = generate(ast, state.options); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots ( el, slots, state ) { // by default scoped slots are considered "stable", this allows child // components with only scoped slots to skip forced updates from parent. // but in some cases we have to bail-out of this optimization // for example if the slot contains dynamic names, has v-if or v-for on them... var needsForceUpdate = el.for || Object.keys(slots).some(function (key) { var slot = slots[key]; return ( slot.slotTargetDynamic || slot.if || slot.for || containsSlotChild(slot) // is passing down slot from parent which may be dynamic ) }); // #9534: if a component with scoped slots is inside a conditional branch, // it's possible for the same component to be reused but with different // compiled slot content. To avoid that, we generate a unique key based on // the generated code of all the slot contents. var needsKey = !!el.if; // OR when it is inside another scoped slot or v-for (the reactivity may be // disconnected due to the intermediate scope variable) // #9438, #9506 // TODO: this can be further optimized by properly analyzing in-scope bindings // and skip force updating ones that do not actually use scope variables. if (!needsForceUpdate) { var parent = el.parent; while (parent) { if ( (parent.slotScope && parent.slotScope !== emptySlotScopeToken) || parent.for ) { needsForceUpdate = true; break } if (parent.if) { needsKey = true; } parent = parent.parent; } } var generatedSlots = Object.keys(slots) .map(function (key) { return genScopedSlot(slots[key], state); }) .join(','); return ("scopedSlots:_u([" + generatedSlots + "]" + (needsForceUpdate ? ",null,true" : "") + (!needsForceUpdate && needsKey ? (",null,false," + (hash(generatedSlots))) : "") + ")") } function hash(str) { var hash = 5381; var i = str.length; while(i) { hash = (hash * 33) ^ str.charCodeAt(--i); } return hash >>> 0 } function containsSlotChild (el) { if (el.type === 1) { if (el.tag === 'slot') { return true } return el.children.some(containsSlotChild) } return false } function genScopedSlot ( el, state ) { var isLegacySyntax = el.attrsMap['slot-scope']; if (el.if && !el.ifProcessed && !isLegacySyntax) { return genIf(el, state, genScopedSlot, "null") } if (el.for && !el.forProcessed) { return genFor(el, state, genScopedSlot) } var slotScope = el.slotScope === emptySlotScopeToken ? "" : String(el.slotScope); var fn = "function(" + slotScope + "){" + "return " + (el.tag === 'template' ? el.if && isLegacySyntax ? ("(" + (el.if) + ")?" + (genChildren(el, state) || 'undefined') + ":undefined") : genChildren(el, state) || 'undefined' : genElement(el, state)) + "}"; // reverse proxy v-slot without scope on this.$slots var reverseProxy = slotScope ? "" : ",proxy:true"; return ("{key:" + (el.slotTarget || "\"default\"") + ",fn:" + fn + reverseProxy + "}") } function genChildren ( el, state, checkSkip, altGenElement, altGenNode ) { var children = el.children; if (children.length) { var el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot' ) { var normalizationType = checkSkip ? state.maybeComponent(el$1) ? ",1" : ",0" : ""; return ("" + ((altGenElement || genElement)(el$1, state)) + normalizationType) } var normalizationType$1 = checkSkip ? getNormalizationType(children, state.maybeComponent) : 0; var gen = altGenNode || genNode; return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType$1 ? ("," + normalizationType$1) : '')) } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType ( children, maybeComponent ) { var res = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.type !== 1) { continue } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) { res = 2; break } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) { res = 1; } } return res } function needsNormalization (el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot' } function genNode (node, state) { if (node.type === 1) { return genElement(node, state) } else if (node.type === 3 && node.isComment) { return genComment(node) } else { return genText(node) } } function genText (text) { return ("_v(" + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ")") } function genComment (comment) { return ("_e(" + (JSON.stringify(comment.text)) + ")") } function genSlot (el, state) { var slotName = el.slotName || '"default"'; var children = genChildren(el, state); var res = "_t(" + slotName + (children ? ("," + children) : ''); var attrs = el.attrs || el.dynamicAttrs ? genProps((el.attrs || []).concat(el.dynamicAttrs || []).map(function (attr) { return ({ // slot props are camelized name: camelize(attr.name), value: attr.value, dynamic: attr.dynamic }); })) : null; var bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ",null"; } if (attrs) { res += "," + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + "," + bind$$1; } return res + ')' } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent ( componentName, el, state ) { var children = el.inlineTemplate ? null : genChildren(el, state, true); return ("_c(" + componentName + "," + (genData$2(el, state)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var staticProps = ""; var dynamicProps = ""; for (var i = 0; i < props.length; i++) { var prop = props[i]; var value = transformSpecialNewlines(prop.value); if (prop.dynamic) { dynamicProps += (prop.name) + "," + value + ","; } else { staticProps += "\"" + (prop.name) + "\":" + value + ","; } } staticProps = "{" + (staticProps.slice(0, -1)) + "}"; if (dynamicProps) { return ("_d(" + staticProps + ",[" + (dynamicProps.slice(0, -1)) + "])") } else { return staticProps } } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ // these keywords should not appear inside expressions, but operators like // typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // these unary operators should not be used as property/method names var unaryOperatorsRE = new RegExp('\\b' + ( 'delete,typeof,void' ).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'); // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast, warn) { if (ast) { checkNode(ast, warn); } } function checkNode (node, warn) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { var range = node.rawAttrsMap[name]; if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), warn, range); } else if (name === 'v-slot' || name[0] === '#') { checkFunctionParameterExpression(value, (name + "=\"" + value + "\""), warn, range); } else if (onRE.test(name)) { checkEvent(value, (name + "=\"" + value + "\""), warn, range); } else { checkExpression(value, (name + "=\"" + value + "\""), warn, range); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], warn); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, warn, node); } } function checkEvent (exp, text, warn, range) { var stripped = exp.replace(stripStringRE, ''); var keywordMatch = stripped.match(unaryOperatorsRE); if (keywordMatch && stripped.charAt(keywordMatch.index - 1) !== '$') { warn( "avoid using JavaScript unary operator as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()), range ); } checkExpression(exp, text, warn, range); } function checkFor (node, text, warn, range) { checkExpression(node.for || '', text, warn, range); checkIdentifier(node.alias, 'v-for alias', text, warn, range); checkIdentifier(node.iterator1, 'v-for iterator', text, warn, range); checkIdentifier(node.iterator2, 'v-for iterator', text, warn, range); } function checkIdentifier ( ident, type, text, warn, range ) { if (typeof ident === 'string') { try { new Function(("var " + ident + "=_")); } catch (e) { warn(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())), range); } } } function checkExpression (exp, text, warn, range) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { warn( "avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\"\n Raw expression: " + (text.trim()), range ); } else { warn( "invalid expression: " + (e.message) + " in\n\n" + " " + exp + "\n\n" + " Raw expression: " + (text.trim()) + "\n", range ); } } } function checkFunctionParameterExpression (exp, text, warn, range) { try { new Function(exp, ''); } catch (e) { warn( "invalid function parameter expression: " + (e.message) + " in\n\n" + " " + exp + "\n\n" + " Raw expression: " + (text.trim()) + "\n", range ); } } /* */ var range = 2; function generateCodeFrame ( source, start, end ) { if ( start === void 0 ) start = 0; if ( end === void 0 ) end = source.length; var lines = source.split(/\r?\n/); var count = 0; var res = []; for (var i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start) { for (var j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) { continue } res.push(("" + (j + 1) + (repeat$1(" ", 3 - String(j + 1).length)) + "| " + (lines[j]))); var lineLength = lines[j].length; if (j === i) { // push underline var pad = start - (count - lineLength) + 1; var length = end > count ? lineLength - pad : end - start; res.push(" | " + repeat$1(" ", pad) + repeat$1("^", length)); } else if (j > i) { if (end > count) { var length$1 = Math.min(end - count, lineLength); res.push(" | " + repeat$1("^", length$1)); } count += lineLength + 1; } } break } } return res.join('\n') } function repeat$1 (str, n) { var result = ''; if (n > 0) { while (true) { // eslint-disable-line if (n & 1) { result += str; } n >>>= 1; if (n <= 0) { break } str += str; } } return result } /* */ function createFunction (code, errors) { try { return new Function(code) } catch (err) { errors.push({ err: err, code: code }); return noop } } function createCompileToFunctionFn (compile) { var cache = Object.create(null); return function compileToFunctions ( template, options, vm ) { options = extend({}, options); var warn$$1 = options.warn || warn; delete options.warn; /* istanbul ignore if */ { // detect possible CSP restriction try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { warn$$1( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } // check cache var key = options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key] } // compile var compiled = compile(template, options); // check compilation errors/tips { if (compiled.errors && compiled.errors.length) { if (options.outputSourceRange) { compiled.errors.forEach(function (e) { warn$$1( "Error compiling template:\n\n" + (e.msg) + "\n\n" + generateCodeFrame(template, e.start, e.end), vm ); }); } else { warn$$1( "Error compiling template:\n\n" + template + "\n\n" + compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n', vm ); } } if (compiled.tips && compiled.tips.length) { if (options.outputSourceRange) { compiled.tips.forEach(function (e) { return tip(e.msg, vm); }); } else { compiled.tips.forEach(function (msg) { return tip(msg, vm); }); } } } // turn code into functions var res = {}; var fnGenErrors = []; res.render = createFunction(compiled.render, fnGenErrors); res.staticRenderFns = compiled.staticRenderFns.map(function (code) { return createFunction(code, fnGenErrors) }); // check function generation errors. // this should only happen if there is a bug in the compiler itself. // mostly for codegen development use /* istanbul ignore if */ { if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) { warn$$1( "Failed to generate render function:\n\n" + fnGenErrors.map(function (ref) { var err = ref.err; var code = ref.code; return ((err.toString()) + " in\n\n" + code + "\n"); }).join('\n'), vm ); } } return (cache[key] = res) } } /* */ function createCompilerCreator (baseCompile) { return function createCompiler (baseOptions) { function compile ( template, options ) { var finalOptions = Object.create(baseOptions); var errors = []; var tips = []; var warn = function (msg, range, tip) { (tip ? tips : errors).push(msg); }; if (options) { if (options.outputSourceRange) { // $flow-disable-line var leadingSpaceLength = template.match(/^\s*/)[0].length; warn = function (msg, range, tip) { var data = { msg: msg }; if (range) { if (range.start != null) { data.start = range.start + leadingSpaceLength; } if (range.end != null) { data.end = range.end + leadingSpaceLength; } } (tip ? tips : errors).push(data); }; } // merge custom modules if (options.modules) { finalOptions.modules = (baseOptions.modules || []).concat(options.modules); } // merge custom directives if (options.directives) { finalOptions.directives = extend( Object.create(baseOptions.directives || null), options.directives ); } // copy other options for (var key in options) { if (key !== 'modules' && key !== 'directives') { finalOptions[key] = options[key]; } } } finalOptions.warn = warn; var compiled = baseCompile(template.trim(), finalOptions); { detectErrors(compiled.ast, warn); } compiled.errors = errors; compiled.tips = tips; return compiled } return { compile: compile, compileToFunctions: createCompileToFunctionFn(compile) } } } /* */ // `createCompilerCreator` allows creating compilers that use alternative // parser/optimizer/codegen, e.g the SSR optimizing compiler. // Here we just export a default compiler using the default parts. var createCompiler = createCompilerCreator(function baseCompile ( template, options ) { var ast = parse(template.trim(), options); if (options.optimize !== false) { optimize(ast, options); } var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } }); /* */ var ref$1 = createCompiler(baseOptions); var compile = ref$1.compile; var compileToFunctions = ref$1.compileToFunctions; /* */ // check whether current browser encodes a char inside attribute values var div; function getShouldDecode (href) { div = div || document.createElement('div'); div.innerHTML = href ? "<a href=\"\n\"/>" : "<div a=\"\n\"/>"; return div.innerHTML.indexOf('&#10;') > 0 } // #3663: IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false; // #6828: chrome encodes content in a[href] var shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false; /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue.prototype.$mount; Vue.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if (!template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { /* istanbul ignore if */ if (config.performance && mark) { mark('compile'); } var ref = compileToFunctions(template, { outputSourceRange: "development" !== 'production', shouldDecodeNewlines: shouldDecodeNewlines, shouldDecodeNewlinesForHref: shouldDecodeNewlinesForHref, delimiters: options.delimiters, comments: options.comments }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; /* istanbul ignore if */ if (config.performance && mark) { mark('compile end'); measure(("vue " + (this._name) + " compile"), 'compile', 'compile end'); } } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue.compile = compileToFunctions; return Vue; }));
/* * Copyright (c) 2015 - present Adobe Systems Incorporated. All rights reserved. * * 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. * */ define(function (require, exports, module) { "use strict"; var TokenUtils = require("utils/TokenUtils"); // Enumerations for token types. var TOKEN_KEY = 1, TOKEN_VALUE = 2; // Whitelist for allowed value types. var valueTokenTypes = ["atom", "string", "number", "variable"]; // Reg-ex to match colon, comma, opening bracket of an array and white-space. var regexAllowedChars = /(?:^[:,\[]$)|(?:^\s+$)/; /** * @private * * Returns an object that represents all its parameters * * @param {!Object} token CodeMirror token * @param {!number} tokenType Type of current token * @param {!number} offset Offset in current token * @param {!String} keyName Name of corresponding key * @param {String} valueName Name of current value * @param {String} parentKeyName Name of parent key name * @param {Boolean} isArray Whether or not we are inside an array * @param {Array.<String>} exclusionList An array of keys that have already been used in the context of an object * @param {Boolean} shouldReplace Should we just replace the current token or also add colons/braces/brackets to it * @return {!{token: Object, tokenType: number, offset: number, keyName: String, valueName: String, parentKeyName: String, isArray: Boolean, exclusionList: Array.<String>, shouldReplace: Boolean}} */ function _createContextInfo(token, tokenType, offset, keyName, valueName, parentKeyName, isArray, exclusionList, shouldReplace) { return { token: token || null, tokenType: tokenType || null, offset: offset || 0, keyName: keyName || null, valueName: valueName || null, parentKeyName: parentKeyName || null, isArray: isArray || false, exclusionList: exclusionList || [], shouldReplace: shouldReplace || false }; } /** * Removes the quotes around a string * * @param {!String} string * @return {String} */ function stripQuotes(string) { if (string) { if (/^['"]$/.test(string.charAt(0))) { string = string.substr(1); } if (/^['"]$/.test(string.substr(-1, 1))) { string = string.substr(0, string.length - 1); } } return string; } /** * @private * * Returns the name of parent object * * @param {!{editor:!CodeMirror, pos:!{ch:number, line:number}, token:Object}} ctx * @return {String} */ function _getParentKeyName(ctx) { var parentKeyName, braceParity = 1, hasColon; // Move the context back to find the parent key. while (TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctx)) { if (ctx.token.type === null) { if (ctx.token.string === "}") { braceParity++; } else if (ctx.token.string === "{") { braceParity--; } } if (braceParity === 0) { while (TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctx)) { if (ctx.token.type === null && ctx.token.string === ":") { hasColon = true; } else if (ctx.token.type === "string property") { parentKeyName = stripQuotes(ctx.token.string); break; } } break; } } if (parentKeyName && hasColon) { return parentKeyName; } return null; } /** * @private * * Returns a list of properties that are already used by an object * * @param {!Editor} editor * @param {!{line: number, ch: number}} constPos * @return {Array.<String>} */ function _getExclusionList(editor, constPos) { var ctxPrev, ctxNext, exclusionList = [], pos, braceParity; // Move back to find exclusions. pos = $.extend({}, constPos); braceParity = 1; ctxPrev = TokenUtils.getInitialContext(editor._codeMirror, pos); while (TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctxPrev)) { if (ctxPrev.token.type === null) { if (ctxPrev.token.string === "}") { braceParity++; } else if (ctxPrev.token.string === "{") { braceParity--; } } if (braceParity === 1 && ctxPrev.token.type === "string property") { exclusionList.push(stripQuotes(ctxPrev.token.string)); } else if (braceParity === 0) { break; } } // Move forward and find exclusions. pos = $.extend({}, constPos); braceParity = 1; ctxNext = TokenUtils.getInitialContext(editor._codeMirror, pos); while (TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctxNext)) { if (ctxNext.token.type === null) { if (ctxNext.token.string === "{") { braceParity++; } else if (ctxNext.token.string === "}") { braceParity--; } } if (braceParity === 1 && ctxNext.token.type === "string property") { exclusionList.push(stripQuotes(ctxNext.token.string)); } else if (braceParity === 0) { break; } } return exclusionList; } /** * Returns context info at a given position in editor * * @param {!Editor} editor * @param {!{line: number, ch: number}} constPos Position of cursor in the editor * @param {Boolean} requireParent If true will look for parent key name * @param {Boolean} requireNextToken if true we can replace the next token of a value. * @return {!{token: Object, tokenType: number, offset: number, keyName: String, valueName: String, parentKeyName: String, isArray: Boolean, exclusionList: Array.<String>, shouldReplace: Boolean}} */ function getContextInfo(editor, constPos, requireParent, requireNextToken) { var pos, ctx, ctxPrev, ctxNext, offset, keyName, valueName, parentKeyName, isArray, exclusionList, hasColon, hasComma, hasBracket, shouldReplace; pos = $.extend({}, constPos); ctx = TokenUtils.getInitialContext(editor._codeMirror, pos); offset = TokenUtils.offsetInToken(ctx); if (ctx.token && ctx.token.type === "string property") { // String literals used as keys. // Disallow hints if cursor is out of the string. if (/^['"]$/.test(ctx.token.string.substr(-1, 1)) && ctx.token.string.length !== 1 && ctx.token.end === pos.ch) { return null; } keyName = stripQuotes(ctx.token.string); // Get parent key name. if (requireParent) { ctxPrev = $.extend(true, {}, ctx); parentKeyName = stripQuotes(_getParentKeyName(ctxPrev)); } // Check if the key is followed by a colon, so we should not append colon again. ctxNext = $.extend(true, {}, ctx); TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctxNext); if (ctxNext.token.type === null && ctxNext.token.string === ":") { shouldReplace = true; } // Get an exclusion list of properties. pos = $.extend({}, constPos); exclusionList = _getExclusionList(editor, pos); return _createContextInfo(ctx.token, TOKEN_KEY, offset, keyName, valueName, parentKeyName, null, exclusionList, shouldReplace); } else if (ctx.token && (valueTokenTypes.indexOf(ctx.token.type) !== -1 || (ctx.token.type === null && regexAllowedChars.test(ctx.token.string)))) { // Boolean, String, Number and variable literal values. // Disallow hints if cursor is out of the string. if (ctx.token.type === "string" && /^['"]$/.test(ctx.token.string.substr(-1, 1)) && ctx.token.string.length !== 1 && ctx.token.end === pos.ch) { return null; } valueName = ctx.token.string; // Check the current token if (ctx.token.type === null) { if (ctx.token.string === ":") { hasColon = true; } else if (ctx.token.string === ",") { hasComma = true; } else if (ctx.token.string === "[") { hasBracket = true; } } // move context back and find corresponding key name. ctxPrev = $.extend(true, {}, ctx); while (TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctxPrev)) { if (ctxPrev.token.type === "string property") { keyName = stripQuotes(ctxPrev.token.string); break; } else if (ctxPrev.token.type === null) { if (ctxPrev.token.string === ":") { hasColon = true; } else if (ctxPrev.token.string === ",") { hasComma = true; } else if (ctxPrev.token.string === "[") { hasBracket = true; } else { return null; } } else if (!hasComma) { return null; } } // If no key name or colon found OR // If we have a comma but no opening bracket, return null. if ((!keyName || !hasColon) || (hasComma && !hasBracket)) { return null; } else { isArray = hasBracket; } // Get parent key name. if (requireParent) { ctxPrev = $.extend(true, {}, ctx); parentKeyName = stripQuotes(_getParentKeyName(ctxPrev)); } // Check if we can replace the next token of a value. ctxNext = $.extend(true, {}, ctx); TokenUtils.moveNextToken(ctxNext); if (requireNextToken && valueTokenTypes.indexOf(ctxNext.token.type) !== -1) { shouldReplace = true; } return _createContextInfo((shouldReplace) ? ctxNext.token : ctx.token, TOKEN_VALUE, offset, keyName, valueName, parentKeyName, isArray, null, shouldReplace); } return null; } // Expose public API. exports.TOKEN_KEY = TOKEN_KEY; exports.TOKEN_VALUE = TOKEN_VALUE; exports.regexAllowedChars = regexAllowedChars; exports.getContextInfo = getContextInfo; exports.stripQuotes = stripQuotes; });
// Paver // Description: A minimal panorama/image viewer replicating the effect seen in Facebook Pages app // Version: 1.0.0 // Author: Terry Mun // Author URI: http://terrymun.com ;(function ( $, window, document, undefined ) { "use strict"; // Create the defaults once var $w = $(window), $d = $(document), pluginName = "paver", defaults = { // Failure message settings failureMessage: 'Scroll left/right to pan through panorama.', failureMessageInsert: 'after', gracefulFailure: true, // Display settings meta: false, responsive: true, startPosition: 0.5, // Minimum overflow before panorama gets converted into a Paver instance minimumOverflow: 200, // Performance grain: 3, panningThrottle: 100, resizeThrottle: 500, // For mousemove event mouseSmoothingFunction: 'linear', // For deviceOrientationEvent tilt: true, tiltSensitivity: 0.2, tiltScrollerPersistence: 500, tiltSmoothingFunction: 'gaussian', tiltThresholdPortrait: 12, tiltThresholdLandscape: 24 }; // The actual plugin constructor var Plugin = function(element, options, check) { // Assign element this.element = element; this.check = check; // Merge defaults into options, into dataset this.settings = $.extend({}, defaults, options, $(this.element).data()); // Coerce settings if(parseInt(this.settings.grain <= 0)) { this.settings.grain = 1; } this.settings.startPosition = Math.max(Math.min(this.settings.startPosition, 1), 0); this.settings.tiltThresholdPortrait = Math.max(Math.min(this.settings.tiltThresholdPortrait, 180), 0); this.settings.tiltThresholdLandscape = Math.max(Math.min(this.settings.tiltThresholdLandscape, 180), 0); // Store plugin name this._name = pluginName; // Initialize if(this.check.features.hasGyroscope === true) { // Has functional gyroscope this.init(); } else { // No functional gyroscope if(this.check.features.isTouch) { this.fallback(); } else { this.init(); } } } // Public functions $.extend(Plugin.prototype, { init: function () { // Trigger custom enabled event $d.trigger('enabled.paver'); // Define elements _fun.defineElements(this); var paver = this; // Only perform initialization when it is NOT yet initialized if(!paver.instanceData || !paver.instanceData.initialized) { paver.instanceData = {}; // Initialize and store original node paver.instanceData.initialized = true; paver.instanceData.originalNode = paver.$t.html(); // DOM replacement _fun.domReplacement(this); // Sniff out container dimensions and get center _fun.getContainerDimensions(this); _fun.getCenter(this); // Wait for panorama to load var img = new Image(); img.onload = function() { // Fire image loaded event paver.$t.trigger('imageLoadDone.paver'); // Set panorama dimensions paver.instanceData.naturalWidth = paver.$p[0].naturalWidth; paver.instanceData.naturalHeight = paver.$p[0].naturalHeight; paver.instanceData.panoAspectRatio = paver.instanceData.naturalWidth/paver.instanceData.naturalHeight; paver.instanceData.containerAspectRatio = paver.instanceData.outerWidth/paver.instanceData.outerHeight; // Panorama replacement _fun.replacePanorama(paver); // Compute _fun.compute(paver); // Check if we really need to bind events if( paver.instanceData.containerAspectRatio <= paver.instanceData.panoAspectRatio && paver.instanceData.outerWidth <= paver.instanceData.computedWidth - paver.settings.minimumOverflow ) { // Position panorama centrally the first time paver.instanceData.panCounter = 0; paver.pan({ xPos: paver.settings.startPosition, yPos: paver.settings.startPosition }); // Turn on paver paver.$t.addClass('paver--on'); // Bind events _fun.bindEvents(paver); // Update dimensions and recompute upon window resize, or custom event $w.on('resize', $.throttle(paver.settings.resizeThrottle, function() { paver.recompute(); })); // Here we call public functions by listening to namespaced events // Recompute paver.$t.on('recompute.paver', function() { paver.recompute(); }); // Destroy paver.$t.on('destroy.paver', function() { paver.destroy(); }); // Pan paver.$t.on('pan.paver', function(e, ratio) { paver.pan(ratio); }); } else { } } img.src = paver.$p.attr('src'); } }, fallback: function() { // Trigger custom fallback event $d.trigger('disabled.paver'); // If failure message is turned on if(this.settings.gracefulFailure) { var $t = $(this.element), $msg = $('<div />', { 'class': 'paver__fallbackMessage' }); $t .addClass('paver--fallback'); // DOM insertion of message // Coerce insert position to lower case switch (this.settings.failureMessageInsert.toLowerCase()) { case 'after': $t.after($msg.html(this.settings.failureMessage)); break; case 'before': $t.before($msg.html(this.settings.failureMessage)); break; case 'prepend': $t.prepend($msg.html(this.settings.failureMessage)); break; case 'append': $t.append($msg.html(this.settings.failureMessage)); break; default: $t.after($msg.html(this.settings.failureMessage)); break; } $t.trigger('fallbackend.paver'); } }, unbindEvents: function() { $(this.element) .off('mousemove.paver devicetilt.paver') .removeClass('paver--on'); }, destroy: function(a) { var pluginData = $(this.element).data('plugin_paver'); if(pluginData) { // Unbind events this.unbindEvents(); // DOM reversal $(this.element) .trigger('destroyed.paver') // Fire destroyed event .removeClass('paver--initialized paver--ready') // Remove classes .empty() // Empty element .html(pluginData.instanceData.originalNode); // Attach original node // Destroy plugin data entirely $(this.element).data('plugin_paver', null); } }, recompute: function() { var $t = $(this.element), paver = $t.data('plugin_paver'); // Turn off events $t.off('mousemove.paver devicetilt.paver'); // Update container dimensions _fun.getContainerDimensions(this); paver.instanceData.containerAspectRatio = paver.instanceData.outerWidth/paver.instanceData.outerHeight; // Fire recompute event and recompute dimensions $t.trigger('recomputeStart.paver'); _fun.compute(this); // Pan to last known position paver.pan({ xPos: Math.min(paver.instanceData.lastPanX,1), yPos: Math.min(paver.instanceData.lastPanY,1) }); // Rebind events _fun.bindEvents(this); }, pan: function(ratio) { var $t = $(this.element), $scroller = $t.find('div.paver__scroller'), $thumb = $scroller.find('span'), grain = parseInt(this.settings.grain), paver = $t.data('plugin_paver'); // If ratio exists and if it is valid if(!ratio) { ratio = { xPos: paver.settings.startPosition, yPos: paver.settings.startPosition } } else { if(ratio.xPos === undefined) ratio.xPos = paver.settings.startPosition; if(ratio.yPos === undefined) ratio.yPos = paver.settings.startPosition; } // Coerce positions if(ratio.xPos > 1) { ratio.xPos = 1; } else if(ratio.xPos < 0) { ratio.xPos = 0; } if(ratio.yPos > 1) { ratio.yPos = 1; } else if(ratio.yPos < 0) { ratio.yPos = 0; } // Set x and y ratios var rX = ratio.xPos.toFixed(grain), rY = ratio.yPos.toFixed(grain); // Keep track of panning count if(!paver.instanceData.panCounter || paver.instanceData.panCounter === 0) { // First pan involves positioning based on settings $t.trigger('initialPanStart.paver'); } else { // Fire custom event on start of pan $t.trigger('panStart.paver'); } // Translate the panorama to match ratio calculated $t .find('div.paver__pano') .css('transform', 'translate('+(-rX * (paver.instanceData.computedWidth - paver.instanceData.outerWidth))+'px, '+(-rY * (paver.instanceData.computedHeight - paver.instanceData.outerHeight))+'px)') .end() .find('div.paver__scroller span') .css('transform', 'translateX('+(rX * ($scroller.width() - $thumb.width()))+'px)') .end(); // Fire custom event on end of pan (end of transition) $w.one(_fun.whichTransitionEnd(), function() { if(!paver.instanceData.panCounter || paver.instanceData.panCounter === 0) { // First pan involves positioning based on settings $t.trigger('initialPanEnd.paver'); } else { // Fire custom event on start of pan $t.trigger('panEnd.paver'); } }); // Update counter and last panned position paver.instanceData.panCounter += 1; paver.instanceData.lastPanX = parseInt(rX); paver.instanceData.lastPanY = parseInt(rY); } }); // Private functions var _fun = { whichTransitionEnd: function() { var el = document.createElement('div'), transition, eventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'transition': 'transitionend' }; for (transition in eventNames) { if (el.style[transition] !== undefined) return eventNames[transition]; } }, //// ------------------ //// //// Let's do some math //// //// ------------------ //// // Adapted from http://stackoverflow.com/questions/5259421/cumulative-distribution-function-in-javascript normalcdf: function(mean, sigma, to) { var z = (to-mean)/Math.sqrt(2*sigma*sigma); var t = 1/(1+0.3275911*Math.abs(z)); var a1 = 0.254829592; var a2 = -0.284496736; var a3 = 1.421413741; var a4 = -1.453152027; var a5 = 1.061405429; var erf = 1-(((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*Math.exp(-z*z); var sign = 1; if(z < 0) sign = -1; return (1/2)*(1+sign*erf); }, // Collection of smoothing functions smoothingFunction: { linear: function(delta, threshold) { if (delta >= threshold) return 1; if (delta <= -threshold) return 0; return 0.5 * (delta/threshold + 1); }, tangent: function(delta, threshold) { if (delta >= threshold) return 1; if (delta <= -threshold) return 0; return 0.5 * (Math.tan((delta/threshold) * (Math.PI/4)) + 1); }, cosine: function(delta, threshold) { if (delta >= threshold) return 1; if (delta <= -threshold) return 0; return 0.5 * (Math.sin((delta/threshold) * (Math.PI/2)) + 1); }, gaussian: function(delta, threshold) { if (delta >= threshold) return 1; if (delta <= -threshold) return 0; return _fun.normalcdf(0, 0.375, delta/threshold); } }, //// --------------- //// //// Paver functions //// //// --------------- //// // Define elements defineElements: function(paver) { paver.t = paver.element; paver.$t = $(paver.element); paver.$p = paver.$t.find('img').first(); paver.instanceData = paver.$t.data('instance-data'); }, domReplacement: function(paver) { // Initialize and append metadata paver.$t .addClass('paver--initialized') .append($('<div />', { 'class': 'paver__meta' })); // If metadata is present, and enabled if(paver.settings.meta && (paver.$p.attr('title') !== undefined || paver.$p.attr('alt') !== undefined) && (paver.$p.attr('title').length || paver.$p.attr('alt').length) ) { paver.$t .addClass('paver--metaActive') .find('.paver__meta') .html('<span class="paver__title">'+paver.$p.attr('title')+'</span><span class="paver__desc">'+paver.$p.attr('alt')+'</span>'); } // Fire initialized event paver.$t.trigger('init.paver'); }, getContainerDimensions: function(paver) { // Set parent container dimensions paver.instanceData.outerWidth = paver.$t.width(); paver.instanceData.outerHeight = paver.$t.height(); paver.instanceData.offsetX = paver.$t.offset().left; paver.instanceData.offsetY = paver.$t.offset().top; }, getCenter: function(paver) { paver.instanceData.centerX = 0.5*paver.instanceData.outerWidth; paver.instanceData.centerY = 0.5*paver.instanceData.outerHeight; }, replacePanorama: function(paver) { var $newP = $('<div />', { 'class': 'paver__pano' }) .css('background-image', 'url('+paver.$p.attr('src')+')'), $scroller = $('<div />', { 'class': 'paver__scroller' }) .append($('<span />')); // DOM manipulation paver.$t .addClass('paver--ready') .append($newP) .append($scroller); // Remove original panorama paver.$p.remove(); // Fire loaded event paver.$t.trigger('ready.paver'); paver.instanceData.ready = true; }, compute: function(paver) { // Get computed dimensions paver.instanceData.computedWidth = paver.instanceData.outerHeight * paver.instanceData.panoAspectRatio; paver.instanceData.computedHeight = paver.instanceData.computedWidth / paver.instanceData.panoAspectRatio; // Get center _fun.getCenter(paver); // Set panorama dimensions paver.$t.find('div.paver__pano').css({ 'width': paver.instanceData.computedWidth, 'height': paver.instanceData.outerHeight }); // Fire custom event paver.$t.trigger('computeEnd.paver'); }, bindEvents: function(paver) { if(paver.check.features.isTouch) { if(paver.check.features.hasGyroscope){ _fun.bindOrientationEvents(paver); } } else { _fun.bindMouseEvents(paver); } // Fire custom event paver.$t.trigger('eventsBound.paver'); }, bindMouseEvents: function(paver) { paver.$t.on('mousemove.paver', $.throttle(paver.settings.panningThrottle, function(e) { // Calculate ratio var smooth = _fun.smoothingFunction[paver.settings.mouseSmoothingFunction]; // Set transform paver.pan({ xPos: smooth((e.pageX - paver.instanceData.offsetX) - paver.instanceData.centerX, paver.instanceData.centerX), yPos: smooth((e.pageY - paver.instanceData.offsetY) - paver.instanceData.centerY, paver.instanceData.centerY) }); })); }, bindOrientationEvents: function(paver) { paver.$t.on('devicetilt.paver', $.throttle(paver.settings.panningThrottle, function(e, alpha, beta, gamma) { // Declare scroller var scrollerTimer; // Declare empty object for tilt change from baseline paver.instanceData.deltaTilt = {}; // Is scroller persistence turned on? if(paver.settings.tiltScrollerPersistence === 0) { // We want scroller to appear all the time paver.$t.addClass('paver-tilting'); } else { // We only want to conditionally enable scroller // Is the tilting beyond a threshold? if( !$.isEmptyObject(paver.instanceData.deltaTilt) && ( Math.abs(paver.instanceData.deltaTilt.alpha - alpha + paver.check.startTilt.alpha) > paver.settings.tiltSensitivity || Math.abs(paver.instanceData.deltaTilt.beta - beta + paver.check.startTilt.beta) > paver.settings.tiltSensitivity || Math.abs(paver.instanceData.deltaTilt.gamma - gamma + paver.check.startTilt.gamma) > paver.settings.tiltSensitivity ) ) { paver.$t.addClass('paver--tilting'); if(!scrollerTimer) { scrollerTimer = window.setTimeout(function() { paver.$t.removeClass('paver--tilting'); }, paver.settings.tiltScrollerPersistence); } } } // Update change in tilt (deltaTilt) paver.instanceData.deltaTilt = { alpha: alpha - paver.check.startTilt.alpha, beta: beta - paver.check.startTilt.beta, gamma: gamma - paver.check.startTilt.gamma }; // Declare screen-adjusted screen tilt, ratio and thresholds var screenTilt = {}, tiltThreshold, smooth = _fun.smoothingFunction[paver.settings.tiltSmoothingFunction]; // Listen to adjusted beta and gamma, as well as the appropriate tilt thresholds // According to screen orientation switch(paver.check.screenOrientationAngle) { case 0: // Portrait-primary screenTilt = { beta: paver.instanceData.deltaTilt.beta, gamma: paver.instanceData.deltaTilt.gamma }; tiltThreshold = paver.settings.tiltThresholdPortrait; break; case 180: case -180: // Portrait-secondary screenTilt = { beta: -paver.instanceData.deltaTilt.beta, gamma: -paver.instanceData.deltaTilt.gamma }; tiltThreshold = paver.settings.tiltThresholdPortrait; break; case 90: case -270: // Landscape-primary screenTilt = { beta: -paver.instanceData.deltaTilt.gamma, gamma: paver.instanceData.deltaTilt.beta }; tiltThreshold = paver.settings.tiltThresholdLandscape; break; case 270: case -90: // Landscape-secondary screenTilt = { beta: paver.instanceData.deltaTilt.gamma, gamma: -paver.instanceData.deltaTilt.beta }; tiltThreshold = paver.settings.tiltThresholdLandscape; break; default: // Portrait-primary screenTilt = { beta: paver.instanceData.deltaTilt.beta, gamma: paver.instanceData.deltaTilt.gamma }; tiltThreshold = paver.settings.tiltThresholdPortrait; break; } paver.pan({ xPos: smooth(screenTilt.gamma, tiltThreshold), yPos: smooth(screenTilt.beta, tiltThreshold) }); })); } }; // A really lightweight plugin wrapper around the constructor, // preventing against multiple instantiations $.fn.paver = function(options) { var t = this, check, args = arguments; // Global data check = { features: { isTouch: false, hasGyroscope: false, hasScreenOrientationAPI: (window.screen && window.screen.orientation && window.screen.orientation.angle !== undefined && window.screen.orientation.angle !== null ? true : false) }, screenOrientationAngle: null, startTilt: {} }; // Private global function var _check = { // Is it a touch-based device? isTouch: function() { try { document.createEvent('TouchEvent'); check.features.isTouch = true; } catch (e) { check.features.isTouch = false; } }, // Does it have a working gyroscope? hasGyroscope: function() { var d = new $.Deferred(), h = function(e) { // Check if we have any useful gyroscopic data if(e.alpha !== null && e.beta !== null && e.gamma !== null) { d.resolve({ orientation: { alpha: e.alpha, beta: e.beta, gamma: e.gamma, }, status: { deviceOrientationEventSupport: true, deviceOrientationData: true } }); } else { d.reject({ status: { deviceOrientationEventSupport: true, deviceOrientationData: false } }); } // Listen to device orientation once and remove listener immediately window.removeEventListener('deviceorientation', h, false); }; // Check of DeviceOrientationEvent is even supported first if (window.DeviceOrientationEvent) { window.addEventListener('deviceorientation', h, false); } else { d.reject({ status: { deviceOrientationEventSupport: false, deviceOrientationData: false } }); } // Return promise return d.promise(); }, // What is the device orientation? // Logic from Full-Tilt: https://github.com/richtr/Full-Tilt/ hasOrientation: function() { check.screenOrientationAngle = (check.features.hasScreenOrientationAPI ? window.screen.orientation.angle : (window.orientation || 0)); } }; // Do checks first _check.isTouch(); _check.hasOrientation(); window.addEventListener('orientationchange', function() { _check.hasOrientation(); _check.hasGyroscope(); }, false); // Wait for gyroscopic data $.when(_check.hasGyroscope()).then(function(gyroData) { // We have gyroscopic data! // Do paver check.features.hasGyroscope = true; // Establish startTilt check.startTilt.alpha = gyroData.orientation.alpha; check.startTilt.beta = gyroData.orientation.beta; check.startTilt.gamma = gyroData.orientation.gamma; // Trigger event $d.trigger('hasGyroscopeData.paver', [gyroData]); // Do paver _doPaver.call(t); }, function(gyroData) { // We do not have gyroscopic data check.features.hasGyroscope = false; // Trigger event $d.trigger('hasNoGyroscopeData.paver', [gyroData]); // Do paver _doPaver.call(t); }); // Paver loop var _doPaver = function() { var $t = $(this); // Listen to starting tilt, only when gyroscopic data is available var deviceOrientationHandler = function(e) { $t.trigger('devicetilt.paver', [e.alpha, e.beta, e.gamma]); }; if(check.features.hasGyroscope) { window.addEventListener('deviceorientation', deviceOrientationHandler, false); } // Check the options parameter // If it is undefined (initialization of plugin) or is an object (plugin configuration), // we create a new instance of the plugin if(options === undefined || typeof options === 'object') { return $t.each(function() { // Only if the plugin_paver data is not present, // to prevent multiple instances being created if(!$.data(this, 'plugin_' + pluginName)) { // Initialize plugin and store $.data(this, 'plugin_' + pluginName, new Plugin(this, options, check)); // Allow individual element access to global check var c = $(this).data('plugin_' + pluginName); c.check = check; } }); // If it is defined, but is a string, does not start with an underscore and is not init(), // we allow users to make calls to public methods } else if(typeof options === 'string' && options[0] !== '_' && options !== 'init') { var publicMethods; $t.each(function() { // Check if plugin instance already exists, and that the 'options' string is a function name var instance = $.data(this, 'plugin_' + pluginName); if(instance instanceof Plugin && typeof instance[options] === 'function') { publicMethods = instance[options].apply(instance, Array.prototype.slice.call(args,1)); } }); return publicMethods !== undefined ? publicMethods : $t; } }; // Return return t; } })( jQuery, window, document );
/************************************************************* * * MathJax/jax/output/HTML-CSS/entities/q.js * * Copyright (c) 2010-2013 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ (function (MATHML) { MathJax.Hub.Insert(MATHML.Parse.Entity,{ 'QUOT': '\u0022', 'qint': '\u2A0C', 'qprime': '\u2057', 'quaternions': '\u210D', 'quatint': '\u2A16', 'quest': '\u003F', 'questeq': '\u225F', 'quot': '\u0022' }); MathJax.Ajax.loadComplete(MATHML.entityDir+"/q.js"); })(MathJax.InputJax.MathML);
'use strict'; angular.module('com.module.core') /** * @ngdoc function * @name com.module.core.controller:LayoutCtrl * @description Layout controller * @requires $scope * @requires $rootScope * @requires CoreService * @requires gettextCatalog **/ .controller('LayoutCtrl', function($scope, $rootScope, $cookies, CoreService, gettextCatalog) { // angular translate $scope.locale = { isopen: false }; $scope.locales = $rootScope.locales; $scope.selectLocale = $rootScope.locale; $scope.setLocale = function(locale) { // set the current lang $scope.locale = $scope.locales[locale]; $scope.selectLocale = $scope.locale; $rootScope.locale = $scope.locale; $cookies.lang = $scope.locale.lang; // You can change the language during runtime $scope.locale.isopen = !$scope.locale.isopen; gettextCatalog.setCurrentLanguage($scope.locale.lang); }; $scope.appName = 'LB-NG-BS'; $scope.apiUrl = CoreService.env.apiUrl; $scope.appTheme = 'skin-blue'; $scope.appThemes = [{ 'name': 'Black', 'class': 'skin-black' }, { 'name': 'Blue', 'class': 'skin-blue' }]; $scope.appLayout = ''; $scope.appLayouts = [{ 'name': 'Fixed', 'class': 'fixed' }, { 'name': 'Scrolling', 'class': 'not-fixed' }]; $scope.toggleSidebar = function() { var $ = angular.element; if ($(window).width() <= 992) { $('.row-offcanvas').toggleClass('active'); $('.left-side').removeClass('collapse-left'); $('.right-side').removeClass('strech'); $('.row-offcanvas').toggleClass('relative'); } else { // Else, enable content streching $('.left-side').toggleClass('collapse-left'); $('.right-side').toggleClass('strech'); } }; $scope.settings = $rootScope.settings; $rootScope.loadSettings(); });
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'indent', 'lv', { indent: 'Palielināt atkāpi', outdent: 'Samazināt atkāpi' } );
!function(e,t){"function"==typeof define&&define.amd?define(["exports"],t):"undefined"!=typeof exports?t(exports):(t(t={}),e.settings=t)}("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:this,function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t={prefix:"bx",selectorTabbable:"\n a[href], area[href], input:not([disabled]):not([tabindex='-1']),\n button:not([disabled]):not([tabindex='-1']),select:not([disabled]):not([tabindex='-1']),\n textarea:not([disabled]):not([tabindex='-1']),\n iframe, object, embed, *[tabindex]:not([tabindex='-1']), *[contenteditable=true]\n ",selectorFocusable:"\n a[href], area[href], input:not([disabled]),\n button:not([disabled]),select:not([disabled]),\n textarea:not([disabled]),\n iframe, object, embed, *[tabindex], *[contenteditable=true]\n "};e.default=t});
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'docprops', 'sr', { bgColor: 'Боја позадине', bgFixed: 'Фиксирана позадина', bgImage: 'УРЛ позадинске слике', charset: 'Кодирање скупа карактера', charsetASCII: 'ASCII', // MISSING charsetCE: 'Central European', // MISSING charsetCR: 'Cyrillic', // MISSING charsetCT: 'Chinese Traditional (Big5)', // MISSING charsetGR: 'Greek', // MISSING charsetJP: 'Japanese', // MISSING charsetKR: 'Korean', // MISSING charsetOther: 'Остала кодирања скупа карактера', charsetTR: 'Turkish', // MISSING charsetUN: 'Unicode (UTF-8)', // MISSING charsetWE: 'Western European', // MISSING chooseColor: 'Choose', design: 'Design', // MISSING docTitle: 'Наслов странице', docType: 'Заглавље типа документа', docTypeOther: 'Остала заглавља типа документа', label: 'Особине документа', margin: 'Маргине странице', marginBottom: 'Доња', marginLeft: 'Лева', marginRight: 'Десна', marginTop: 'Горња', meta: 'Метаподаци', metaAuthor: 'Аутор', metaCopyright: 'Ауторска права', metaDescription: 'Опис документа', metaKeywords: 'Кључне речи за индексирање документа (раздвојене зарезом)', other: '<other>', previewHtml: '<p>This is some <strong>sample text</strong>. You are using <a href="javascript:void(0)">CKEditor</a>.</p>', // MISSING title: 'Особине документа', txtColor: 'Боја текста', xhtmlDec: 'Улључи XHTML декларације' } );
'use strict';var mode=typeof window==='undefined'?'server':'browser';var Vault=(function(){var Local,Session,Server;var conf={vaultFile:'/.vault.json',vaultData:'__vaultData'};var parse=function(value){if(value===null||value===undefined||value==='undefined'){return undefined;} if(value==='null'){return null;} if(value===true||value==='true'){return true;} if(value===false||value==='false'){return false;} if(value!==''&&!isNaN(value)){return parseFloat(value);} if(value.indexOf&&(value.indexOf('{')===0||value.indexOf('[')===0)){return JSON.parse(value);} return value;};var prepare=function(value){if(typeof value==='object'){return JSON.stringify(value);} return value;};var getExpires=function(config){if(config.expires.match(/^(\+|\-)\d+\s\w+/)){var expires=new Date();var operator=config.expires.substring(0,1);var parts=config.expires.substring(1).split(' ');var num=parseInt(parts[0],10);var time=parts[1];switch(time){case'millisecond':case'milliseconds':time='Milliseconds';break;case'second':case'seconds':time='Seconds';break;case'minute':case'minutes':time='Minutes';break;case'hour':case'hours':time='Hours';break;case'day':case'days':time='Date';break;case'month':case'months':time='Month';break;case'year':case'years':time='FullYear';break;} if(operator==='-'){expires['set'+time](expires['get'+time]()-num);}else{expires['set'+time](expires['get'+time]()+num);} return expires;} return new Date(config.expires);};var getData=function(storage){var vaultDataDictionary=storage.getItem(conf.vaultData);if(!vaultDataDictionary){vaultDataDictionary={};} if(typeof vaultDataDictionary==='string'){vaultDataDictionary=JSON.parse(vaultDataDictionary);} return vaultDataDictionary;};var setKeyMeta=function(storage,key,config){if(key===conf.vaultData){return false;} config=config||{};var vaultDataDictionary=getData(storage);if(!vaultDataDictionary[key]){vaultDataDictionary[key]={};} if(config.expires){var expires=getExpires(config);vaultDataDictionary[key].expires=expires&&expires.valueOf();}else{delete vaultDataDictionary[key].expires;} if(config.path){vaultDataDictionary[key].path=config.path;}else{delete vaultDataDictionary[key].path;} storage.setItem(conf.vaultData,prepare(vaultDataDictionary));};var getKeyMeta=function(storage,key){if(key===conf.vaultData){return false;} try{var vaultDataDictionary=getData(storage);return vaultDataDictionary[key];}catch(e){return undefined;}};var clearKeyMeta=function(storage,key){if(key===conf.vaultData){return false;} try{var vaultDataDictionary=getData(storage);delete vaultDataDictionary[key];storage.setItem(conf.vaultData,prepare(vaultDataDictionary));}catch(e){}};var checkKeyMeta=function(storage,key){if(key===conf.vaultData){return false;} try{var obj=parse(storage[key]);var keyMeta=getKeyMeta(storage,key);if(keyMeta){if(mode==='browser'&&keyMeta.path){var storagePath=window.location.pathname||window.location.path;if(!storagePath.match(keyMeta.path)){return true;}} if(!keyMeta.expires&&obj&&obj.expires){keyMeta.expires=obj.expires;} if(keyMeta.expires&&keyMeta.expires<=new Date()){var expired=new Date(keyMeta.expires).toString();console.log('Removing expired item: '+key+'. It expired on: '+expired);clearKeyMeta(storage,key);storage.removeItem(key);return true;}}}catch(e){console.warn('Vault Error:',e);} return false;};var setup=function(type){var storage;try{storage=window[type];try{var test=storage['foo'];}catch(e){storage=undefined;}}catch(e){storage=undefined;} if(!storage){console.warn('Vault: '+type+' is not suppored. I will attempt to use Cookies instead.');return Cookie;} return{type:type,get:function(key,default_value){var obj;if(storage[key]){var meta=checkKeyMeta(storage,key);if(meta){return default_value;} if(obj&&obj.value!==undefined){return parse(obj.value);} return parse(storage[key]);} return default_value;},getAndRemove:function(key){var value=this.get(key);this.remove(key);return value;},getList:function(){var list=[];for(var i in storage){var item={};item[i]=this.get(i);list.push(item);} return list;},set:function(key,value,config){try{if(type==='sessionStorage'&&config&&config.expires){delete config.expires;} setKeyMeta(storage,key,config);return storage.setItem(key,prepare(value));}catch(e){console.warn('Vault: I cannot write to localStoarge even though localStorage is supported. Perhaps you are using your browser in private mode? Here is the error: ',e);}},remove:function(key){clearKeyMeta(storage,key);return storage.removeItem(key);},clear:function(){return storage.clear();},list:function(raw){var i,il=storage.length;if(il===0){console.log('0 items in '+type);return undefined;} for(i in storage){var value=raw?parse(storage[i]):this.get(i);console.log(i,'=',value);}}};};var Cookie={get:function(cookie,default_value){var cookies=document.cookie.split(';');var cl=cookies.length;for(var c=0;c<cl;c++){var pair=cookies[c].split('=');pair[0]=pair[0].replace(/^[ ]/,'');if(pair[0]===cookie){return parse(pair[1]);}} return default_value;},getAndRemove:function(key){var value=this.get(key);this.remove(key);return value;},getList:function(){var list=[];if(document.cookie!==''){var cookies=document.cookie.split(';');var cl=cookies.length;for(var c=0;c<cl;c++){var pair=cookies[c].split('=');pair[0]=pair[0].replace(/^[ ]/,'');var item={};item[pair[0]]=parse(pair[1]);list.push(item);}} return list;},set:function(key,value,config){var expires='';if(config&&config.expires){var exp=getExpires(config);expires='; expires='+exp.toUTCString();} var max_age='';if(config&&config.max_age){max_age='; max-age='+config.max_age;} var domain='';if(config&&config.domain){domain='; domain='+config.domain;} var cookiePath='';if(config&&config.path){cookiePath='; path='+config.path;} var secure=(config&&config.secure)?'; secure':'';value=prepare(value)+cookiePath+domain+max_age+expires+secure;console.log('Vault: set cookie "'+key+'": '+value);document.cookie=key+'='+value;},remove:function(key){document.cookie=key+'=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';},clear:function(){var cookies=document.cookie.split(';');var cl=cookies.length;for(var c=0;c<cl;c++){var pair=cookies[c].split('=');pair[0]=pair[0].replace(/^[ ]/,'');this.remove(pair[0]);}},list:function(){var cookies=document.cookie.split(';');var cl=cookies.length;if(document.cookie===''||cl===0){console.log('0 cookies');return undefined;} for(var c=0;c<cl;c++){var pair=cookies[c].split('=');pair[0]=pair[0].replace(/^[ ]/,'');console.log(pair[0],'=',parse(pair[1]));}}};if(mode==='server'){var fs=require('fs');var path=require('path');var appDir=path.dirname();var _file=appDir+conf.vaultFile;var cache;try{cache=fs.readFileSync(_file);}catch(e){fs.writeFileSync(_file,JSON.stringify({},null,2));} if(cache){try{cache=JSON.parse(cache);}catch(e){}}else{cache={};} Server={type:'Server',save:function(callback){fs.writeFileSync(_file,JSON.stringify(cache,null,2));},get:function(key,default_value){var meta=checkKeyMeta(this,key);if(meta){return default_value;} return cache[key]||default_value;},getItem:function(key,default_value){return this.get(key,default_value);},getAndRemove:function(key){var value=cache[key];delete cache[key];this.save();return value;},getList:function(){var list=[];for(var key in cache){var obj={};obj[key]=cache[key];list.push(obj);} return list;},set:function(key,value,config){cache[key]=value;setKeyMeta(this,key,config);this.save();return cache[key];},setItem:function(key,value,config){return this.set(key,value,config);},remove:function(key){try{delete cache[key];}catch(e){} this.save();},removeItem:function(key){this.remove(key);},clear:function(){cache={};this.save();},list:function(){for(var key in cache){console.log(key,'=',cache[key]);}}};Cookie=Server;Local=Server;Session=Server;}else{Local=setup('localStorage');Session=setup('sessionStorage');} var v={conf:conf,Local:Local,Session:Session,Cookie:Cookie,set:function(key,value,config){if(config&&config.expires){return Local.set(key,value,config);}else{return Session.set(key,value,config);} return Cookie.set(key,value,config);},get:function(key){var sess=Session.get(key);if(sess!==undefined){return sess;}else{var local=Local.get(key);if(local!==undefined){return local;}else{return Cookie.get(key);}}},list:function(raw){if(mode==='server'){console.log('--== Server ==--');return Local.list(raw);} console.log('--== Local ==--');Local.list(raw);console.log('--== Session ==--');Session.list(raw);console.log('--== Cookie ==--');Cookie.list(raw);},getLists:function(){if(mode==='server'){return Local.getList();} return{Local:Local.getList(),Session:Session.getList(),Cookie:Cookie.getList()};},remove:function(key){Local.remove(key);Session.remove(key);Cookie.remove(key);},clear:function(){Local.clear();Session.clear();Cookie.clear();}};return v;}());if(typeof module==='object'&&module.exports){module.exports=Vault;}
/** * Copyright (c) 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. * * @flow */ 'use strict'; const babel = require('babel-core'); const collectDependencies = require('./collect-dependencies'); const constantFolding = require('../../JSTransformer/worker/constant-folding').plugin; const generate = require('./generate'); const inline = require('../../JSTransformer/worker/inline').plugin; const minify = require('../../JSTransformer/worker/minify'); const sourceMap = require('source-map'); import type {TransformedFile, TransformResult} from '../types.flow'; export type OptimizationOptions = {| dev: boolean, isPolyfill?: boolean, platform: string, |}; function optimizeModule( data: string | TransformedFile, optimizationOptions: OptimizationOptions, ): TransformedFile { if (typeof data === 'string') { data = JSON.parse(data); } const {code, file, transformed} = data; const result = {...data, transformed: {}}; //$FlowIssue #14545724 Object.entries(transformed).forEach(([k, t: TransformResult]: [*, TransformResult]) => { result.transformed[k] = optimize(t, file, code, optimizationOptions); }); return result; } function optimize(transformed, file, originalCode, options): TransformResult { const {code, dependencyMapName, map} = transformed; const optimized = optimizeCode(code, map, file, options); let dependencies; if (options.isPolyfill) { dependencies = []; } else { ({dependencies} = collectDependencies.forOptimization( optimized.ast, transformed.dependencies, dependencyMapName, )); } const inputMap = transformed.map; const gen = generate(optimized.ast, file, originalCode); const min = minify( file, gen.code, inputMap && mergeSourceMaps(file, inputMap, gen.map), ); return {code: min.code, map: inputMap && min.map, dependencies}; } function optimizeCode(code, map, filename, inliningOptions) { return babel.transform(code, { plugins: [ [constantFolding], [inline, {...inliningOptions, isWrapped: true}], ], babelrc: false, code: false, filename, }); } function mergeSourceMaps(file, originalMap, secondMap) { const merged = new sourceMap.SourceMapGenerator(); const inputMap = new sourceMap.SourceMapConsumer(originalMap); new sourceMap.SourceMapConsumer(secondMap) .eachMapping(mapping => { const original = inputMap.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn, }); if (original.line == null) { return; } merged.addMapping({ generated: {line: mapping.generatedLine, column: mapping.generatedColumn}, original: {line: original.line, column: original.column || 0}, source: file, name: original.name || mapping.name, }); }); return merged.toJSON(); } module.exports = optimizeModule;
tinyMCE.addI18n('pl.searchreplace_dlg',{findwhat:"Znajd\u017a...",replacewith:"Zamie\u0144 na...",direction:"Kierunek",up:"W g\u00f3r\u0119",down:"W d\u00f3\u0142",mcase:"Uwzgl\u0119dniaj wielko\u015b\u0107 liter",findnext:"Znajd\u017a nast\u0119pny",allreplaced:"Wszystkie wyst\u0105pienia szukanego fragmentu zosta\u0142y zast\u0105pione.","searchnext_desc":"Znajd\u017a ponownie",notfound:"Wyszukiwanie zako\u0144czone. Poszukiwany fragment nie zosta\u0142 znaleziony.","search_title":"Znajd\u017a","replace_title":"Znajd\u017a/zamie\u0144",replaceall:"Zamie\u0144 wszystko",replace:"Zamie\u0144"});
/**! * AngularJS file upload directives and services. Supports: file upload/drop/paste, resume, cancel/abort, * progress, resize, thumbnail, preview, validation and CORS * FileAPI Flash shim for old browsers not supporting FormData * @author Danial <danial.farid@gmail.com> * @version 12.2.0 */ (function () { /** @namespace FileAPI.noContentTimeout */ function patchXHR(fnName, newFn) { window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]); } function redefineProp(xhr, prop, fn) { try { Object.defineProperty(xhr, prop, {get: fn}); } catch (e) {/*ignore*/ } } if (!window.FileAPI) { window.FileAPI = {}; } if (!window.XMLHttpRequest) { throw 'AJAX is not supported. XMLHttpRequest is not defined.'; } FileAPI.shouldLoad = !window.FormData || FileAPI.forceLoad; if (FileAPI.shouldLoad) { var initializeUploadListener = function (xhr) { if (!xhr.__listeners) { if (!xhr.upload) xhr.upload = {}; xhr.__listeners = []; var origAddEventListener = xhr.upload.addEventListener; xhr.upload.addEventListener = function (t, fn) { xhr.__listeners[t] = fn; if (origAddEventListener) origAddEventListener.apply(this, arguments); }; } }; patchXHR('open', function (orig) { return function (m, url, b) { initializeUploadListener(this); this.__url = url; try { orig.apply(this, [m, url, b]); } catch (e) { if (e.message.indexOf('Access is denied') > -1) { this.__origError = e; orig.apply(this, [m, '_fix_for_ie_crossdomain__', b]); } } }; }); patchXHR('getResponseHeader', function (orig) { return function (h) { return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h])); }; }); patchXHR('getAllResponseHeaders', function (orig) { return function () { return this.__fileApiXHR && this.__fileApiXHR.getAllResponseHeaders ? this.__fileApiXHR.getAllResponseHeaders() : (orig == null ? null : orig.apply(this)); }; }); patchXHR('abort', function (orig) { return function () { return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this)); }; }); patchXHR('setRequestHeader', function (orig) { return function (header, value) { if (header === '__setXHR_') { initializeUploadListener(this); var val = value(this); // fix for angular < 1.2.0 if (val instanceof Function) { val(this); } } else { this.__requestHeaders = this.__requestHeaders || {}; this.__requestHeaders[header] = value; orig.apply(this, arguments); } }; }); patchXHR('send', function (orig) { return function () { var xhr = this; if (arguments[0] && arguments[0].__isFileAPIShim) { var formData = arguments[0]; var config = { url: xhr.__url, jsonp: false, //removes the callback form param cache: true, //removes the ?fileapiXXX in the url complete: function (err, fileApiXHR) { if (err && angular.isString(err) && err.indexOf('#2174') !== -1) { // this error seems to be fine the file is being uploaded properly. err = null; } xhr.__completed = true; if (!err && xhr.__listeners.load) xhr.__listeners.load({ type: 'load', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true }); if (!err && xhr.__listeners.loadend) xhr.__listeners.loadend({ type: 'loadend', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true }); if (err === 'abort' && xhr.__listeners.abort) xhr.__listeners.abort({ type: 'abort', loaded: xhr.__loaded, total: xhr.__total, target: xhr, lengthComputable: true }); if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function () { return (fileApiXHR.status === 0 && err && err !== 'abort') ? 500 : fileApiXHR.status; }); if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function () { return fileApiXHR.statusText; }); redefineProp(xhr, 'readyState', function () { return 4; }); if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function () { return fileApiXHR.response; }); var resp = fileApiXHR.responseText || (err && fileApiXHR.status === 0 && err !== 'abort' ? err : undefined); redefineProp(xhr, 'responseText', function () { return resp; }); redefineProp(xhr, 'response', function () { return resp; }); if (err) redefineProp(xhr, 'err', function () { return err; }); xhr.__fileApiXHR = fileApiXHR; if (xhr.onreadystatechange) xhr.onreadystatechange(); if (xhr.onload) xhr.onload(); }, progress: function (e) { e.target = xhr; if (xhr.__listeners.progress) xhr.__listeners.progress(e); xhr.__total = e.total; xhr.__loaded = e.loaded; if (e.total === e.loaded) { // fix flash issue that doesn't call complete if there is no response text from the server var _this = this; setTimeout(function () { if (!xhr.__completed) { xhr.getAllResponseHeaders = function () { }; _this.complete(null, {status: 204, statusText: 'No Content'}); } }, FileAPI.noContentTimeout || 10000); } }, headers: xhr.__requestHeaders }; config.data = {}; config.files = {}; for (var i = 0; i < formData.data.length; i++) { var item = formData.data[i]; if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) { config.files[item.key] = item.val; } else { config.data[item.key] = item.val; } } setTimeout(function () { if (!FileAPI.hasFlash) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } xhr.__fileApiXHR = FileAPI.upload(config); }, 1); } else { if (this.__origError) { throw this.__origError; } orig.apply(xhr, arguments); } }; }); window.XMLHttpRequest.__isFileAPIShim = true; window.FormData = FormData = function () { return { append: function (key, val, name) { if (val.__isFileAPIBlobShim) { val = val.data[0]; } this.data.push({ key: key, val: val, name: name }); }, data: [], __isFileAPIShim: true }; }; window.Blob = Blob = function (b) { return { data: b, __isFileAPIBlobShim: true }; }; } })(); (function () { /** @namespace FileAPI.forceLoad */ /** @namespace window.FileAPI.jsUrl */ /** @namespace window.FileAPI.jsPath */ function isInputTypeFile(elem) { return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file'; } function hasFlash() { try { var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); if (fo) return true; } catch (e) { if (navigator.mimeTypes['application/x-shockwave-flash'] !== undefined) return true; } return false; } function getOffset(obj) { var left = 0, top = 0; if (window.jQuery) { return jQuery(obj).offset(); } if (obj.offsetParent) { do { left += (obj.offsetLeft - obj.scrollLeft); top += (obj.offsetTop - obj.scrollTop); obj = obj.offsetParent; } while (obj); } return { left: left, top: top }; } if (FileAPI.shouldLoad) { FileAPI.hasFlash = hasFlash(); //load FileAPI if (FileAPI.forceLoad) { FileAPI.html5 = false; } if (!FileAPI.upload) { var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src; if (window.FileAPI.jsUrl) { jsUrl = window.FileAPI.jsUrl; } else if (window.FileAPI.jsPath) { basePath = window.FileAPI.jsPath; } else { for (i = 0; i < allScripts.length; i++) { src = allScripts[i].src; index = src.search(/\/ng\-file\-upload[\-a-zA-z0-9\.]*\.js/); if (index > -1) { basePath = src.substring(0, index + 1); break; } } } if (FileAPI.staticPath == null) FileAPI.staticPath = basePath; script.setAttribute('src', jsUrl || basePath + 'FileAPI.min.js'); document.getElementsByTagName('head')[0].appendChild(script); } FileAPI.ngfFixIE = function (elem, fileElem, changeFn) { if (!hasFlash()) { throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"'; } var fixInputStyle = function () { var label = fileElem.parent(); if (elem.attr('disabled')) { if (label) label.removeClass('js-fileapi-wrapper'); } else { if (!fileElem.attr('__ngf_flash_')) { fileElem.unbind('change'); fileElem.unbind('click'); fileElem.bind('change', function (evt) { fileApiChangeFn.apply(this, [evt]); changeFn.apply(this, [evt]); }); fileElem.attr('__ngf_flash_', 'true'); } label.addClass('js-fileapi-wrapper'); if (!isInputTypeFile(elem)) { label.css('position', 'absolute') .css('top', getOffset(elem[0]).top + 'px').css('left', getOffset(elem[0]).left + 'px') .css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px') .css('filter', 'alpha(opacity=0)').css('display', elem.css('display')) .css('overflow', 'hidden').css('z-index', '900000') .css('visibility', 'visible'); fileElem.css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px') .css('position', 'absolute').css('top', '0px').css('left', '0px'); } } }; elem.bind('mouseenter', fixInputStyle); var fileApiChangeFn = function (evt) { var files = FileAPI.getFiles(evt); //just a double check for #233 for (var i = 0; i < files.length; i++) { if (files[i].size === undefined) files[i].size = 0; if (files[i].name === undefined) files[i].name = 'file'; if (files[i].type === undefined) files[i].type = 'undefined'; } if (!evt.target) { evt.target = {}; } evt.target.files = files; // if evt.target.files is not writable use helper field if (evt.target.files !== files) { evt.__files_ = files; } (evt.__files_ || evt.target.files).item = function (i) { return (evt.__files_ || evt.target.files)[i] || null; }; }; }; FileAPI.disableFileInput = function (elem, disable) { if (disable) { elem.removeClass('js-fileapi-wrapper'); } else { elem.addClass('js-fileapi-wrapper'); } }; } })(); if (!window.FileReader) { window.FileReader = function () { var _this = this, loadStarted = false; this.listeners = {}; this.addEventListener = function (type, fn) { _this.listeners[type] = _this.listeners[type] || []; _this.listeners[type].push(fn); }; this.removeEventListener = function (type, fn) { if (_this.listeners[type]) _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1); }; this.dispatchEvent = function (evt) { var list = _this.listeners[evt.type]; if (list) { for (var i = 0; i < list.length; i++) { list[i].call(_this, evt); } } }; this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null; var constructEvent = function (type, evt) { var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error}; if (evt.result != null) e.target.result = evt.result; return e; }; var listener = function (evt) { if (!loadStarted) { loadStarted = true; if (_this.onloadstart) _this.onloadstart(constructEvent('loadstart', evt)); } var e; if (evt.type === 'load') { if (_this.onloadend) _this.onloadend(constructEvent('loadend', evt)); e = constructEvent('load', evt); if (_this.onload) _this.onload(e); _this.dispatchEvent(e); } else if (evt.type === 'progress') { e = constructEvent('progress', evt); if (_this.onprogress) _this.onprogress(e); _this.dispatchEvent(e); } else { e = constructEvent('error', evt); if (_this.onerror) _this.onerror(e); _this.dispatchEvent(e); } }; this.readAsDataURL = function (file) { FileAPI.readAsDataURL(file, listener); }; this.readAsText = function (file) { FileAPI.readAsText(file, listener); }; }; }
!function($, wysi) { "use strict"; var tpl = { "font-styles": function(locale, options) { var size = (options && options.size) ? ' btn-'+options.size : ''; return "<li class='dropdown'>" + "<a class='btn btn-default dropdown-toggle" + size + "' data-toggle='dropdown' href='#'>" + "<i class='fa fa-font'></i>&nbsp;<span class='current-font'>" + locale.font_styles.normal + "</span>&nbsp;<b class='caret'></b>" + "</a>" + "<ul class='dropdown-menu'>" + "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='div' tabindex='-1'>" + locale.font_styles.normal + "</a></li>" + "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h1' tabindex='-1'>" + locale.font_styles.h1 + "</a></li>" + "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h2' tabindex='-1'>" + locale.font_styles.h2 + "</a></li>" + "<li><a data-wysihtml5-command='formatBlock' data-wysihtml5-command-value='h3' tabindex='-1'>" + locale.font_styles.h3 + "</a></li>" + "</ul>" + "</li>"; }, "emphasis": function(locale, options) { var size = (options && options.size) ? ' btn-'+options.size : ''; return "<li>" + "<div class='btn-group'>" + "<a class='btn btn-default" + size + "' data-wysihtml5-command='bold' title='CTRL+B' tabindex='-1'>" + locale.emphasis.bold + "</a>" + "<a class='btn btn-default" + size + "' data-wysihtml5-command='italic' title='CTRL+I' tabindex='-1'>" + locale.emphasis.italic + "</a>" + "<a class='btn btn-default" + size + "' data-wysihtml5-command='underline' title='CTRL+U' tabindex='-1'>" + locale.emphasis.underline + "</a>" + "</div>" + "</li>"; }, "lists": function(locale, options) { var size = (options && options.size) ? ' btn-'+options.size : ''; return "<li>" + "<div class='btn-group'>" + "<a class='btn btn-default" + size + "' data-wysihtml5-command='insertUnorderedList' title='" + locale.lists.unordered + "' tabindex='-1'><i class='fa fa-list'></i></a>" + "<a class='btn btn-default" + size + "' data-wysihtml5-command='insertOrderedList' title='" + locale.lists.ordered + "' tabindex='-1'><i class='fa fa-th-list'></i></a>" + "<a class='btn btn-default" + size + "' data-wysihtml5-command='Outdent' title='" + locale.lists.outdent + "' tabindex='-1'><i class='fa fa-indent'></i></a>" + "<a class='btn btn-default" + size + "' data-wysihtml5-command='Indent' title='" + locale.lists.indent + "' tabindex='-1'><i class='fa fa-outdent'></i></a>" + "</div>" + "</li>"; }, "link": function(locale, options) { var size = (options && options.size) ? ' btn-'+options.size : ''; return "<li>" + "<div class='bootstrap-wysihtml5-insert-link-modal modal fade'>" + "<div class='modal-dialog'>"+ "<div class='modal-content'>"+ "<div class='modal-header'>" + "<a class='close' data-dismiss='modal'>&times;</a>" + "<h3 class='modal-title'>" + locale.link.insert + "</h3>" + "</div>" + "<div class='modal-body'>" + "<input value='http://' class='bootstrap-wysihtml5-insert-link-url input-xlarge'>" + "</div>" + "<div class='modal-footer'>" + "<a href='#' class='btn btn-default' data-dismiss='modal'>" + locale.link.cancel + "</a>" + "<a href='#' class='btn btn-primary' data-dismiss='modal'>" + locale.link.insert + "</a>" + "</div>" + "</div>" + "</div>"+ "</div>"+ "<a class='btn btn-default" + size + "' data-wysihtml5-command='createLink' title='" + locale.link.insert + "' tabindex='-1'><i class='fa fa-share'></i></a>" + "</li>"; }, "image": function(locale, options) { var size = (options && options.size) ? ' btn-'+options.size : ''; return "<li>" + "<div class='bootstrap-wysihtml5-insert-image-modal modal fade'>" + "<div class='modal-dialog'>"+ "<div class='modal-content'>"+ "<div class='modal-header'>" + "<a class='close' data-dismiss='modal'>&times;</a>" + "<h3 class='modal-title'>" + locale.image.insert + "</h3>" + "</div>" + "<div class='modal-body'>" + "<input value='http://' class='bootstrap-wysihtml5-insert-image-url input-xlarge'>" + "</div>" + "<div class='modal-footer'>" + "<a href='#' class='btn btn-default' data-dismiss='modal'>" + locale.image.cancel + "</a>" + "<a href='#' class='btn btn-primary' data-dismiss='modal'>" + locale.image.insert + "</a>" + "</div>" + "</div>" + "</div>"+ "</div>"+ "<a class='btn btn-default" + size + "' data-wysihtml5-command='insertImage' title='" + locale.image.insert + "' tabindex='-1'><i class='fa fa-picture-o'></i></a>" + "</li>"; }, "html": function(locale, options) { var size = (options && options.size) ? ' btn-'+options.size : ''; return "<li>" + "<div class='btn-group'>" + "<a class='btn btn-default" + size + "' data-wysihtml5-action='change_view' title='" + locale.html.edit + "' tabindex='-1'><i class='fa fa-pencil'></i></a>" + "</div>" + "</li>"; }, "color": function(locale, options) { var size = (options && options.size) ? ' btn-'+options.size : ''; return "<li class='dropdown'>" + "<a class='btn btn-default dropdown-toggle" + size + "' data-toggle='dropdown' href='#' tabindex='-1'>" + "<span class='current-color'>" + locale.colours.black + "</span>&nbsp;<b class='caret'></b>" + "</a>" + "<ul class='dropdown-menu'>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='black'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='black'>" + locale.colours.black + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='silver'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='silver'>" + locale.colours.silver + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='gray'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='gray'>" + locale.colours.gray + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='maroon'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='maroon'>" + locale.colours.maroon + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='red'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='red'>" + locale.colours.red + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='purple'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='purple'>" + locale.colours.purple + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='green'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='green'>" + locale.colours.green + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='olive'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='olive'>" + locale.colours.olive + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='navy'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='navy'>" + locale.colours.navy + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='blue'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='blue'>" + locale.colours.blue + "</a></li>" + "<li><div class='wysihtml5-colors' data-wysihtml5-command-value='orange'></div><a class='wysihtml5-colors-title' data-wysihtml5-command='foreColor' data-wysihtml5-command-value='orange'>" + locale.colours.orange + "</a></li>" + "</ul>" + "</li>"; } }; var templates = function(key, locale, options) { return tpl[key](locale, options); }; var Wysihtml5 = function(el, options) { this.el = el; var toolbarOpts = options || defaultOptions; for(var t in toolbarOpts.customTemplates) { tpl[t] = toolbarOpts.customTemplates[t]; } this.toolbar = this.createToolbar(el, toolbarOpts); this.editor = this.createEditor(options); window.editor = this.editor; $('iframe.wysihtml5-sandbox').each(function(i, el){ $(el.contentWindow).off('focus.wysihtml5').on({ 'focus.wysihtml5' : function(){ $('li.dropdown').removeClass('open'); } }); }); }; Wysihtml5.prototype = { constructor: Wysihtml5, createEditor: function(options) { options = options || {}; // Add the toolbar to a clone of the options object so multiple instances // of the WYISYWG don't break because "toolbar" is already defined options = $.extend(true, {}, options); options.toolbar = this.toolbar[0]; var editor = new wysi.Editor(this.el[0], options); if(options && options.events) { for(var eventName in options.events) { editor.on(eventName, options.events[eventName]); } } return editor; }, createToolbar: function(el, options) { var self = this; var toolbar = $("<ul/>", { 'class' : "wysihtml5-toolbar", 'style': "display:none" }); var culture = options.locale || defaultOptions.locale || "en"; for(var key in defaultOptions) { var value = false; if(options[key] !== undefined) { if(options[key] === true) { value = true; } } else { value = defaultOptions[key]; } if(value === true) { toolbar.append(templates(key, locale[culture], options)); if(key === "html") { this.initHtml(toolbar); } if(key === "link") { this.initInsertLink(toolbar); } if(key === "image") { this.initInsertImage(toolbar); } } } if(options.toolbar) { for(key in options.toolbar) { toolbar.append(options.toolbar[key]); } } toolbar.find("a[data-wysihtml5-command='formatBlock']").click(function(e) { var target = e.target || e.srcElement; var el = $(target); self.toolbar.find('.current-font').text(el.html()); }); toolbar.find("a[data-wysihtml5-command='foreColor']").click(function(e) { var target = e.target || e.srcElement; var el = $(target); self.toolbar.find('.current-color').text(el.html()); }); this.el.before(toolbar); return toolbar; }, initHtml: function(toolbar) { var changeViewSelector = "a[data-wysihtml5-action='change_view']"; toolbar.find(changeViewSelector).click(function(e) { toolbar.find('a.btn btn-default').not(changeViewSelector).toggleClass('disabled'); }); }, initInsertImage: function(toolbar) { var self = this; var insertImageModal = toolbar.find('.bootstrap-wysihtml5-insert-image-modal'); var urlInput = insertImageModal.find('.bootstrap-wysihtml5-insert-image-url'); var insertButton = insertImageModal.find('a.btn-primary'); var initialValue = urlInput.val(); var caretBookmark; var insertImage = function() { var url = urlInput.val(); urlInput.val(initialValue); self.editor.currentView.element.focus(); if (caretBookmark) { self.editor.composer.selection.setBookmark(caretBookmark); caretBookmark = null; } self.editor.composer.commands.exec("insertImage", url); }; urlInput.keypress(function(e) { if(e.which == 13) { insertImage(); insertImageModal.modal('hide'); } }); insertButton.click(insertImage); insertImageModal.on('shown', function() { urlInput.focus(); }); insertImageModal.on('hide', function() { self.editor.currentView.element.focus(); }); toolbar.find('a[data-wysihtml5-command=insertImage]').click(function() { var activeButton = $(this).hasClass("wysihtml5-command-active"); if (!activeButton) { self.editor.currentView.element.focus(false); caretBookmark = self.editor.composer.selection.getBookmark(); insertImageModal.appendTo('body').modal('show'); insertImageModal.on('click.dismiss.modal', '[data-dismiss="modal"]', function(e) { e.stopPropagation(); }); return false; } else { return true; } }); }, initInsertLink: function(toolbar) { var self = this; var insertLinkModal = toolbar.find('.bootstrap-wysihtml5-insert-link-modal'); var urlInput = insertLinkModal.find('.bootstrap-wysihtml5-insert-link-url'); var insertButton = insertLinkModal.find('a.btn-primary'); var initialValue = urlInput.val(); var caretBookmark; var insertLink = function() { var url = urlInput.val(); urlInput.val(initialValue); self.editor.currentView.element.focus(); if (caretBookmark) { self.editor.composer.selection.setBookmark(caretBookmark); caretBookmark = null; } self.editor.composer.commands.exec("createLink", { href: url, target: "_blank", rel: "nofollow" }); }; var pressedEnter = false; urlInput.keypress(function(e) { if(e.which == 13) { insertLink(); insertLinkModal.modal('hide'); } }); insertButton.click(insertLink); insertLinkModal.on('shown', function() { urlInput.focus(); }); insertLinkModal.on('hide', function() { self.editor.currentView.element.focus(); }); toolbar.find('a[data-wysihtml5-command=createLink]').click(function() { var activeButton = $(this).hasClass("wysihtml5-command-active"); if (!activeButton) { self.editor.currentView.element.focus(false); caretBookmark = self.editor.composer.selection.getBookmark(); insertLinkModal.appendTo('body').modal('show'); insertLinkModal.on('click.dismiss.modal', '[data-dismiss="modal"]', function(e) { e.stopPropagation(); }); return false; } else { return true; } }); } }; // these define our public api var methods = { resetDefaults: function() { $.fn.wysihtml5.defaultOptions = $.extend(true, {}, $.fn.wysihtml5.defaultOptionsCache); }, bypassDefaults: function(options) { return this.each(function () { var $this = $(this); $this.data('wysihtml5', new Wysihtml5($this, options)); }); }, shallowExtend: function (options) { var settings = $.extend({}, $.fn.wysihtml5.defaultOptions, options || {}); var that = this; return methods.bypassDefaults.apply(that, [settings]); }, deepExtend: function(options) { var settings = $.extend(true, {}, $.fn.wysihtml5.defaultOptions, options || {}); var that = this; return methods.bypassDefaults.apply(that, [settings]); }, init: function(options) { var that = this; return methods.shallowExtend.apply(that, [options]); } }; $.fn.wysihtml5 = function ( method ) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.wysihtml5' ); } }; $.fn.wysihtml5.Constructor = Wysihtml5; var defaultOptions = $.fn.wysihtml5.defaultOptions = { "font-styles": true, "color": false, "emphasis": true, "lists": true, "html": false, "link": true, "image": true, events: {}, parserRules: { classes: { // (path_to_project/lib/css/wysiwyg-color.css) "wysiwyg-color-silver" : 1, "wysiwyg-color-gray" : 1, "wysiwyg-color-white" : 1, "wysiwyg-color-maroon" : 1, "wysiwyg-color-red" : 1, "wysiwyg-color-purple" : 1, "wysiwyg-color-fuchsia" : 1, "wysiwyg-color-green" : 1, "wysiwyg-color-lime" : 1, "wysiwyg-color-olive" : 1, "wysiwyg-color-yellow" : 1, "wysiwyg-color-navy" : 1, "wysiwyg-color-blue" : 1, "wysiwyg-color-teal" : 1, "wysiwyg-color-aqua" : 1, "wysiwyg-color-orange" : 1 }, tags: { "b": {}, "i": {}, "br": {}, "ol": {}, "ul": {}, "li": {}, "h1": {}, "h2": {}, "h3": {}, "blockquote": {}, "u": 1, "img": { "check_attributes": { "width": "numbers", "alt": "alt", "src": "url", "height": "numbers" } }, "a": { set_attributes: { target: "_blank", rel: "nofollow" }, check_attributes: { href: "url" // important to avoid XSS } }, "span": 1, "div": 1, // to allow save and edit files with code tag hacks "code": 1, "pre": 1 } }, stylesheets: ["./lib/css/wysiwyg-color.css"], // (path_to_project/lib/css/wysiwyg-color.css) locale: "en" }; if (typeof $.fn.wysihtml5.defaultOptionsCache === 'undefined') { $.fn.wysihtml5.defaultOptionsCache = $.extend(true, {}, $.fn.wysihtml5.defaultOptions); } var locale = $.fn.wysihtml5.locale = { en: { font_styles: { normal: "Normal text", h1: "Heading 1", h2: "Heading 2", h3: "Heading 3" }, emphasis: { bold: "Bold", italic: "Italic", underline: "Underline" }, lists: { unordered: "Unordered list", ordered: "Ordered list", outdent: "Outdent", indent: "Indent" }, link: { insert: "Insert link", cancel: "Cancel" }, image: { insert: "Insert image", cancel: "Cancel" }, html: { edit: "Edit HTML" }, colours: { black: "Black", silver: "Silver", gray: "Grey", maroon: "Maroon", red: "Red", purple: "Purple", green: "Green", olive: "Olive", navy: "Navy", blue: "Blue", orange: "Orange" } } }; }(window.jQuery, window.wysihtml5);
/* System bundles Allows a bundle module to be specified which will be dynamically loaded before trying to load a given module. For example: SystemJS.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap'] Will result in a load to "mybundle" whenever a load to "jquery" or "bootstrap/js/bootstrap" is made. In this way, the bundle becomes the request that provides the module */ (function() { // bundles support (just like RequireJS) // bundle name is module name of bundle itself // bundle is array of modules defined by the bundle // when a module in the bundle is requested, the bundle is loaded instead // of the form SystemJS.bundles['mybundle'] = ['jquery', 'bootstrap/js/bootstrap'] hookConstructor(function(constructor) { return function() { constructor.call(this); this.bundles = {}; this._loader.loadedBundles = {}; }; }); // assign bundle metadata for bundle loads hook('locate', function(locate) { return function(load) { var loader = this; var matched = false; if (!(load.name in loader.defined)) for (var b in loader.bundles) { for (var i = 0; i < loader.bundles[b].length; i++) { var curModule = loader.bundles[b][i]; if (curModule == load.name) { matched = true; break; } // wildcard in bundles does not include / boundaries if (curModule.indexOf('*') != -1) { var parts = curModule.split('*'); if (parts.length != 2) { loader.bundles[b].splice(i--, 1); continue; } if (load.name.substring(0, parts[0].length) == parts[0] && load.name.substr(load.name.length - parts[1].length, parts[1].length) == parts[1] && load.name.substr(parts[0].length, load.name.length - parts[1].length - parts[0].length).indexOf('/') == -1) { matched = true; break; } } } if (matched) return loader['import'](b) .then(function() { return locate.call(loader, load); }); } return locate.call(loader, load); }; }); })();
/** * Copyright (c) 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 SnapshotViewIOS * @flow */ 'use strict'; var React = require('React'); const PropTypes = require('prop-types'); var StyleSheet = require('StyleSheet'); var { TestModule } = require('NativeModules'); var UIManager = require('UIManager'); var View = require('View'); const ViewPropTypes = require('ViewPropTypes'); var requireNativeComponent = require('requireNativeComponent'); class SnapshotViewIOS extends React.Component { props: { onSnapshotReady?: Function, testIdentifier?: string, }; // $FlowFixMe(>=0.41.0) static propTypes = { ...ViewPropTypes, // A callback when the Snapshot view is ready to be compared onSnapshotReady : PropTypes.func, // A name to identify the individual instance to the SnapshotView testIdentifier : PropTypes.string, }; onDefaultAction = (event: Object) => { TestModule.verifySnapshot(TestModule.markTestPassed); }; render() { var testIdentifier = this.props.testIdentifier || 'test'; var onSnapshotReady = this.props.onSnapshotReady || this.onDefaultAction; return ( <RCTSnapshot style={style.snapshot} {...this.props} onSnapshotReady={onSnapshotReady} testIdentifier={testIdentifier} /> ); } } var style = StyleSheet.create({ snapshot: { flex: 1, }, }); // Verify that RCTSnapshot is part of the UIManager since it is only loaded // if you have linked against RCTTest like in tests, otherwise we will have // a warning printed out var RCTSnapshot = UIManager.RCTSnapshot ? requireNativeComponent('RCTSnapshot', SnapshotViewIOS) : View; module.exports = SnapshotViewIOS;