34255 lines · 1.2 MB · JavaScript
RawDownload
     // 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();      } else {        if (!sameBase) {          pendingLocation = url;        }        if (replace) {          location.replace(url);        } else if (!sameBase) {          location.href = url;        } else {          location.hash = getHash(url);        }        if (location.href !== url) {          pendingLocation = url;        }      }      if (pendingLocation) {        pendingLocation = url;      }      return self;    // getter    } else {      // - pendingLocation is needed as browsers don't allow to read out      //   the new location.href if a reload happened or if there is a bug like in iOS 9 (see      //   https://openradar.appspot.com/22186109).      // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172      return pendingLocation || 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() {    pendingLocation = null;    fireStateOrUrlChange();  }   // 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 = getCurrentState();    cachedState = isUndefined(cachedState) ? null : cachedState;     // Prevent callbacks fo fire twice if both hashchange & popstate were fired.    if (equals(cachedState, lastCachedState)) {      cachedState = lastCachedState;    }     lastCachedState = cachedState;    lastHistoryState = cachedState;  }   function fireStateOrUrlChange() {    var prevLastHistoryState = lastHistoryState;    cacheState();     if (lastBrowserUrl === self.url() && prevLastHistoryState === 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 don't      // fire popstate when user changes 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;  };   /**   * @private   * Remove popstate and hashchange handler from window.   *   * NOTE: this api is intended for use only by $rootScope.   */  self.$$applicationDestroyed = function() {    jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);  };   /**   * 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 = fireStateOrUrlChange;   //////////////////////////////////////////////////////////////  // 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?:)?\/\/[^/]*/, '') : '';  };   /**   * @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;  }; } /** @this */function $BrowserProvider() {  this.$get = ['$window', '$log', '$sniffer', '$document',      function($window, $log, $sniffer, $document) {        return new Browser($window, $document, $log, $sniffer);      }];} /** * @ngdoc service * @name $cacheFactory * @this * * @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" name="cache-factory">     <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 (angular.isUndefined($scope.cache.get(key))) {               $scope.keys.push(key);             }             $scope.cache.put(key, angular.isUndefined(value) ? 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 = createMap(),          capacity = (options && options.capacity) || Number.MAX_VALUE,          lruHash = createMap(),          freshEnd = null,          staleEnd = null;       /**       * @ngdoc type       * @name $cacheFactory.Cache       *       * @description       * A cache object used to store and retrieve data, primarily used by       * {@link $templateRequest $templateRequest} 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 (isUndefined(value)) return;          if (capacity < Number.MAX_VALUE) {            var lruEntry = lruHash[key] || (lruHash[key] = {key: key});             refresh(lruEntry);          }           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];          }           if (!(key in data)) return;           delete data[key];          size--;        },          /**         * @ngdoc method         * @name $cacheFactory.Cache#removeAll         * @kind function         *         * @description         * Clears the cache object of any entries.         */        removeAll: function() {          data = createMap();          size = 0;          lruHash = createMap();          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

Lines 6501–7000 of 34255. Previous lines

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t