UNPKG

cordova-plugin-progressindicator

Version:
1,419 lines (1,287 loc) 116 kB
/** * State-based routing for AngularJS * @version v0.2.10 * @link http://angular-ui.github.com/ * @license MIT License, http://www.opensource.org/licenses/MIT */ /* commonjs package manager support (eg componentjs) */ if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){ module.exports = 'ui.router'; } (function (window, angular, undefined) { /*jshint globalstrict:true*/ /*global angular:false*/ 'use strict'; var isDefined = angular.isDefined, isFunction = angular.isFunction, isString = angular.isString, isObject = angular.isObject, isArray = angular.isArray, forEach = angular.forEach, extend = angular.extend, copy = angular.copy; function inherit(parent, extra) { return extend(new (extend(function() {}, { prototype: parent }))(), extra); } function merge(dst) { forEach(arguments, function(obj) { if (obj !== dst) { forEach(obj, function(value, key) { if (!dst.hasOwnProperty(key)) dst[key] = value; }); } }); return dst; } /** * Finds the common ancestor path between two states. * * @param {Object} first The first state. * @param {Object} second The second state. * @return {Array} Returns an array of state names in descending order, not including the root. */ function ancestors(first, second) { var path = []; for (var n in first.path) { if (first.path[n] !== second.path[n]) break; path.push(first.path[n]); } return path; } /** * IE8-safe wrapper for `Object.keys()`. * * @param {Object} object A JavaScript object. * @return {Array} Returns the keys of the object as an array. */ function keys(object) { if (Object.keys) { return Object.keys(object); } var result = []; angular.forEach(object, function(val, key) { result.push(key); }); return result; } /** * IE8-safe wrapper for `Array.prototype.indexOf()`. * * @param {Array} array A JavaScript array. * @param {*} value A value to search the array for. * @return {Number} Returns the array index value of `value`, or `-1` if not present. */ function arraySearch(array, value) { if (Array.prototype.indexOf) { return array.indexOf(value, Number(arguments[2]) || 0); } var len = array.length >>> 0, from = Number(arguments[2]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in array && array[from] === value) return from; } return -1; } /** * Merges a set of parameters with all parameters inherited between the common parents of the * current state and a given destination state. * * @param {Object} currentParams The value of the current state parameters ($stateParams). * @param {Object} newParams The set of parameters which will be composited with inherited params. * @param {Object} $current Internal definition of object representing the current state. * @param {Object} $to Internal definition of object representing state to transition to. */ function inheritParams(currentParams, newParams, $current, $to) { var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = []; for (var i in parents) { if (!parents[i].params || !parents[i].params.length) continue; parentParams = parents[i].params; for (var j in parentParams) { if (arraySearch(inheritList, parentParams[j]) >= 0) continue; inheritList.push(parentParams[j]); inherited[parentParams[j]] = currentParams[parentParams[j]]; } } return extend({}, inherited, newParams); } /** * Normalizes a set of values to string or `null`, filtering them by a list of keys. * * @param {Array} keys The list of keys to normalize/return. * @param {Object} values An object hash of values to normalize. * @return {Object} Returns an object hash of normalized string values. */ function normalize(keys, values) { var normalized = {}; forEach(keys, function (name) { var value = values[name]; normalized[name] = (value != null) ? String(value) : null; }); return normalized; } /** * Performs a non-strict comparison of the subset of two objects, defined by a list of keys. * * @param {Object} a The first object. * @param {Object} b The second object. * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified, * it defaults to the list of keys in `a`. * @return {Boolean} Returns `true` if the keys match, otherwise `false`. */ function equalForKeys(a, b, keys) { if (!keys) { keys = []; for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility } for (var i=0; i<keys.length; i++) { var k = keys[i]; if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized } return true; } /** * Returns the subset of an object, based on a list of keys. * * @param {Array} keys * @param {Object} values * @return {Boolean} Returns a subset of `values`. */ function filterByKeys(keys, values) { var filtered = {}; forEach(keys, function (name) { filtered[name] = values[name]; }); return filtered; } /** * @ngdoc overview * @name ui.router.util * * @description * # ui.router.util sub-module * * This module is a dependency of other sub-modules. Do not include this module as a dependency * in your angular app (use {@link ui.router} module instead). * */ angular.module('ui.router.util', ['ng']); /** * @ngdoc overview * @name ui.router.router * * @requires ui.router.util * * @description * # ui.router.router sub-module * * This module is a dependency of other sub-modules. Do not include this module as a dependency * in your angular app (use {@link ui.router} module instead). */ angular.module('ui.router.router', ['ui.router.util']); /** * @ngdoc overview * @name ui.router.state * * @requires ui.router.router * @requires ui.router.util * * @description * # ui.router.state sub-module * * This module is a dependency of the main ui.router module. Do not include this module as a dependency * in your angular app (use {@link ui.router} module instead). * */ angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']); /** * @ngdoc overview * @name ui.router * * @requires ui.router.state * * @description * # ui.router * * ## The main module for ui.router * There are several sub-modules included with the ui.router module, however only this module is needed * as a dependency within your angular app. The other modules are for organization purposes. * * The modules are: * * ui.router - the main "umbrella" module * * ui.router.router - * * *You'll need to include **only** this module as the dependency within your angular app.* * * <pre> * <!doctype html> * <html ng-app="myApp"> * <head> * <script src="js/angular.js"></script> * <!-- Include the ui-router script --> * <script src="js/angular-ui-router.min.js"></script> * <script> * // ...and add 'ui.router' as a dependency * var myApp = angular.module('myApp', ['ui.router']); * </script> * </head> * <body> * </body> * </html> * </pre> */ angular.module('ui.router', ['ui.router.state']); angular.module('ui.router.compat', ['ui.router']); /** * @ngdoc object * @name ui.router.util.$resolve * * @requires $q * @requires $injector * * @description * Manages resolution of (acyclic) graphs of promises. */ $Resolve.$inject = ['$q', '$injector']; function $Resolve( $q, $injector) { var VISIT_IN_PROGRESS = 1, VISIT_DONE = 2, NOTHING = {}, NO_DEPENDENCIES = [], NO_LOCALS = NOTHING, NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING }); /** * @ngdoc function * @name ui.router.util.$resolve#study * @methodOf ui.router.util.$resolve * * @description * Studies a set of invocables that are likely to be used multiple times. * <pre> * $resolve.study(invocables)(locals, parent, self) * </pre> * is equivalent to * <pre> * $resolve.resolve(invocables, locals, parent, self) * </pre> * but the former is more efficient (in fact `resolve` just calls `study` * internally). * * @param {object} invocables Invocable objects * @return {function} a function to pass in locals, parent and self */ this.study = function (invocables) { if (!isObject(invocables)) throw new Error("'invocables' must be an object"); // Perform a topological sort of invocables to build an ordered plan var plan = [], cycle = [], visited = {}; function visit(value, key) { if (visited[key] === VISIT_DONE) return; cycle.push(key); if (visited[key] === VISIT_IN_PROGRESS) { cycle.splice(0, cycle.indexOf(key)); throw new Error("Cyclic dependency: " + cycle.join(" -> ")); } visited[key] = VISIT_IN_PROGRESS; if (isString(value)) { plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES); } else { var params = $injector.annotate(value); forEach(params, function (param) { if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param); }); plan.push(key, value, params); } cycle.pop(); visited[key] = VISIT_DONE; } forEach(invocables, visit); invocables = cycle = visited = null; // plan is all that's required function isResolve(value) { return isObject(value) && value.then && value.$$promises; } return function (locals, parent, self) { if (isResolve(locals) && self === undefined) { self = parent; parent = locals; locals = null; } if (!locals) locals = NO_LOCALS; else if (!isObject(locals)) { throw new Error("'locals' must be an object"); } if (!parent) parent = NO_PARENT; else if (!isResolve(parent)) { throw new Error("'parent' must be a promise returned by $resolve.resolve()"); } // To complete the overall resolution, we have to wait for the parent // promise and for the promise for each invokable in our plan. var resolution = $q.defer(), result = resolution.promise, promises = result.$$promises = {}, values = extend({}, locals), wait = 1 + plan.length/3, merged = false; function done() { // Merge parent values we haven't got yet and publish our own $$values if (!--wait) { if (!merged) merge(values, parent.$$values); result.$$values = values; result.$$promises = true; // keep for isResolve() resolution.resolve(values); } } function fail(reason) { result.$$failure = reason; resolution.reject(reason); } // Short-circuit if parent has already failed if (isDefined(parent.$$failure)) { fail(parent.$$failure); return result; } // Merge parent values if the parent has already resolved, or merge // parent promises and wait if the parent resolve is still in progress. if (parent.$$values) { merged = merge(values, parent.$$values); done(); } else { extend(promises, parent.$$promises); parent.then(done, fail); } // Process each invocable in the plan, but ignore any where a local of the same name exists. for (var i=0, ii=plan.length; i<ii; i+=3) { if (locals.hasOwnProperty(plan[i])) done(); else invoke(plan[i], plan[i+1], plan[i+2]); } function invoke(key, invocable, params) { // Create a deferred for this invocation. Failures will propagate to the resolution as well. var invocation = $q.defer(), waitParams = 0; function onfailure(reason) { invocation.reject(reason); fail(reason); } // Wait for any parameter that we have a promise for (either from parent or from this // resolve; in that case study() will have made sure it's ordered before us in the plan). forEach(params, function (dep) { if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) { waitParams++; promises[dep].then(function (result) { values[dep] = result; if (!(--waitParams)) proceed(); }, onfailure); } }); if (!waitParams) proceed(); function proceed() { if (isDefined(result.$$failure)) return; try { invocation.resolve($injector.invoke(invocable, self, values)); invocation.promise.then(function (result) { values[key] = result; done(); }, onfailure); } catch (e) { onfailure(e); } } // Publish promise synchronously; invocations further down in the plan may depend on it. promises[key] = invocation.promise; } return result; }; }; /** * @ngdoc function * @name ui.router.util.$resolve#resolve * @methodOf ui.router.util.$resolve * * @description * Resolves a set of invocables. An invocable is a function to be invoked via * `$injector.invoke()`, and can have an arbitrary number of dependencies. * An invocable can either return a value directly, * or a `$q` promise. If a promise is returned it will be resolved and the * resulting value will be used instead. Dependencies of invocables are resolved * (in this order of precedence) * * - from the specified `locals` * - from another invocable that is part of this `$resolve` call * - from an invocable that is inherited from a `parent` call to `$resolve` * (or recursively * - from any ancestor `$resolve` of that parent). * * The return value of `$resolve` is a promise for an object that contains * (in this order of precedence) * * - any `locals` (if specified) * - the resolved return values of all injectables * - any values inherited from a `parent` call to `$resolve` (if specified) * * The promise will resolve after the `parent` promise (if any) and all promises * returned by injectables have been resolved. If any invocable * (or `$injector.invoke`) throws an exception, or if a promise returned by an * invocable is rejected, the `$resolve` promise is immediately rejected with the * same error. A rejection of a `parent` promise (if specified) will likewise be * propagated immediately. Once the `$resolve` promise has been rejected, no * further invocables will be called. * * Cyclic dependencies between invocables are not permitted and will caues `$resolve` * to throw an error. As a special case, an injectable can depend on a parameter * with the same name as the injectable, which will be fulfilled from the `parent` * injectable of the same name. This allows inherited values to be decorated. * Note that in this case any other injectable in the same `$resolve` with the same * dependency would see the decorated value, not the inherited value. * * Note that missing dependencies -- unlike cyclic dependencies -- will cause an * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous) * exception. * * Invocables are invoked eagerly as soon as all dependencies are available. * This is true even for dependencies inherited from a `parent` call to `$resolve`. * * As a special case, an invocable can be a string, in which case it is taken to * be a service name to be passed to `$injector.get()`. This is supported primarily * for backwards-compatibility with the `resolve` property of `$routeProvider` * routes. * * @param {object} invocables functions to invoke or * `$injector` services to fetch. * @param {object} locals values to make available to the injectables * @param {object} parent a promise returned by another call to `$resolve`. * @param {object} self the `this` for the invoked methods * @return {object} Promise for an object that contains the resolved return value * of all invocables, as well as any inherited and local values. */ this.resolve = function (invocables, locals, parent, self) { return this.study(invocables)(locals, parent, self); }; } angular.module('ui.router.util').service('$resolve', $Resolve); /** * @ngdoc object * @name ui.router.util.$templateFactory * * @requires $http * @requires $templateCache * @requires $injector * * @description * Service. Manages loading of templates. */ $TemplateFactory.$inject = ['$http', '$templateCache', '$injector']; function $TemplateFactory( $http, $templateCache, $injector) { /** * @ngdoc function * @name ui.router.util.$templateFactory#fromConfig * @methodOf ui.router.util.$templateFactory * * @description * Creates a template from a configuration object. * * @param {object} config Configuration object for which to load a template. * The following properties are search in the specified order, and the first one * that is defined is used to create the template: * * @param {string|object} config.template html string template or function to * load via {@link ui.router.util.$templateFactory#fromString fromString}. * @param {string|object} config.templateUrl url to load or a function returning * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}. * @param {Function} config.templateProvider function to invoke via * {@link ui.router.util.$templateFactory#fromProvider fromProvider}. * @param {object} params Parameters to pass to the template function. * @param {object} locals Locals to pass to `invoke` if the template is loaded * via a `templateProvider`. Defaults to `{ params: params }`. * * @return {string|object} The template html as a string, or a promise for * that string,or `null` if no template is configured. */ this.fromConfig = function (config, params, locals) { return ( isDefined(config.template) ? this.fromString(config.template, params) : isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) : isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) : null ); }; /** * @ngdoc function * @name ui.router.util.$templateFactory#fromString * @methodOf ui.router.util.$templateFactory * * @description * Creates a template from a string or a function returning a string. * * @param {string|object} template html template as a string or function that * returns an html template as a string. * @param {object} params Parameters to pass to the template function. * * @return {string|object} The template html as a string, or a promise for that * string. */ this.fromString = function (template, params) { return isFunction(template) ? template(params) : template; }; /** * @ngdoc function * @name ui.router.util.$templateFactory#fromUrl * @methodOf ui.router.util.$templateFactory * * @description * Loads a template from the a URL via `$http` and `$templateCache`. * * @param {string|Function} url url of the template to load, or a function * that returns a url. * @param {Object} params Parameters to pass to the url function. * @return {string|Promise.<string>} The template html as a string, or a promise * for that string. */ this.fromUrl = function (url, params) { if (isFunction(url)) url = url(params); if (url == null) return null; else return $http .get(url, { cache: $templateCache }) .then(function(response) { return response.data; }); }; /** * @ngdoc function * @name ui.router.util.$templateFactory#fromUrl * @methodOf ui.router.util.$templateFactory * * @description * Creates a template by invoking an injectable provider function. * * @param {Function} provider Function to invoke via `$injector.invoke` * @param {Object} params Parameters for the template. * @param {Object} locals Locals to pass to `invoke`. Defaults to * `{ params: params }`. * @return {string|Promise.<string>} The template html as a string, or a promise * for that string. */ this.fromProvider = function (provider, params, locals) { return $injector.invoke(provider, null, locals || { params: params }); }; } angular.module('ui.router.util').service('$templateFactory', $TemplateFactory); /** * @ngdoc object * @name ui.router.util.type:UrlMatcher * * @description * Matches URLs against patterns and extracts named parameters from the path or the search * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list * of search parameters. Multiple search parameter names are separated by '&'. Search parameters * do not influence whether or not a URL is matched, but their values are passed through into * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}. * * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace * syntax, which optionally allows a regular expression for the parameter to be specified: * * * `':'` name - colon placeholder * * `'*'` name - catch-all placeholder * * `'{' name '}'` - curly placeholder * * `'{' name ':' regexp '}'` - curly placeholder with regexp. Should the regexp itself contain * curly braces, they must be in matched pairs or escaped with a backslash. * * Parameter names may contain only word characters (latin letters, digits, and underscore) and * must be unique within the pattern (across both path and search parameters). For colon * placeholders or curly placeholders without an explicit regexp, a path parameter matches any * number of characters other than '/'. For catch-all placeholders the path parameter matches * any number of characters. * * Examples: * * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for * trailing slashes, and patterns have to match the entire path, not just a prefix. * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or * '/user/bob/details'. The second path segment will be captured as the parameter 'id'. * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax. * * `'/user/{id:[^/]*}'` - Same as the previous example. * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id * parameter consists of 1 to 8 hex digits. * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the * path into the parameter 'path'. * * `'/files/*path'` - ditto. * * @param {string} pattern the pattern to compile into a matcher. * * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns * non-null) will start with this prefix. * * @property {string} source The pattern that was passed into the contructor * * @property {string} sourcePath The path portion of the source property * * @property {string} sourceSearch The search portion of the source property * * @property {string} regex The constructed regex that will be used to match against the url when * it is time to determine which url will match. * * @returns {Object} New UrlMatcher object */ function UrlMatcher(pattern) { // Find all placeholders and create a compiled pattern, using either classic or curly syntax: // '*' name // ':' name // '{' name '}' // '{' name ':' regexp '}' // The regular expression is somewhat complicated due to the need to allow curly braces // inside the regular expression. The placeholder regexp breaks down as follows: // ([:*])(\w+) classic placeholder ($1 / $2) // \{(\w+)(?:\:( ... ))?\} curly brace placeholder ($3) with optional regexp ... ($4) // (?: ... | ... | ... )+ the regexp consists of any number of atoms, an atom being either // [^{}\\]+ - anything other than curly braces or backslash // \\. - a backslash escape // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms var placeholder = /([:*])(\w+)|\{(\w+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, names = {}, compiled = '^', last = 0, m, segments = this.segments = [], params = this.params = []; function addParameter(id) { if (!/^\w+(-+\w+)*$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'"); if (names[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'"); names[id] = true; params.push(id); } function quoteRegExp(string) { return string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&"); } this.source = pattern; // Split into static segments separated by path parameter placeholders. // The number of segments is always 1 more than the number of parameters. var id, regexp, segment; while ((m = placeholder.exec(pattern))) { id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null regexp = m[4] || (m[1] == '*' ? '.*' : '[^/]*'); segment = pattern.substring(last, m.index); if (segment.indexOf('?') >= 0) break; // we're into the search part compiled += quoteRegExp(segment) + '(' + regexp + ')'; addParameter(id); segments.push(segment); last = placeholder.lastIndex; } segment = pattern.substring(last); // Find any search parameter names and remove them from the last segment var i = segment.indexOf('?'); if (i >= 0) { var search = this.sourceSearch = segment.substring(i); segment = segment.substring(0, i); this.sourcePath = pattern.substring(0, last+i); // Allow parameters to be separated by '?' as well as '&' to make concat() easier forEach(search.substring(1).split(/[&?]/), addParameter); } else { this.sourcePath = pattern; this.sourceSearch = ''; } compiled += quoteRegExp(segment) + '$'; segments.push(segment); this.regexp = new RegExp(compiled); this.prefix = segments[0]; } /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#concat * @methodOf ui.router.util.type:UrlMatcher * * @description * Returns a new matcher for a pattern constructed by appending the path part and adding the * search parameters of the specified pattern to this pattern. The current pattern is not * modified. This can be understood as creating a pattern for URLs that are relative to (or * suffixes of) the current pattern. * * @example * The following two matchers are equivalent: * ``` * new UrlMatcher('/user/{id}?q').concat('/details?date'); * new UrlMatcher('/user/{id}/details?q&date'); * ``` * * @param {string} pattern The pattern to append. * @returns {ui.router.util.type:UrlMatcher} A matcher for the concatenated pattern. */ UrlMatcher.prototype.concat = function (pattern) { // Because order of search parameters is irrelevant, we can add our own search // parameters to the end of the new pattern. Parse the new pattern by itself // and then join the bits together, but it's much easier to do this on a string level. return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch); }; UrlMatcher.prototype.toString = function () { return this.source; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#exec * @methodOf ui.router.util.type:UrlMatcher * * @description * Tests the specified path against this matcher, and returns an object containing the captured * parameter values, or null if the path does not match. The returned object contains the values * of any search parameters that are mentioned in the pattern, but their value may be null if * they are not present in `searchParams`. This means that search parameters are always treated * as optional. * * @example * ``` * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', { x:'1', q:'hello' }); * // returns { id:'bob', q:'hello', r:null } * ``` * * @param {string} path The URL path to match, e.g. `$location.path()`. * @param {Object} searchParams URL search parameters, e.g. `$location.search()`. * @returns {Object} The captured parameter values. */ UrlMatcher.prototype.exec = function (path, searchParams) { var m = this.regexp.exec(path); if (!m) return null; var params = this.params, nTotal = params.length, nPath = this.segments.length-1, values = {}, i; if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'"); for (i=0; i<nPath; i++) values[params[i]] = m[i+1]; for (/**/; i<nTotal; i++) values[params[i]] = searchParams[params[i]]; return values; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#parameters * @methodOf ui.router.util.type:UrlMatcher * * @description * Returns the names of all path and search parameters of this pattern in an unspecified order. * * @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the * pattern has no parameters, an empty array is returned. */ UrlMatcher.prototype.parameters = function () { return this.params; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#format * @methodOf ui.router.util.type:UrlMatcher * * @description * Creates a URL that matches this pattern by substituting the specified values * for the path and search parameters. Null values for path parameters are * treated as empty strings. * * @example * ``` * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' }); * // returns '/user/bob?q=yes' * ``` * * @param {Object} values the values to substitute for the parameters in this pattern. * @returns {string} the formatted URL (path and optionally search part). */ UrlMatcher.prototype.format = function (values) { var segments = this.segments, params = this.params; if (!values) return segments.join(''); var nPath = segments.length-1, nTotal = params.length, result = segments[0], i, search, value; for (i=0; i<nPath; i++) { value = values[params[i]]; // TODO: Maybe we should throw on null here? It's not really good style to use '' and null interchangeabley if (value != null) result += encodeURIComponent(value); result += segments[i+1]; } for (/**/; i<nTotal; i++) { value = values[params[i]]; if (value != null) { result += (search ? '&' : '?') + params[i] + '=' + encodeURIComponent(value); search = true; } } return result; }; /** * @ngdoc object * @name ui.router.util.$urlMatcherFactory * * @description * Factory for {@link ui.router.util.type:UrlMatcher} instances. The factory is also available to providers * under the name `$urlMatcherFactoryProvider`. */ function $UrlMatcherFactory() { /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#compile * @methodOf ui.router.util.$urlMatcherFactory * * @description * Creates a {@link ui.router.util.type:UrlMatcher} for the specified pattern. * * @param {string} pattern The URL pattern. * @returns {ui.router.util.type:UrlMatcher} The UrlMatcher. */ this.compile = function (pattern) { return new UrlMatcher(pattern); }; /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#isMatcher * @methodOf ui.router.util.$urlMatcherFactory * * @description * Returns true if the specified object is a UrlMatcher, or false otherwise. * * @param {Object} object The object to perform the type check against. * @returns {Boolean} Returns `true` if the object has the following functions: `exec`, `format`, and `concat`. */ this.isMatcher = function (o) { return isObject(o) && isFunction(o.exec) && isFunction(o.format) && isFunction(o.concat); }; /* No need to document $get, since it returns this */ this.$get = function () { return this; }; } // Register as a provider so it's available to other providers angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory); /** * @ngdoc object * @name ui.router.router.$urlRouterProvider * * @requires ui.router.util.$urlMatcherFactoryProvider * * @description * `$urlRouterProvider` has the responsibility of watching `$location`. * When `$location` changes it runs through a list of rules one by one until a * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify * a url in a state configuration. All urls are compiled into a UrlMatcher object. * * There are several methods on `$urlRouterProvider` that make it useful to use directly * in your module config. */ $UrlRouterProvider.$inject = ['$urlMatcherFactoryProvider']; function $UrlRouterProvider( $urlMatcherFactory) { var rules = [], otherwise = null; // Returns a string that is a prefix of all strings matching the RegExp function regExpPrefix(re) { var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source); return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : ''; } // Interpolates matched values into a String.replace()-style pattern function interpolate(pattern, match) { return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) { return match[what === '$' ? 0 : Number(what)]; }); } /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#rule * @methodOf ui.router.router.$urlRouterProvider * * @description * Defines rules that are used by `$urlRouterProvider to find matches for * specific URLs. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * // Here's an example of how you might allow case insensitive urls * $urlRouterProvider.rule(function ($injector, $location) { * var path = $location.path(), * normalized = path.toLowerCase(); * * if (path !== normalized) { * return normalized; * } * }); * }); * </pre> * * @param {object} rule Handler function that takes `$injector` and `$location` * services as arguments. You can use them to return a valid path as a string. * * @return {object} $urlRouterProvider - $urlRouterProvider instance */ this.rule = function (rule) { if (!isFunction(rule)) throw new Error("'rule' must be a function"); rules.push(rule); return this; }; /** * @ngdoc object * @name ui.router.router.$urlRouterProvider#otherwise * @methodOf ui.router.router.$urlRouterProvider * * @description * Defines a path that is used when an invalied route is requested. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * // if the path doesn't match any of the urls you configured * // otherwise will take care of routing the user to the * // specified url * $urlRouterProvider.otherwise('/index'); * * // Example of using function rule as param * $urlRouterProvider.otherwise(function ($injector, $location) { * ... * }); * }); * </pre> * * @param {string|object} rule The url path you want to redirect to or a function * rule that returns the url path. The function version is passed two params: * `$injector` and `$location` services. * * @return {object} $urlRouterProvider - $urlRouterProvider instance */ this.otherwise = function (rule) { if (isString(rule)) { var redirect = rule; rule = function () { return redirect; }; } else if (!isFunction(rule)) throw new Error("'rule' must be a function"); otherwise = rule; return this; }; function handleIfMatch($injector, handler, match) { if (!match) return false; var result = $injector.invoke(handler, handler, { $match: match }); return isDefined(result) ? result : true; } /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#when * @methodOf ui.router.router.$urlRouterProvider * * @description * Registers a handler for a given url matching. if handle is a string, it is * treated as a redirect, and is interpolated according to the syyntax of match * (i.e. like String.replace() for RegExp, or like a UrlMatcher pattern otherwise). * * If the handler is a function, it is injectable. It gets invoked if `$location` * matches. You have the option of inject the match object as `$match`. * * The handler can return * * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter` * will continue trying to find another one that matches. * - **string** which is treated as a redirect and passed to `$location.url()` * - **void** or any **truthy** value tells `$urlRouter` that the url was handled. * * @example * <pre> * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * $urlRouterProvider.when($state.url, function ($match, $stateParams) { * if ($state.$current.navigable !== state || * !equalForKeys($match, $stateParams) { * $state.transitionTo(state, $match, false); * } * }); * }); * </pre> * * @param {string|object} what The incoming path that you want to redirect. * @param {string|object} handler The path you want to redirect your user to. */ this.when = function (what, handler) { var redirect, handlerIsString = isString(handler); if (isString(what)) what = $urlMatcherFactory.compile(what); if (!handlerIsString && !isFunction(handler) && !isArray(handler)) throw new Error("invalid 'handler' in when()"); var strategies = { matcher: function (what, handler) { if (handlerIsString) { redirect = $urlMatcherFactory.compile(handler); handler = ['$match', function ($match) { return redirect.format($match); }]; } return extend(function ($injector, $location) { return handleIfMatch($injector, handler, what.exec($location.path(), $location.search())); }, { prefix: isString(what.prefix) ? what.prefix : '' }); }, regex: function (what, handler) { if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky"); if (handlerIsString) { redirect = handler; handler = ['$match', function ($match) { return interpolate(redirect, $match); }]; } return extend(function ($injector, $location) { return handleIfMatch($injector, handler, what.exec($location.path())); }, { prefix: regExpPrefix(what) }); } }; var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp }; for (var n in check) { if (check[n]) { return this.rule(strategies[n](what, handler)); } } throw new Error("invalid 'what' in when()"); }; /** * @ngdoc object * @name ui.router.router.$urlRouter * * @requires $location * @requires $rootScope * @requires $injector * * @description * */ this.$get = [ '$location', '$rootScope', '$injector', function ($location, $rootScope, $injector) { // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree function update(evt) { if (evt && evt.defaultPrevented) return; function check(rule) { var handled = rule($injector, $location); if (handled) { if (isString(handled)) $location.replace().url(handled); return true; } return false; } var n=rules.length, i; for (i=0; i<n; i++) { if (check(rules[i])) return; } // always check otherwise last to allow dynamic updates to the set of rules if (otherwise) check(otherwise); } $rootScope.$on('$locationChangeSuccess', update); return { /** * @ngdoc function * @name ui.router.router.$urlRouter#sync * @methodOf ui.router.router.$urlRouter * * @description * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`. * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event, * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed * with the transition by calling `$urlRouter.sync()`. * * @example * <pre> * angular.module('app', ['ui.router']); * .run(function($rootScope, $urlRouter) { * $rootScope.$on('$locationChangeSuccess', function(evt) { * // Halt state change from even starting * evt.preventDefault(); * // Perform custom logic * var meetsRequirement = ... * // Continue with the update and state transition if logic allows * if (meetsRequirement) $urlRouter.sync(); * }); * }); * </pre> */ sync: function () { update(); } }; }]; } angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider); /** * @ngdoc object * @name ui.router.state.$stateProvider * * @requires ui.router.router.$urlRouterProvider * @requires ui.router.util.$urlMatcherFactoryProvider * @requires $locationProvider * * @description * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely * on state. * * A state corresponds to a "place" in the application in terms of the overall UI and * navigation. A state describes (via the controller / template / view properties) what * the UI looks like and does at that place. * * States often have things in common, and the primary way of factoring out these * commonalities in this model is via the state hierarchy, i.e. parent/child states aka * nested states. * * The `$stateProvider` provides interfaces to declare these states for your app. */ $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider', '$locationProvider']; function $StateProvider( $urlRouterProvider, $urlMatcherFactory, $locationProvider) { var root, states = {}, $state, queue = {}, abstractKey = 'abstract'; // Builds state properties from definition passed to registerState() var stateBuilder = { // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined. // state.children = []; // if (parent) parent.children.push(state); parent: function(state) { if (isDefined(state.parent) && state.parent) return findState(state.parent); // regex matches any valid composite state name // would match "contact.list" but not "contacts" var compositeName = /^(.+)\.[^.]+$/.exec(state.name); return compositeName ? findState(compositeName[1]) : root; }, // inherit 'data' from parent and override by own values (if any) data: function(state) { if (state.parent && state.parent.data) { state.data = state.self.data = extend({}, state.parent.data, state.data); } return state.data; }, // Build a URLMatcher if necessary, either via a relative or absolute URL url: function(state) { var url = state.url; if (isString(url)) { if (url.charAt(0) == '^') { return $urlMatcherFactory.compile(url.substring(1)); } return (state.parent.navigable || root).url.concat(url); } if ($urlMatcherFactory.isMatcher(url) || url == null) { return url; } throw new Error("Invalid url '" + url + "' in state '" + state + "'"); }, // Keep track of the closest ancestor state that has a URL (i.e. is navigable) navigable: function(state) { return state.url ? state : (state.parent ? state.parent.navigable : null); }, // Derive parameters for this state and ensure they're a super-set of parent's parameters params: function(state) { if (!state.params) { return state.url ? state.url.parameters() : state.parent.params; } if (!isArray(state.params)) throw new Error("Invalid params in state '" + state + "'"); if (state.url) throw new Error("Both params and url specicified in state '" + state + "'"); return state.params; }, // If there is no explicit multi-view configuration, make one up so we don't have // to handle both cases in the view directive later. Note that having an explicit // 'views' property will mean the default unnamed view properties are ignored. This // is also a good time to resolve view names to absolute names, so everything is a // straight lookup at link time. views: function(state) { var views = {}; forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) { if (name.indexOf('@') < 0) name += '@' + state.parent.name; views[name] = view; }); return views; }, ownParams: function(state) { if (!state.parent) { return state.params; } var paramNames = {}; forEach(state.params, function (p) { paramNames[p] = true; }); forEach(state.parent.params, function (p) { if (!paramNames[p]) { throw new Error("Missing required parameter '" + p + "' in state '" + state.name + "'"); } paramNames[p] = false; }); var ownParams = []; forEach(paramNames, function (own, p) { if (own) ownParams.push(p); }); return ownParams; }, // Keep a full path from the root down to this state as this is needed for state activation. path: function(state) { return state.parent ? state.parent.path.concat(state) : []; // exclude root from path }, // Speed up $state.contains() as it's used a lot includes: function(state) { var includes = state.parent ? extend({}, state.parent.includes) : {}; includes[state.name] = true; return includes; }, $delegates: {} }; function isRelative(stateName) { return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0; } function findState(stateOrName, base) { var isStr = isString(stateOrName), name = isStr ? stateOrName : stateOrName.name, path = isRelative(name); if (path) { if (!base) throw new Error("No reference point given for path '" + name + "'"); var rel = name.split("."), i = 0, pathLength = rel.length, current = base; for (; i < pathLength; i++) { if (rel[i] === "" && i === 0) { current = base; continue; } if (rel[i] === "^") { if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'"); current = current.parent; continue; } break; } rel = rel.slice(i).join("."); name = current.name + (current.name && rel ? "." : "") + rel; } var state = states[name]; if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) { return state; } return undefined; } function queueState(parentName, state) { if (!queue[parentName]) { queue[parentName] = []; } queue[parentName].push(state); } function registerState(state) { // Wrap a new object around the state so we can store our private details easily. state = inherit(state, { self: state, resolve: state.resolve || {}, toString: function() { return this.name; } }); var name = state.name; if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name"); if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined"); // Get parent name var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.')) : (isString(state.parent)) ? state.parent : ''; // If parent is not registered yet, add state to queue and register later if (parentName && !states[parentName]) { return queueState(parentName, state.self); } for (var key in stateBuilder) { if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]); } states[name] = state; // Register the state in the global state list and with $urlRouter if necessary. if (!state[abstractKey] && state.url) { $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) { if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) { $state.transitionTo(state, $match, { location: false }); } }]); } // Register any queued children if (queue[name]) { for (var i = 0; i < queue[name].length; i++) { registerState(queue[name][i]); } } return state; } // Checks text to see if it looks like a glob. function isGlob (text) { return text.indexOf('*') > -1; } // Returns true if glob matches current $state name. funct