missing files

Signed-off-by: Gwenhael Le Moine <gwenhael.le.moine@gmail.com>
This commit is contained in:
Gwenhael Le Moine 2017-11-06 16:55:00 +01:00
parent 73a47c9594
commit 50eb9da406
No known key found for this signature in database
GPG key ID: FDFE3669426707A7
968 changed files with 730355 additions and 37 deletions

38
.gitignore vendored
View file

@ -1,37 +1 @@
*.gem .bundle/
*.rbc
/.config
/coverage/
/InstalledFiles
/pkg/
/spec/reports/
/test/tmp/
/test/version_tmp/
/tmp/
## Specific to RubyMotion:
.dat*
.repl_history
#build/
## Documentation cache and generated files:
/.yardoc/
/_yardoc/
/doc/
/rdoc/
## Environment normalisation:
/.bundle/
/lib/bundler/man/
# for a library or gem, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# Gemfile.lock
# .ruby-version
# .ruby-gemset
# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc
/thin.*
/bundle/
vendor/

View file

@ -0,0 +1 @@
../google-closure-compiler-js/cmd.js

1
public/app/vendor/node_modules/.bin/tsc generated vendored Symbolic link
View file

@ -0,0 +1 @@
../typescript/bin/tsc

1
public/app/vendor/node_modules/.bin/tsserver generated vendored Symbolic link
View file

@ -0,0 +1 @@
../typescript/bin/tsserver

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,113 @@
# Report an Issue
Help us make UI-Router better! If you think you might have found a bug, or some other weirdness, start by making sure
it hasn't already been reported. You can [search through existing issues](https://github.com/angular-ui/ui-router/search?q=wat%3F&type=Issues)
to see if someone's reported one similar to yours.
If not, then [create a plunkr](http://bit.ly/UIR-Plunk) that demonstrates the problem (try to use as little code
as possible: the more minimalist, the faster we can debug it).
Next, [create a new issue](https://github.com/angular-ui/ui-router/issues/new) that briefly explains the problem,
and provides a bit of background as to the circumstances that triggered it. Don't forget to include the link to
that plunkr you created!
**Note**: If you're unsure how a feature is used, or are encountering some unexpected behavior that you aren't sure
is a bug, it's best to talk it out on
[StackOverflow](http://stackoverflow.com/questions/ask?tags=angularjs,angular-ui-router) before reporting it. This
keeps development streamlined, and helps us focus on building great software.
Issues only! |
-------------|
Please keep in mind that the issue tracker is for *issues*. Please do *not* post an issue if you need help or support. Instead, see one of the above-mentioned forums or [IRC](irc://irc.freenode.net/#angularjs). |
#### Purple Labels
A purple label means that **you** need to take some further action.
- ![Not Actionable - Need Info](https://angular-ui.github.io/ui-router/ngdoc_assets/incomplete.png): Your issue is not specific enough, or there is no clear action that we can take. Please clarify and refine your issue.
- ![Plunkr Please](https://angular-ui.github.io/ui-router/ngdoc_assets/example.png): Please [create a plunkr](http://bit.ly/UIR-Plunk)
- ![StackOverflow](https://angular-ui.github.io/ui-router/ngdoc_assets/so.png): We suspect your issue is really a help request, or could be answered by the community. Please ask your question on [StackOverflow](http://stackoverflow.com/questions/ask?tags=angularjs,angular-ui-router). If you determine that is an actual issue, please explain why.
If your issue gets labeled with purple label, no further action will be taken until you respond to the label appropriately.
# Contribute
**(1)** See the **[Developing](#developing)** section below, to get the development version of UI-Router up and running on your local machine.
**(2)** Check out the [roadmap](https://github.com/angular-ui/ui-router/milestones) to see where the project is headed, and if your feature idea fits with where we're headed.
**(3)** If you're not sure, [open an RFC](https://github.com/angular-ui/ui-router/issues/new?title=RFC:%20My%20idea) to get some feedback on your idea.
**(4)** Finally, commit some code and open a pull request. Code & commits should abide by the following rules:
- *Always* have test coverage for new features (or regression tests for bug fixes), and *never* break existing tests
- Commits should represent one logical change each; if a feature goes through multiple iterations, squash your commits down to one
- Make sure to follow the [Angular commit message format](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#commit-message-format) so your change will appear in the changelog of the next release.
- Changes should always respect the coding style of the project
# Developing
UI-Router uses <code>npm</code> and <code>Rollup</code>.
## Fetch the source code
The code for Angular UI-Router is split into two source repositories:
* [UI-Router Core](https://github.com/ui-router/core) (`@uirouter/core` on npm)
* [UI-Router for Angular 1](https://github.com/angular-ui/ui-router) (`@ui-router/angularjs` on npm)
Clone both repositories into directories next to each other.
```
mkdir uirouter
cd uirouter
git clone https://github.com/angular-ui/ui-router.git angularjs
git clone https://github.com/ui-router/core.git core
```
## Install dependencies
Use `npm` to install the development dependencies for each repository.
```
cd core
npm install
cd ../angularjs
npm install
cd ..
```
## Link the directories
This step is necessary if you need to modify any code in `@uirouter/core`.
Using `npm`, link `@uirouter/core` into `@uirouter/angularjs`
```
cd core
npm link
cd ../angularjs
npm link '@uirouter/core'
```
After executing these steps, `@uirouter/angularjs` will be depend on your local copy of `@uirouter/core` instead of the version listed in `package.json`.
## Develop
These scripts may be run in the `angularjs` directory:
* `npm run build`: Compiles TypeScript source
* `npm run package`: Compiles TypeScript source and creates the Rollup bundles.
* `npm test`: Runs the test suite (against Angular 1.2 through 1.5).
* `npm run watch`: Continuously compiles the source and runs the test suite (when either source or tests change).
Scripts of the same name (in the `core` directory) can be used.
* `npm run build`: Compiles `@uirouter/core` TypeScript source
* `npm test`: Runs the `@uirouter/core` test suite
* `npm run watch`: Continuously compiles the source and runs the `@uirouter/core` test suite (when core source or tests change).
If you've followed the [linking instructions](#link-the-directories), it's useful to run both
`npm run watch` tasks (each task from `@uirouter/core` *and* `@uirouter/angularjs`).
This ensures that changes to either `@uirouter/core` and `@uirouter/angularjs` compile successfully and are run against their test suites.

View file

@ -0,0 +1,48 @@
# [UI Router for Angular 1](https://ui-router.github.io/ng1/docs/latest)
#### The de-facto solution to flexible routing in angular 1
<div style="display: flex;">
<iframe style="display: inline-block;" src="https://ghbtns.com/github-btn.html?user=angular-ui&repo=ui-router&type=fork&count=true&size=medium" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
<iframe style="display: inline-block;" src="https://ghbtns.com/github-btn.html?user=angular-ui&repo=ui-router&type=star&count=true&size=medium" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
[![Build Status](https://travis-ci.org/angular-ui/ui-router.svg?branch=master)](https://travis-ci.org/angular-ui/ui-router)
</div>
Angular UI-Router is a client-side [Single Page Application](https://en.wikipedia.org/wiki/Single-page_application)
routing framework for [AngularJS](http://angularjs.org).
**[View on Github](http://github.com/angular-ui/ui-router) |**
**[Tutorials](https://ui-router.github.io/ng1/tutorials/)** |
**[Guides](https://ui-router.github.io/guide) |**
**[Sample App](http://ui-router.github.io/resources/sampleapp/) |**
**[Wiki](https://github.com/angular-ui/ui-router/wiki) |**
**[FAQ](https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions)**
#### API Documentation Organization
The documentation is arranged according to API concern, such as `url`, `resolve`, and `core`.
For a list of services and objects that can be injectable, see the [`injectables` section](./injectables.html).
By default, only the public UI-Router API is shown.
To view both public API and the internal APIs, check the "Internal UI-Router API" checkbox.
#### Typescript
UI-Router is written in Typescript.
The API documentation is generated using [TypeDoc](https://github.com/TypeStrong/typedoc).
The documentation reflects the Typescript classes, interfaces, and parameter types information embedded in the source code.
#### Contributing
Angular UI-Router depends on the framework agnostic `@uirouter/core`.
To contribute to the documentation, please submit a PR to either
[@uirouter/angularjs](http://github.com/angular-ui/ui-router)
or
[@uirouter/core](http://github.com/ui-router/core).
To find where a specific piece of documentation is written, follow the links that say:
> _Defined in ui-router/somedir/somefile.ts_

View file

@ -0,0 +1,53 @@
This issue tracker is for Bug Reports and Feature Requests only.
Please direct requests for help to StackOverflow. See http://bit.ly/UIR-SOF for details.
This is a:
- [ ] Bug Report
- [ ] Feature Request
- [ ] General Query
My version of UI-Router is: (version)
# Bug Report
#### Current Behavior:
(current behavior here)
#### Expected Behavior:
(expected behavior here)
#### Link to Plunker that reproduces the issue:
http://bit.ly/UIR-Plunk
# Feature Request
(feature request here)
# General Query
Please direct general implementation questions to StackOverflow:
http://stackoverflow.com/questions/ask?tags=angularjs,angular-ui-router
Please review the Sample Application which highlights common approaches:
https://github.com/ui-router/sample-app-ng1
- [ ] I have already asked my question on StackOverflow and nobody could answer the question
- [ ] I have already reviewed the sample application for examples of common approaches
- [ ] I believe my question can only be answered by the UI-Router maintainers
(general query here)

View file

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2013-2015 The AngularUI Team, Karsten Sperling
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.

View file

@ -0,0 +1,56 @@
# AngularUI Router &nbsp;[![Build Status](https://travis-ci.org/angular-ui/ui-router.svg?branch=master)](https://travis-ci.org/angular-ui/ui-router)
**Note: this is the Angular 1.x source for UI-Router version 1.0. If you are looking for the source for UI-Router
version 0.2.x, it can be found [here](https://github.com/angular-ui/ui-router/tree/legacy)**
---
#### The de-facto solution to flexible routing in angular
---
**[Tutorials](https://ui-router.github.io/tutorials/)** |
**[API Docs](https://ui-router.github.io/docs/latest/)** |
**[Download stable](http://unpkg.com/@uirouter/angularjs@latest/release/angular-ui-router.js)** (or **[Minified](http://unpkg.com/@uirouter/angularjs@latest/release/angular-ui-router.min.js)**) **|**
**[Guide](https://github.com/angular-ui/ui-router/wiki) |**
**[Sample App](http://ui-router.github.io/resources/sampleapp/) |**
**[FAQ](https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions) |**
**[Report an Issue](https://github.com/angular-ui/ui-router/blob/master/CONTRIBUTING.md#report-an-issue) |**
**[Contribute](https://github.com/angular-ui/ui-router/blob/master/CONTRIBUTING.md#contribute) |**
**[Help!](http://stackoverflow.com/questions/ask?tags=angularjs,angular-ui-router) |**
---
Angular UI-Router is a client-side [Single Page Application](https://en.wikipedia.org/wiki/Single-page_application)
routing framework for [AngularJS](http://angularjs.org).
Routing frameworks for SPAs update the browser's URL as the user navigates through the app. Conversely, this allows
changes to the browser's URL to drive navigation through the app, thus allowing the user to create a bookmark to a
location deep within the SPA.
UI-Router applications are modeled as a hierarchical tree of states. UI-Router provides a
[*state machine*](https://en.wikipedia.org/wiki/Finite-state_machine) to manage the transitions between those
application states in a transaction-like manner.
## Get Started
- [UI-Router for Angular 1](https://ui-router.github.io/ng1)
- [UI-Router for Angular 2](https://ui-router.github.io/ng2)
- [UI-Router for React](https://ui-router.github.io/react)
## Resources
* [In-Depth Guide](https://github.com/angular-ui/ui-router/wiki)
* [Slides comparing ngRoute to ui-router](http://slid.es/timkindberg/ui-router#/)
* [UI-Router Extras / Addons for legacy (0.x)](http://christopherthielen.github.io/ui-router-extras/#/home) (@christopherthielen)
### Videos
* [Introduction Video](https://egghead.io/lessons/angularjs-introduction-ui-router) (egghead.io)
* [Tim Kindberg on Angular UI-Router](https://www.youtube.com/watch?v=lBqiZSemrqg)
* [Activating States](https://egghead.io/lessons/angularjs-ui-router-activating-states) (egghead.io)
* [Learn Angular.js using UI-Router](http://youtu.be/QETUuZ27N0w) (LearnCode.academy)
## Reporting issues and Contributing
Please read our [Contributor guidelines](CONTRIBUTING.md) before reporting an issue or creating a pull request.

View file

@ -0,0 +1,8 @@
{
"ARTIFACTS": [
"lib",
"lib-esm",
"release",
"package.json"
]
}

View file

@ -0,0 +1 @@
export declare const ng: any;

View file

@ -0,0 +1,4 @@
import * as ng_from_import from "angular";
var ng_from_global = angular;
export var ng = (ng_from_import && ng_from_import.module) ? ng_from_import : ng_from_global;
//# sourceMappingURL=angular.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "angular.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/angular.ts"
],
"names": [],
"mappings": "AAKA,OAAO,KAAK,cAAc,MAAM,SAAS,CAAC;AAC1C,IAAI,cAAc,GAAG,OAAO,CAAC;AAE7B,MAAM,CAAC,IAAM,EAAE,GAAG,CAAC,cAAc,IAAI,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC",
"sourcesContent": [
"/**\n * @hidden\n * @module ng1\n */ /** */\ndeclare var angular;\nimport * as ng_from_import from \"angular\";\nlet ng_from_global = angular;\n\nexport const ng = (ng_from_import && ng_from_import.module) ? ng_from_import : ng_from_global;\n"
]
}

View file

@ -0,0 +1,3 @@
/** @hidden Used for typedoc */
export interface ng1_directive {
}

View file

@ -0,0 +1,569 @@
/**
* # Angular 1 Directives
*
* These are the directives included in UI-Router for Angular 1.
* These directives are used in templates to create viewports and link/navigate to states.
*
* @ng1api
* @preferred
* @module directives
*/ /** for typedoc */
import { ng as angular } from "../angular";
import { extend, forEach, tail, isString, isObject, isArray, parse, noop, unnestR, identity, uniqR, inArray, removeFrom } from "@uirouter/core";
/** @hidden */
function parseStateRef(ref) {
var paramsOnly = ref.match(/^\s*({[^}]*})\s*$/), parsed;
if (paramsOnly)
ref = '(' + paramsOnly[1] + ')';
parsed = ref.replace(/\n/g, " ").match(/^\s*([^(]*?)\s*(\((.*)\))?\s*$/);
if (!parsed || parsed.length !== 4)
throw new Error("Invalid state ref '" + ref + "'");
return { state: parsed[1] || null, paramExpr: parsed[3] || null };
}
/** @hidden */
function stateContext(el) {
var $uiView = el.parent().inheritedData('$uiView');
var path = parse('$cfg.path')($uiView);
return path ? tail(path).state.name : undefined;
}
/** @hidden */
function processedDef($state, $element, def) {
var uiState = def.uiState || $state.current.name;
var uiStateOpts = extend(defaultOpts($element, $state), def.uiStateOpts || {});
var href = $state.href(uiState, def.uiStateParams, uiStateOpts);
return { uiState: uiState, uiStateParams: def.uiStateParams, uiStateOpts: uiStateOpts, href: href };
}
/** @hidden */
function getTypeInfo(el) {
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';
var isForm = el[0].nodeName === "FORM";
return {
attr: isForm ? "action" : (isSvg ? 'xlink:href' : 'href'),
isAnchor: el.prop("tagName").toUpperCase() === "A",
clickable: !isForm
};
}
/** @hidden */
function clickHook(el, $state, $timeout, type, getDef) {
return function (e) {
var button = e.which || e.button, target = getDef();
if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {
// HACK: This is to allow ng-clicks to be processed before the transition is initiated:
var transition = $timeout(function () {
$state.go(target.uiState, target.uiStateParams, target.uiStateOpts);
});
e.preventDefault();
// if the state has no URL, ignore one preventDefault from the <a> directive.
var ignorePreventDefaultCount = type.isAnchor && !target.href ? 1 : 0;
e.preventDefault = function () {
if (ignorePreventDefaultCount-- <= 0)
$timeout.cancel(transition);
};
}
};
}
/** @hidden */
function defaultOpts(el, $state) {
return {
relative: stateContext(el) || $state.$current,
inherit: true,
source: "sref"
};
}
/** @hidden */
function bindEvents(element, scope, hookFn, uiStateOpts) {
var events;
if (uiStateOpts) {
events = uiStateOpts.events;
}
if (!isArray(events)) {
events = ['click'];
}
var on = element.on ? 'on' : 'bind';
for (var _i = 0, events_1 = events; _i < events_1.length; _i++) {
var event_1 = events_1[_i];
element[on](event_1, hookFn);
}
scope.$on('$destroy', function () {
var off = element.off ? 'off' : 'unbind';
for (var _i = 0, events_2 = events; _i < events_2.length; _i++) {
var event_2 = events_2[_i];
element[off](event_2, hookFn);
}
});
}
/**
* `ui-sref`: A directive for linking to a state
*
* A directive which links to a state (and optionally, parameters).
* When clicked, this directive activates the linked state with the supplied parameter values.
*
* ### Linked State
* The attribute value of the `ui-sref` is the name of the state to link to.
*
* #### Example:
* This will activate the `home` state when the link is clicked.
* ```html
* <a ui-sref="home">Home</a>
* ```
*
* ### Relative Links
* You can also use relative state paths within `ui-sref`, just like a relative path passed to `$state.go()` ([[StateService.go]]).
* You just need to be aware that the path is relative to the state that *created* the link.
* This allows a state to create a relative `ui-sref` which always targets the same destination.
*
* #### Example:
* Both these links are relative to the parent state, even when a child state is currently active.
* ```html
* <a ui-sref=".child1">child 1 state</a>
* <a ui-sref=".child2">child 2 state</a>
* ```
*
* This link activates the parent state.
* ```html
* <a ui-sref="^">Return</a>
* ```
*
* ### hrefs
* If the linked state has a URL, the directive will automatically generate and
* update the `href` attribute (using the [[StateService.href]] method).
*
* #### Example:
* Assuming the `users` state has a url of `/users/`
* ```html
* <a ui-sref="users" href="/users/">Users</a>
* ```
*
* ### Parameter Values
* In addition to the state name, a `ui-sref` can include parameter values which are applied when activating the state.
* Param values can be provided in the `ui-sref` value after the state name, enclosed by parentheses.
* The content inside the parentheses is an expression, evaluated to the parameter values.
*
* #### Example:
* This example renders a list of links to users.
* The state's `userId` parameter value comes from each user's `user.id` property.
* ```html
* <li ng-repeat="user in users">
* <a ui-sref="users.detail({ userId: user.id })">{{ user.displayName }}</a>
* </li>
* ```
*
* Note:
* The parameter values expression is `$watch`ed for updates.
*
* ### Transition Options
* You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-sref-opts` attribute.
* Options are restricted to `location`, `inherit`, and `reload`.
*
* #### Example:
* ```html
* <a ui-sref="home" ui-sref-opts="{ reload: true }">Home</a>
* ```
*
* ### Other DOM Events
*
* You can also customize which DOM events to respond to (instead of `click`) by
* providing an `events` array in the `ui-sref-opts` attribute.
*
* #### Example:
* ```html
* <input type="text" ui-sref="contacts" ui-sref-opts="{ events: ['change', 'blur'] }">
* ```
*
* ### Highlighting the active link
* This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.
*
* ### Examples
* If you have the following template:
*
* ```html
* <a ui-sref="home">Home</a>
* <a ui-sref="about">About</a>
* <a ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
* </li>
* </ul>
* ```
*
* Then (assuming the current state is `contacts`) the rendered html including hrefs would be:
*
* ```html
* <a href="#/home" ui-sref="home">Home</a>
* <a href="#/about" ui-sref="about">About</a>
* <a href="#/contacts?page=2" ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
* </li>
* </ul>
*
* <a href="#/home" ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
* ```
*
* ### Notes
*
* - You can use `ui-sref` to change **only the parameter values** by omitting the state name and parentheses.
* #### Example:
* Sets the `lang` parameter to `en` and remains on the same state.
*
* ```html
* <a ui-sref="{ lang: 'en' }">English</a>
* ```
*
* - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.
*
* - Unlike the parameter values expression, the state name is not `$watch`ed (for performance reasons).
* If you need to dynamically update the state being linked to, use the fully dynamic [[uiState]] directive.
*/
var uiSref;
uiSref = ['$uiRouter', '$timeout',
function $StateRefDirective($uiRouter, $timeout) {
var $state = $uiRouter.stateService;
return {
restrict: 'A',
require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
link: function (scope, element, attrs, uiSrefActive) {
var type = getTypeInfo(element);
var active = uiSrefActive[1] || uiSrefActive[0];
var unlinkInfoFn = null;
var hookFn;
var rawDef = {};
var getDef = function () { return processedDef($state, element, rawDef); };
var ref = parseStateRef(attrs.uiSref);
rawDef.uiState = ref.state;
rawDef.uiStateOpts = attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {};
function update() {
var def = getDef();
if (unlinkInfoFn)
unlinkInfoFn();
if (active)
unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);
if (def.href != null)
attrs.$set(type.attr, def.href);
}
if (ref.paramExpr) {
scope.$watch(ref.paramExpr, function (val) {
rawDef.uiStateParams = extend({}, val);
update();
}, true);
rawDef.uiStateParams = extend({}, scope.$eval(ref.paramExpr));
}
update();
scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));
scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));
if (!type.clickable)
return;
hookFn = clickHook(element, $state, $timeout, type, getDef);
bindEvents(element, scope, hookFn, rawDef.uiStateOpts);
}
};
}];
/**
* `ui-state`: A fully dynamic directive for linking to a state
*
* A directive which links to a state (and optionally, parameters).
* When clicked, this directive activates the linked state with the supplied parameter values.
*
* **This directive is very similar to [[uiSref]], but it `$observe`s and `$watch`es/evaluates all its inputs.**
*
* A directive which links to a state (and optionally, parameters).
* When clicked, this directive activates the linked state with the supplied parameter values.
*
* ### Linked State
* The attribute value of `ui-state` is an expression which is `$watch`ed and evaluated as the state to link to.
* **This is in contrast with `ui-sref`, which takes a state name as a string literal.**
*
* #### Example:
* Create a list of links.
* ```html
* <li ng-repeat="link in navlinks">
* <a ui-state="link.state">{{ link.displayName }}</a>
* </li>
* ```
*
* ### Relative Links
* If the expression evaluates to a relative path, it is processed like [[uiSref]].
* You just need to be aware that the path is relative to the state that *created* the link.
* This allows a state to create relative `ui-state` which always targets the same destination.
*
* ### hrefs
* If the linked state has a URL, the directive will automatically generate and
* update the `href` attribute (using the [[StateService.href]] method).
*
* ### Parameter Values
* In addition to the state name expression, a `ui-state` can include parameter values which are applied when activating the state.
* Param values should be provided using the `ui-state-params` attribute.
* The `ui-state-params` attribute value is `$watch`ed and evaluated as an expression.
*
* #### Example:
* This example renders a list of links with param values.
* The state's `userId` parameter value comes from each user's `user.id` property.
* ```html
* <li ng-repeat="link in navlinks">
* <a ui-state="link.state" ui-state-params="link.params">{{ link.displayName }}</a>
* </li>
* ```
*
* ### Transition Options
* You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-state-opts` attribute.
* Options are restricted to `location`, `inherit`, and `reload`.
* The value of the `ui-state-opts` is `$watch`ed and evaluated as an expression.
*
* #### Example:
* ```html
* <a ui-state="returnto.state" ui-state-opts="{ reload: true }">Home</a>
* ```
*
* ### Other DOM Events
*
* You can also customize which DOM events to respond to (instead of `click`) by
* providing an `events` array in the `ui-state-opts` attribute.
*
* #### Example:
* ```html
* <input type="text" ui-state="contacts" ui-state-opts="{ events: ['change', 'blur'] }">
* ```
*
* ### Highlighting the active link
* This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.
*
* ### Notes
*
* - You can use `ui-params` to change **only the parameter values** by omitting the state name and supplying only `ui-state-params`.
* However, it might be simpler to use [[uiSref]] parameter-only links.
*
* #### Example:
* Sets the `lang` parameter to `en` and remains on the same state.
*
* ```html
* <a ui-state="" ui-state-params="{ lang: 'en' }">English</a>
* ```
*
* - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.
* ```
*/
var uiState;
uiState = ['$uiRouter', '$timeout',
function $StateRefDynamicDirective($uiRouter, $timeout) {
var $state = $uiRouter.stateService;
return {
restrict: 'A',
require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
link: function (scope, element, attrs, uiSrefActive) {
var type = getTypeInfo(element);
var active = uiSrefActive[1] || uiSrefActive[0];
var unlinkInfoFn = null;
var hookFn;
var rawDef = {};
var getDef = function () { return processedDef($state, element, rawDef); };
var inputAttrs = ['uiState', 'uiStateParams', 'uiStateOpts'];
var watchDeregFns = inputAttrs.reduce(function (acc, attr) { return (acc[attr] = noop, acc); }, {});
function update() {
var def = getDef();
if (unlinkInfoFn)
unlinkInfoFn();
if (active)
unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);
if (def.href != null)
attrs.$set(type.attr, def.href);
}
inputAttrs.forEach(function (field) {
rawDef[field] = attrs[field] ? scope.$eval(attrs[field]) : null;
attrs.$observe(field, function (expr) {
watchDeregFns[field]();
watchDeregFns[field] = scope.$watch(expr, function (newval) {
rawDef[field] = newval;
update();
}, true);
});
});
update();
scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));
scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));
if (!type.clickable)
return;
hookFn = clickHook(element, $state, $timeout, type, getDef);
bindEvents(element, scope, hookFn, rawDef.uiStateOpts);
}
};
}];
/**
* `ui-sref-active` and `ui-sref-active-eq`: A directive that adds a CSS class when a `ui-sref` is active
*
* A directive working alongside [[uiSref]] and [[uiState]] to add classes to an element when the
* related directive's state is active (and remove them when it is inactive).
*
* The primary use-case is to highlight the active link in navigation menus,
* distinguishing it from the inactive menu items.
*
* ### Linking to a `ui-sref` or `ui-state`
* `ui-sref-active` can live on the same element as `ui-sref`/`ui-state`, or it can be on a parent element.
* If a `ui-sref-active` is a parent to more than one `ui-sref`/`ui-state`, it will apply the CSS class when **any of the links are active**.
*
* ### Matching
*
* The `ui-sref-active` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state **or any child state is active**.
* This is a "fuzzy match" which uses [[StateService.includes]].
*
* The `ui-sref-active-eq` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state is directly active (not when child states are active).
* This is an "exact match" which uses [[StateService.is]].
*
* ### Parameter values
* If the `ui-sref`/`ui-state` includes parameter values, the current parameter values must match the link's values for the link to be highlighted.
* This allows a list of links to the same state with different parameters to be rendered, and the correct one highlighted.
*
* #### Example:
* ```html
* <li ng-repeat="user in users" ui-sref-active="active">
* <a ui-sref="user.details({ userId: user.id })">{{ user.lastName }}</a>
* </li>
* ```
*
* ### Examples
*
* Given the following template:
* #### Example:
* ```html
* <ul>
* <li ui-sref-active="active" class="item">
* <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
* </li>
* </ul>
* ```
*
* When the app state is `app.user` (or any child state),
* and contains the state parameter "user" with value "bilbobaggins",
* the resulting HTML will appear as (note the 'active' class):
*
* ```html
* <ul>
* <li ui-sref-active="active" class="item active">
* <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
* </li>
* </ul>
* ```
*
* ### Glob mode
*
* It is possible to pass `ui-sref-active` an expression that evaluates to an object.
* The objects keys represent active class names and values represent the respective state names/globs.
* `ui-sref-active` will match if the current active state **includes** any of
* the specified state names/globs, even the abstract ones.
*
* #### Example:
* Given the following template, with "admin" being an abstract state:
* ```html
* <div ui-sref-active="{'active': 'admin.**'}">
* <a ui-sref-active="active" ui-sref="admin.roles">Roles</a>
* </div>
* ```
*
* When the current state is "admin.roles" the "active" class will be applied to both the <div> and <a> elements.
* It is important to note that the state names/globs passed to `ui-sref-active` override any state provided by a linked `ui-sref`.
*
* ### Notes:
*
* - The class name is interpolated **once** during the directives link time (any further changes to the
* interpolated value are ignored).
*
* - Multiple classes may be specified in a space-separated format: `ui-sref-active='class1 class2 class3'`
*/
var uiSrefActive;
uiSrefActive = ['$state', '$stateParams', '$interpolate', '$uiRouter',
function $StateRefActiveDirective($state, $stateParams, $interpolate, $uiRouter) {
return {
restrict: "A",
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
var states = [], activeEqClass, uiSrefActive;
// There probably isn't much point in $observing this
// uiSrefActive and uiSrefActiveEq share the same directive object with some
// slight difference in logic routing
activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);
try {
uiSrefActive = $scope.$eval($attrs.uiSrefActive);
}
catch (e) {
// Do nothing. uiSrefActive is not a valid expression.
// Fall back to using $interpolate below
}
uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);
if (isObject(uiSrefActive)) {
forEach(uiSrefActive, function (stateOrName, activeClass) {
if (isString(stateOrName)) {
var ref = parseStateRef(stateOrName);
addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);
}
});
}
// Allow uiSref to communicate with uiSrefActive[Equals]
this.$$addStateInfo = function (newState, newParams) {
// we already got an explicit state provided by ui-sref-active, so we
// shadow the one that comes from ui-sref
if (isObject(uiSrefActive) && states.length > 0) {
return;
}
var deregister = addState(newState, newParams, uiSrefActive);
update();
return deregister;
};
function updateAfterTransition(trans) {
trans.promise.then(update, noop);
}
$scope.$on('$stateChangeSuccess', update);
$scope.$on('$destroy', $uiRouter.transitionService.onStart({}, updateAfterTransition));
if ($uiRouter.globals.transition) {
updateAfterTransition($uiRouter.globals.transition);
}
function addState(stateName, stateParams, activeClass) {
var state = $state.get(stateName, stateContext($element));
var stateInfo = {
state: state || { name: stateName },
params: stateParams,
activeClass: activeClass
};
states.push(stateInfo);
return function removeState() {
removeFrom(states)(stateInfo);
};
}
// Update route state
function update() {
var splitClasses = function (str) {
return str.split(/\s/).filter(identity);
};
var getClasses = function (stateList) {
return stateList.map(function (x) { return x.activeClass; }).map(splitClasses).reduce(unnestR, []);
};
var allClasses = getClasses(states).concat(splitClasses(activeEqClass)).reduce(uniqR, []);
var fuzzyClasses = getClasses(states.filter(function (x) { return $state.includes(x.state.name, x.params); }));
var exactlyMatchesAny = !!states.filter(function (x) { return $state.is(x.state.name, x.params); }).length;
var exactClasses = exactlyMatchesAny ? splitClasses(activeEqClass) : [];
var addClasses = fuzzyClasses.concat(exactClasses).reduce(uniqR, []);
var removeClasses = allClasses.filter(function (cls) { return !inArray(addClasses, cls); });
$scope.$evalAsync(function () {
addClasses.forEach(function (className) { return $element.addClass(className); });
removeClasses.forEach(function (className) { return $element.removeClass(className); });
});
}
update();
}]
};
}];
angular.module('ui.router.state')
.directive('uiSref', uiSref)
.directive('uiSrefActive', uiSrefActive)
.directive('uiSrefActiveEq', uiSrefActive)
.directive('uiState', uiState);
//# sourceMappingURL=stateDirectives.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,142 @@
import { ActiveUIView } from "@uirouter/core";
import { Ng1ViewConfig } from "../statebuilders/views";
import { ng1_directive } from "./stateDirectives";
/** @hidden */
export declare type UIViewData = {
$cfg: Ng1ViewConfig;
$uiView: ActiveUIView;
};
/** @hidden */
export declare type UIViewAnimData = {
$animEnter: Promise<any>;
$animLeave: Promise<any>;
$$animLeave: {
resolve: () => any;
};
};
/**
* `ui-view`: A viewport directive which is filled in by a view from the active state.
*
* ### Attributes
*
* - `name`: (Optional) A view name.
* The name should be unique amongst the other views in the same state.
* You can have views of the same name that live in different states.
* The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]).
*
* - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated.
* Uses [[$uiViewScroll]] to do the scrolling.
*
* - `onload`: Expression to evaluate whenever the view updates.
*
* #### Example:
* A view can be unnamed or named.
* ```html
* <!-- Unnamed -->
* <div ui-view></div>
*
* <!-- Named -->
* <div ui-view="viewName"></div>
*
* <!-- Named (different style) -->
* <ui-view name="viewName"></ui-view>
* ```
*
* You can only have one unnamed view within any template (or root html). If you are only using a
* single view and it is unnamed then you can populate it like so:
*
* ```html
* <div ui-view></div>
* $stateProvider.state("home", {
* template: "<h1>HELLO!</h1>"
* })
* ```
*
* The above is a convenient shortcut equivalent to specifying your view explicitly with the
* [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name:
*
* ```js
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* ```
*
* But typically you'll only use the views property if you name your view or have more than one view
* in the same template. There's not really a compelling reason to name a view if its the only one,
* but you could if you wanted, like so:
*
* ```html
* <div ui-view="main"></div>
* ```
*
* ```js
* $stateProvider.state("home", {
* views: {
* "main": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* ```
*
* Really though, you'll use views to set up multiple views:
*
* ```html
* <div ui-view></div>
* <div ui-view="chart"></div>
* <div ui-view="data"></div>
* ```
*
* ```js
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* },
* "chart": {
* template: "<chart_thing/>"
* },
* "data": {
* template: "<data_thing/>"
* }
* }
* })
* ```
*
* #### Examples for `autoscroll`:
* ```html
* <!-- If autoscroll present with no expression,
* then scroll ui-view into view -->
* <ui-view autoscroll/>
*
* <!-- If autoscroll present with valid expression,
* then scroll ui-view into view if expression evaluates to true -->
* <ui-view autoscroll='true'/>
* <ui-view autoscroll='false'/>
* <ui-view autoscroll='scopeVariable'/>
* ```
*
* Resolve data:
*
* The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this
* can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template.
*
* Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the
* controller is instantiated. The `$onInit()` hook can be used to perform initialization code which
* depends on `$resolve` data.
*
* #### Example:
* ```js
* $stateProvider.state('home', {
* template: '<my-component user="$resolve.user"></my-component>',
* resolve: {
* user: function(UserService) { return UserService.fetchUser(); }
* }
* });
* ```
*/
export declare let uiView: ng1_directive;

View file

@ -0,0 +1,414 @@
/**
* @ng1api
* @module directives
*/ /** for typedoc */
import { ng as angular } from "../angular";
import { noop } from "angular";
import { extend, unnestR, filter, tail, isDefined, isFunction, isString, trace, parse, ResolveContext, kebobString } from "@uirouter/core";
import { Ng1ViewConfig } from "../statebuilders/views";
import { getLocals } from "../services";
/**
* `ui-view`: A viewport directive which is filled in by a view from the active state.
*
* ### Attributes
*
* - `name`: (Optional) A view name.
* The name should be unique amongst the other views in the same state.
* You can have views of the same name that live in different states.
* The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]).
*
* - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated.
* Uses [[$uiViewScroll]] to do the scrolling.
*
* - `onload`: Expression to evaluate whenever the view updates.
*
* #### Example:
* A view can be unnamed or named.
* ```html
* <!-- Unnamed -->
* <div ui-view></div>
*
* <!-- Named -->
* <div ui-view="viewName"></div>
*
* <!-- Named (different style) -->
* <ui-view name="viewName"></ui-view>
* ```
*
* You can only have one unnamed view within any template (or root html). If you are only using a
* single view and it is unnamed then you can populate it like so:
*
* ```html
* <div ui-view></div>
* $stateProvider.state("home", {
* template: "<h1>HELLO!</h1>"
* })
* ```
*
* The above is a convenient shortcut equivalent to specifying your view explicitly with the
* [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name:
*
* ```js
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* ```
*
* But typically you'll only use the views property if you name your view or have more than one view
* in the same template. There's not really a compelling reason to name a view if its the only one,
* but you could if you wanted, like so:
*
* ```html
* <div ui-view="main"></div>
* ```
*
* ```js
* $stateProvider.state("home", {
* views: {
* "main": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* ```
*
* Really though, you'll use views to set up multiple views:
*
* ```html
* <div ui-view></div>
* <div ui-view="chart"></div>
* <div ui-view="data"></div>
* ```
*
* ```js
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* },
* "chart": {
* template: "<chart_thing/>"
* },
* "data": {
* template: "<data_thing/>"
* }
* }
* })
* ```
*
* #### Examples for `autoscroll`:
* ```html
* <!-- If autoscroll present with no expression,
* then scroll ui-view into view -->
* <ui-view autoscroll/>
*
* <!-- If autoscroll present with valid expression,
* then scroll ui-view into view if expression evaluates to true -->
* <ui-view autoscroll='true'/>
* <ui-view autoscroll='false'/>
* <ui-view autoscroll='scopeVariable'/>
* ```
*
* Resolve data:
*
* The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this
* can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template.
*
* Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the
* controller is instantiated. The `$onInit()` hook can be used to perform initialization code which
* depends on `$resolve` data.
*
* #### Example:
* ```js
* $stateProvider.state('home', {
* template: '<my-component user="$resolve.user"></my-component>',
* resolve: {
* user: function(UserService) { return UserService.fetchUser(); }
* }
* });
* ```
*/
export var uiView;
uiView = ['$view', '$animate', '$uiViewScroll', '$interpolate', '$q',
function $ViewDirective($view, $animate, $uiViewScroll, $interpolate, $q) {
function getRenderer(attrs, scope) {
return {
enter: function (element, target, cb) {
if (angular.version.minor > 2) {
$animate.enter(element, null, target).then(cb);
}
else {
$animate.enter(element, null, target, cb);
}
},
leave: function (element, cb) {
if (angular.version.minor > 2) {
$animate.leave(element).then(cb);
}
else {
$animate.leave(element, cb);
}
}
};
}
function configsEqual(config1, config2) {
return config1 === config2;
}
var rootData = {
$cfg: { viewDecl: { $context: $view._pluginapi._rootViewContext() } },
$uiView: {}
};
var directive = {
count: 0,
restrict: 'ECA',
terminal: true,
priority: 400,
transclude: 'element',
compile: function (tElement, tAttrs, $transclude) {
return function (scope, $element, attrs) {
var previousEl, currentEl, currentScope, unregister, onloadExp = attrs['onload'] || '', autoScrollExp = attrs['autoscroll'], renderer = getRenderer(attrs, scope), viewConfig = undefined, inherited = $element.inheritedData('$uiView') || rootData, name = $interpolate(attrs['uiView'] || attrs['name'] || '')(scope) || '$default';
var activeUIView = {
$type: 'ng1',
id: directive.count++,
name: name,
fqn: inherited.$uiView.fqn ? inherited.$uiView.fqn + "." + name : name,
config: null,
configUpdated: configUpdatedCallback,
get creationContext() {
var fromParentTagConfig = parse('$cfg.viewDecl.$context')(inherited);
// Allow <ui-view name="foo"><ui-view name="bar"></ui-view></ui-view>
// See https://github.com/angular-ui/ui-router/issues/3355
var fromParentTag = parse('$uiView.creationContext')(inherited);
return fromParentTagConfig || fromParentTag;
}
};
trace.traceUIViewEvent("Linking", activeUIView);
function configUpdatedCallback(config) {
if (config && !(config instanceof Ng1ViewConfig))
return;
if (configsEqual(viewConfig, config))
return;
trace.traceUIViewConfigUpdated(activeUIView, config && config.viewDecl && config.viewDecl.$context);
viewConfig = config;
updateView(config);
}
$element.data('$uiView', { $uiView: activeUIView });
updateView();
unregister = $view.registerUIView(activeUIView);
scope.$on("$destroy", function () {
trace.traceUIViewEvent("Destroying/Unregistering", activeUIView);
unregister();
});
function cleanupLastView() {
if (previousEl) {
trace.traceUIViewEvent("Removing (previous) el", previousEl.data('$uiView'));
previousEl.remove();
previousEl = null;
}
if (currentScope) {
trace.traceUIViewEvent("Destroying scope", activeUIView);
currentScope.$destroy();
currentScope = null;
}
if (currentEl) {
var _viewData_1 = currentEl.data('$uiViewAnim');
trace.traceUIViewEvent("Animate out", _viewData_1);
renderer.leave(currentEl, function () {
_viewData_1.$$animLeave.resolve();
previousEl = null;
});
previousEl = currentEl;
currentEl = null;
}
}
function updateView(config) {
var newScope = scope.$new();
var animEnter = $q.defer(), animLeave = $q.defer();
var $uiViewData = {
$cfg: config,
$uiView: activeUIView,
};
var $uiViewAnim = {
$animEnter: animEnter.promise,
$animLeave: animLeave.promise,
$$animLeave: animLeave
};
/**
* @ngdoc event
* @name ui.router.state.directive:ui-view#$viewContentLoading
* @eventOf ui.router.state.directive:ui-view
* @eventType emits on ui-view directive scope
* @description
*
* Fired once the view **begins loading**, *before* the DOM is rendered.
*
* @param {Object} event Event object.
* @param {string} viewName Name of the view.
*/
newScope.$emit('$viewContentLoading', name);
var cloned = $transclude(newScope, function (clone) {
clone.data('$uiViewAnim', $uiViewAnim);
clone.data('$uiView', $uiViewData);
renderer.enter(clone, $element, function onUIViewEnter() {
animEnter.resolve();
if (currentScope)
currentScope.$emit('$viewContentAnimationEnded');
if (isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
$uiViewScroll(clone);
}
});
cleanupLastView();
});
currentEl = cloned;
currentScope = newScope;
/**
* @ngdoc event
* @name ui.router.state.directive:ui-view#$viewContentLoaded
* @eventOf ui.router.state.directive:ui-view
* @eventType emits on ui-view directive scope
* @description *
* Fired once the view is **loaded**, *after* the DOM is rendered.
*
* @param {Object} event Event object.
*/
currentScope.$emit('$viewContentLoaded', config || viewConfig);
currentScope.$eval(onloadExp);
}
};
}
};
return directive;
}];
$ViewDirectiveFill.$inject = ['$compile', '$controller', '$transitions', '$view', '$q', '$timeout'];
/** @hidden */
function $ViewDirectiveFill($compile, $controller, $transitions, $view, $q, $timeout) {
var getControllerAs = parse('viewDecl.controllerAs');
var getResolveAs = parse('viewDecl.resolveAs');
return {
restrict: 'ECA',
priority: -400,
compile: function (tElement) {
var initial = tElement.html();
tElement.empty();
return function (scope, $element) {
var data = $element.data('$uiView');
if (!data) {
$element.html(initial);
$compile($element.contents())(scope);
return;
}
var cfg = data.$cfg || { viewDecl: {}, getTemplate: noop };
var resolveCtx = cfg.path && new ResolveContext(cfg.path);
$element.html(cfg.getTemplate($element, resolveCtx) || initial);
trace.traceUIViewFill(data.$uiView, $element.html());
var link = $compile($element.contents());
var controller = cfg.controller;
var controllerAs = getControllerAs(cfg);
var resolveAs = getResolveAs(cfg);
var locals = resolveCtx && getLocals(resolveCtx);
scope[resolveAs] = locals;
if (controller) {
var controllerInstance = $controller(controller, extend({}, locals, { $scope: scope, $element: $element }));
if (controllerAs) {
scope[controllerAs] = controllerInstance;
scope[controllerAs][resolveAs] = locals;
}
// TODO: Use $view service as a central point for registering component-level hooks
// Then, when a component is created, tell the $view service, so it can invoke hooks
// $view.componentLoaded(controllerInstance, { $scope: scope, $element: $element });
// scope.$on('$destroy', () => $view.componentUnloaded(controllerInstance, { $scope: scope, $element: $element }));
$element.data('$ngControllerController', controllerInstance);
$element.children().data('$ngControllerController', controllerInstance);
registerControllerCallbacks($q, $transitions, controllerInstance, scope, cfg);
}
// Wait for the component to appear in the DOM
if (isString(cfg.viewDecl.component)) {
var cmp_1 = cfg.viewDecl.component;
var kebobName = kebobString(cmp_1);
var tagRegexp_1 = new RegExp("^(x-|data-)?" + kebobName + "$", "i");
var getComponentController = function () {
var directiveEl = [].slice.call($element[0].children)
.filter(function (el) { return el && el.tagName && tagRegexp_1.exec(el.tagName); });
return directiveEl && angular.element(directiveEl).data("$" + cmp_1 + "Controller");
};
var deregisterWatch_1 = scope.$watch(getComponentController, function (ctrlInstance) {
if (!ctrlInstance)
return;
registerControllerCallbacks($q, $transitions, ctrlInstance, scope, cfg);
deregisterWatch_1();
});
}
link(scope);
};
}
};
}
/** @hidden */
var hasComponentImpl = typeof angular.module('ui.router')['component'] === 'function';
/** @hidden incrementing id */
var _uiCanExitId = 0;
/** @hidden TODO: move these callbacks to $view and/or `/hooks/components.ts` or something */
function registerControllerCallbacks($q, $transitions, controllerInstance, $scope, cfg) {
// Call $onInit() ASAP
if (isFunction(controllerInstance.$onInit) && !(cfg.viewDecl.component && hasComponentImpl)) {
controllerInstance.$onInit();
}
var viewState = tail(cfg.path).state.self;
var hookOptions = { bind: controllerInstance };
// Add component-level hook for onParamsChange
if (isFunction(controllerInstance.uiOnParamsChanged)) {
var resolveContext = new ResolveContext(cfg.path);
var viewCreationTrans_1 = resolveContext.getResolvable('$transition$').data;
// Fire callback on any successful transition
var paramsUpdated = function ($transition$) {
// Exit early if the $transition$ is the same as the view was created within.
// Exit early if the $transition$ will exit the state the view is for.
if ($transition$ === viewCreationTrans_1 || $transition$.exiting().indexOf(viewState) !== -1)
return;
var toParams = $transition$.params("to");
var fromParams = $transition$.params("from");
var toSchema = $transition$.treeChanges().to.map(function (node) { return node.paramSchema; }).reduce(unnestR, []);
var fromSchema = $transition$.treeChanges().from.map(function (node) { return node.paramSchema; }).reduce(unnestR, []);
// Find the to params that have different values than the from params
var changedToParams = toSchema.filter(function (param) {
var idx = fromSchema.indexOf(param);
return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]);
});
// Only trigger callback if a to param has changed or is new
if (changedToParams.length) {
var changedKeys_1 = changedToParams.map(function (x) { return x.id; });
// Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params.
var newValues = filter(toParams, function (val, key) { return changedKeys_1.indexOf(key) !== -1; });
controllerInstance.uiOnParamsChanged(newValues, $transition$);
}
};
$scope.$on('$destroy', $transitions.onSuccess({}, paramsUpdated, hookOptions));
}
// Add component-level hook for uiCanExit
if (isFunction(controllerInstance.uiCanExit)) {
var id_1 = _uiCanExitId++;
var cacheProp_1 = '_uiCanExitIds';
// Returns true if a redirect transition already answered truthy
var prevTruthyAnswer_1 = function (trans) {
return !!trans && (trans[cacheProp_1] && trans[cacheProp_1][id_1] === true || prevTruthyAnswer_1(trans.redirectedFrom()));
};
// If a user answered yes, but the transition was later redirected, don't also ask for the new redirect transition
var wrappedHook = function (trans) {
var promise, ids = trans[cacheProp_1] = trans[cacheProp_1] || {};
if (!prevTruthyAnswer_1(trans)) {
promise = $q.when(controllerInstance.uiCanExit(trans));
promise.then(function (val) { return ids[id_1] = (val !== false); });
}
return promise;
};
var criteria = { exiting: viewState.name };
$scope.$on('$destroy', $transitions.onBefore(criteria, wrappedHook, hookOptions));
}
}
angular.module('ui.router.state').directive('uiView', uiView);
angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
//# sourceMappingURL=viewDirective.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,19 @@
/**
* Main entry point for angular 1.x build
* @module ng1
*/ /** */
export * from "./interface";
export * from "./services";
export * from "./statebuilders/views";
export * from "./stateProvider";
export * from "./urlRouterProvider";
import "./injectables";
import "./directives/stateDirectives";
import "./stateFilters";
import "./directives/viewDirective";
import "./viewScroll";
declare const _default: "ui.router";
export default _default;
import * as core from "@uirouter/core";
export { core };
export * from "@uirouter/core";

View file

@ -0,0 +1,18 @@
/**
* Main entry point for angular 1.x build
* @module ng1
*/ /** */
export * from "./services";
export * from "./statebuilders/views";
export * from "./stateProvider";
export * from "./urlRouterProvider";
import "./injectables";
import "./directives/stateDirectives";
import "./stateFilters";
import "./directives/viewDirective";
import "./viewScroll";
export default "ui.router";
import * as core from "@uirouter/core";
export { core };
export * from "@uirouter/core";
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "index.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/index.ts"
],
"names": [],
"mappings": "AAAA;;;GAGG,CAAC,MAAM;AAGV,cAAc,YAAY,CAAC;AAC3B,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AAEpC,OAAO,eAAe,CAAC;AACvB,OAAO,8BAA8B,CAAC;AACtC,OAAO,gBAAgB,CAAC;AACxB,OAAO,4BAA4B,CAAC;AACpC,OAAO,cAAc,CAAC;AAEtB,eAAe,WAAW,CAAC;AAE3B,OAAO,KAAK,IAAI,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,IAAI,EAAE,CAAC;AAChB,cAAc,gBAAgB,CAAC",
"sourcesContent": [
"/**\n * Main entry point for angular 1.x build\n * @module ng1\n */ /** */\n\nexport * from \"./interface\";\nexport * from \"./services\";\nexport * from \"./statebuilders/views\";\nexport * from \"./stateProvider\";\nexport * from \"./urlRouterProvider\";\n\nimport \"./injectables\";\nimport \"./directives/stateDirectives\";\nimport \"./stateFilters\";\nimport \"./directives/viewDirective\";\nimport \"./viewScroll\";\n\nexport default \"ui.router\";\n\nimport * as core from \"@uirouter/core\";\nexport { core };\nexport * from \"@uirouter/core\";\n\n"
]
}

View file

@ -0,0 +1,366 @@
/**
* # Angular 1 injectable services
*
* This is a list of the objects which can be injected using angular's injector.
*
* There are three different kind of injectable objects:
*
* ## **Provider** objects
* #### injectable into a `.config()` block during configtime
*
* - [[$uiRouterProvider]]: The UI-Router instance
* - [[$stateProvider]]: State registration
* - [[$transitionsProvider]]: Transition hooks
* - [[$urlServiceProvider]]: All URL related public APIs
*
* - [[$uiViewScrollProvider]]: Disable ui-router view scrolling
* - [[$urlRouterProvider]]: (deprecated) Url matching rules
* - [[$urlMatcherFactoryProvider]]: (deprecated) Url parsing config
*
* ## **Service** objects
* #### injectable globally during runtime
*
* - [[$uiRouter]]: The UI-Router instance
* - [[$trace]]: Enable transition trace/debug
* - [[$transitions]]: Transition hooks
* - [[$state]]: Imperative state related APIs
* - [[$stateRegistry]]: State registration
* - [[$urlService]]: All URL related public APIs
* - [[$uiRouterGlobals]]: Global variables
* - [[$uiViewScroll]]: Scroll an element into view
*
* - [[$stateParams]]: (deprecated) Global state param values
* - [[$urlRouter]]: (deprecated) URL synchronization
* - [[$urlMatcherFactory]]: (deprecated) URL parsing config
*
* ## **Per-Transition** objects
*
* - These kind of objects are injectable into:
* - Resolves ([[Ng1StateDeclaration.resolve]]),
* - Transition Hooks ([[TransitionService.onStart]], etc),
* - Routed Controllers ([[Ng1ViewDeclaration.controller]])
*
* #### Different instances are injected based on the [[Transition]]
*
* - [[$transition$]]: The current Transition object
* - [[$stateParams]]: State param values for pending Transition (deprecated)
* - Any resolve data defined using [[Ng1StateDeclaration.resolve]]
*
* @ng1api
* @preferred
* @module injectables
*/ /** */
/**
* The current (or pending) State Parameters
*
* An injectable global **Service Object** which holds the state parameters for the latest **SUCCESSFUL** transition.
*
* The values are not updated until *after* a `Transition` successfully completes.
*
* **Also:** an injectable **Per-Transition Object** object which holds the pending state parameters for the pending `Transition` currently running.
*
* ### Deprecation warning:
*
* The value injected for `$stateParams` is different depending on where it is injected.
*
* - When injected into an angular service, the object injected is the global **Service Object** with the parameter values for the latest successful `Transition`.
* - When injected into transition hooks, resolves, or view controllers, the object is the **Per-Transition Object** with the parameter values for the running `Transition`.
*
* Because of these confusing details, this service is deprecated.
*
* ### Instead of using the global `$stateParams` service object,
* inject [[$uiRouterGlobals]] and use [[UIRouterGlobals.params]]
*
* ```js
* MyService.$inject = ['$uiRouterGlobals'];
* function MyService($uiRouterGlobals) {
* return {
* paramValues: function () {
* return $uiRouterGlobals.params;
* }
* }
* }
* ```
*
* ### Instead of using the per-transition `$stateParams` object,
* inject the current `Transition` (as [[$transition$]]) and use [[Transition.params]]
*
* ```js
* MyController.$inject = ['$transition$'];
* function MyController($transition$) {
* var username = $transition$.params().username;
* // .. do something with username
* }
* ```
*
* ---
*
* This object can be injected into other services.
*
* #### Deprecated Example:
* ```js
* SomeService.$inject = ['$http', '$stateParams'];
* function SomeService($http, $stateParams) {
* return {
* getUser: function() {
* return $http.get('/api/users/' + $stateParams.username);
* }
* }
* };
* angular.service('SomeService', SomeService);
* ```
* @deprecated
*/
var $stateParams;
/**
* Global UI-Router variables
*
* The router global state as a **Service Object** (injectable during runtime).
*
* This object contains globals such as the current state and current parameter values.
*/
var $uiRouterGlobals;
/**
* The UI-Router instance
*
* The [[UIRouter]] singleton (the router instance) as a **Service Object** (injectable during runtime).
*
* This object is the UI-Router singleton instance, created by angular dependency injection during application bootstrap.
* It has references to the other UI-Router services
*
* #### Note: This object is also exposed as [[$uiRouterProvider]] for injection during angular config time.
*/
var $uiRouter;
/**
* The UI-Router instance
*
* The [[UIRouter]] singleton (the router instance) as a **Provider Object** (injectable during config phase).
*
* This object is the UI-Router singleton instance, created by angular dependency injection during application bootstrap.
* It has references to the other UI-Router services
*
* #### Note: This object is also exposed as [[$uiRouter]] for injection during runtime.
*/
var $uiRouterProvider;
/**
* Transition debug/tracing
*
* The [[Trace]] singleton as a **Service Object** (injectable during runtime).
*
* Enables or disables Transition tracing which can help to debug issues.
*/
var $trace;
/**
* The Transition Service
*
* The [[TransitionService]] singleton as a **Service Object** (injectable during runtime).
*
* This angular service exposes the [[TransitionService]] singleton, which is primarily
* used to register global transition hooks.
*
* #### Note: This object is also exposed as [[$transitionsProvider]] for injection during the config phase.
*/
var $transitions;
/**
* The Transition Service
*
* The [[TransitionService]] singleton as a **Provider Object** (injectable during config phase)
*
* This angular service exposes the [[TransitionService]] singleton, which is primarily
* used to register global transition hooks.
*
* #### Note: This object is also exposed as [[$transitions]] for injection during runtime.
*/
var $transitionsProvider;
/**
* The current [[Transition]] object
*
* The current [[Transition]] object as a **Per-Transition Object** (injectable into Resolve, Hooks, Controllers)
*
* This object returns information about the current transition, including:
*
* - To/from states
* - To/from parameters
* - Transition options
* - States being entered, exited, and retained
* - Resolve data
* - A Promise for the transition
* - Any transition failure information
* - An injector for both Service and Per-Transition Objects
*/
var $transition$;
/**
* The State Service
*
* The [[StateService]] singleton as a **Service Object** (injectable during runtime).
*
* This service used to manage and query information on registered states.
* It exposes state related APIs including:
*
* - Start a [[Transition]]
* - Imperatively lazy load states
* - Check if a state is currently active
* - Look up states by name
* - Build URLs for a state+parameters
* - Configure the global Transition error handler
*
* This angular service exposes the [[StateService]] singleton.
*/
var $state;
/**
* The State Registry
*
* The [[StateRegistry]] singleton as a **Service Object** (injectable during runtime).
*
* This service is used to register/deregister states.
* It has state registration related APIs including:
*
* - Register/deregister states
* - Listen for state registration/deregistration
* - Get states by name
* - Add state decorators (to customize the state creation process)
*
* #### Note: This object is also exposed as [[$stateRegistryProvider]] for injection during the config phase.
*/
var $stateRegistry;
/**
* The State Registry
*
* The [[StateRegistry]] singleton as a **Provider Object** (injectable during config time).
*
* This service is used to register/deregister states.
* It has state registration related APIs including:
*
* - Register/deregister states
* - Listen for state registration/deregistration
* - Get states by name
* - Add state decorators (to customize the state creation process)
*
* #### Note: This object is also exposed as [[$stateRegistry]] for injection during runtime.
*/
var $stateRegistryProvider;
/**
* The View Scroll provider
*
* The [[UIViewScrollProvider]] as a **Provider Object** (injectable during config time).
*
* This angular service exposes the [[UIViewScrollProvider]] singleton and is
* used to disable UI-Router's scroll behavior.
*/
var $uiViewScrollProvider;
/**
* The View Scroll function
*
* The View Scroll function as a **Service Object** (injectable during runtime).
*
* This is a function that scrolls an element into view.
* The element is scrolled after a `$timeout` so the DOM has time to refresh.
*
* If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
* this can be enabled by calling [[UIViewScrollProvider.useAnchorScroll]].
*
* Note: this function is used by the [[directives.uiView]] when the `autoscroll` expression evaluates to true.
*/
var $uiViewScroll;
/**
* The StateProvider
*
* An angular1-only [[StateProvider]] as a **Provider Object** (injectable during config time).
*
* This angular service exposes the [[StateProvider]] singleton.
*
* The `StateProvider` is primarily used to register states or add custom state decorators.
*
* ##### Note: This provider is a ng1 vestige.
* It is a passthrough to [[$stateRegistry]] and [[$state]].
*/
var $stateProvider;
/**
* The URL Service Provider
*
* The [[UrlService]] singleton as a **Provider Object** (injectable during the angular config phase).
*
* A service used to configure and interact with the URL.
* It has URL related APIs including:
*
* - register custom Parameter types `UrlService.config.type` ([[UrlConfigApi.type]])
* - add URL rules: `UrlService.rules.when` ([[UrlRulesApi.when]])
* - configure behavior when no url matches: `UrlService.rules.otherwise` ([[UrlRulesApi.otherwise]])
* - delay initial URL synchronization [[UrlService.deferIntercept]].
* - get or set the current url: [[UrlService.url]]
*
* ##### Note: This service can also be injected during runtime as [[$urlService]].
*/
var $urlServiceProvider;
/**
* The URL Service
*
* The [[UrlService]] singleton as a **Service Object** (injectable during runtime).
*
* Note: This service can also be injected during the config phase as [[$urlServiceProvider]].
*
* Used to configure the URL.
* It has URL related APIs including:
*
* - register custom Parameter types `UrlService.config.type` ([[UrlConfigApi.type]])
* - add URL rules: `UrlService.rules.when` ([[UrlRulesApi.when]])
* - configure behavior when no url matches: `UrlService.rules.otherwise` ([[UrlRulesApi.otherwise]])
* - delay initial URL synchronization [[UrlService.deferIntercept]].
* - get or set the current url: [[UrlService.url]]
*
* ##### Note: This service can also be injected during the config phase as [[$urlServiceProvider]].
*/
var $urlService;
/**
* The URL Router Provider
*
* ### Deprecation warning: This object is now considered internal. Use [[$urlServiceProvider]] instead.
*
* The [[UrlRouter]] singleton as a **Provider Object** (injectable during config time).
*
* #### Note: This object is also exposed as [[$urlRouter]] for injection during runtime.
*
* @deprecated
*/
var $urlRouterProvider;
/**
* The Url Router
*
* ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.
*
* The [[UrlRouter]] singleton as a **Service Object** (injectable during runtime).
*
* #### Note: This object is also exposed as [[$urlRouterProvider]] for injection during angular config time.
*
* @deprecated
*/
var $urlRouter;
/**
* The URL Matcher Factory
*
* ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.
*
* The [[UrlMatcherFactory]] singleton as a **Service Object** (injectable during runtime).
*
* This service is used to set url mapping options, define custom parameter types, and create [[UrlMatcher]] objects.
*
* #### Note: This object is also exposed as [[$urlMatcherFactoryProvider]] for injection during angular config time.
*
* @deprecated
*/
var $urlMatcherFactory;
/**
* The URL Matcher Factory
*
* ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.
*
* The [[UrlMatcherFactory]] singleton as a **Provider Object** (injectable during config time).
*
* This service is used to set url mapping options, define custom parameter types, and create [[UrlMatcher]] objects.
*
* #### Note: This object is also exposed as [[$urlMatcherFactory]] for injection during runtime.
*
* @deprecated
*/
var $urlMatcherFactoryProvider;
//# sourceMappingURL=injectables.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,730 @@
/**
* @ng1api
* @module ng1
*/ /** */
import { StateDeclaration, _ViewDeclaration, IInjectable, Transition, HookResult } from "@uirouter/core";
/**
* The signature for Angular 1 State Transition Hooks.
*
* State hooks are registered as onEnter/onRetain/onExit in state declarations.
* State hooks can additionally be injected with $transition$ and $state$ for
* the current [[Transition]] and [[StateObject]] in the transition.
*
* Transition State Hooks are callback functions that hook into the lifecycle events of specific states during a transition.
* As a transition runs, it may exit some states, retain (keep) states, and enter states.
* As each lifecycle event occurs, the hooks which are registered for the event and that state are called (in priority order).
*
* #### See also:
*
* - [[IHookRegistry.onExit]]
* - [[IHookRegistry.onRetain]]
* - [[IHookRegistry.onEnter]]
*
* #### Example:
* ```js
* onEnter: function() { console.log('Entering'); }
* ```
*
* Not minification-safe
* ```js
* onRetain: function($state$) { console.log('Retained ' + $state$.name); }
* ```
*
* Annotated for minification-safety
* ```js
* onExit: [ '$transition$', '$state', function($transition$, $state) {
* // always redirect to 'foo' state when being exited
* if ($transition$.to().name !== 'foo') {
* return $state.target('foo');
* }
* } ]
* ```
*
* @returns an optional [[HookResult]] which may alter the transition
*/
export interface Ng1StateTransitionHook {
(...injectables: any[]): HookResult;
}
/**
* @internalapi
* an intermediate interface.
*
* Used to reset [[StateDeclaration]] typings to `any` so the [[Ng1StateDeclaration]] interface can then narrow them */
export interface _Ng1StateDeclaration extends StateDeclaration {
onExit?: any;
onRetain?: any;
onEnter?: any;
views?: any;
}
/**
* The StateDeclaration object is used to define a state or nested state.
* It should be registered with the [[StateRegistry]].
*
* #### Example:
* ```js
* // StateDeclaration object
* var foldersState = {
* name: 'folders',
* url: '/folders',
* resolve: {
* allfolders: function(FolderService) {
* return FolderService.list();
* }
* },
* template: "<ul><li ng-repeat='folder in allfolders'>{{folder.name}}</li></ul>",
* controller: function(allfolders, $scope) {
* $scope.allfolders = allfolders;
* }
* }
* ```
*
* Since this interface extends [[Ng1ViewDeclaration]], any view declaration properties can be set directly
* on the state declaration and they will be applied to the view with the name `$default`. For example:
*
* ```js
* var state = {
* name: 'foo',
* url: '/foo',
* template: '<h1>foo</h1>',
* controller: 'FooController'
* }
* ```
*
* is simply syntactic sugar for:
*
* ```js
* var state = {
* name: 'foo',
* url: '/foo',
* views: {
* $default: {
* template: '<h1>foo</h1>',
* controller: 'FooController
* }
* }
* }
* ```
*
* If a state definition contains a `views:` object, any view properties set directly on the state are ignored.
* Thus, this is an invalid state defintion:
*
* ```js
* var state = {
* name: 'foo',
* url: '/foo',
* controller: 'FooController, // invalid because views: exists
* views: {
* header: {
* template: '<h1>header</h1>'
* }
* }
* }
* ```
*/
export interface Ng1StateDeclaration extends _Ng1StateDeclaration, Ng1ViewDeclaration {
/**
* An optional object which defines multiple named views.
*
* Each key is the name of a view, and each value is a [[Ng1ViewDeclaration]].
* Unnamed views are internally renamed to `$default`.
*
* A view's name is used to match an active `<ui-view>` directive in the DOM. When the state
* is entered, the state's views are activated and matched with active `<ui-view>` directives:
*
* - The view's name is processed into a ui-view target:
* - ui-view address: an address to a ui-view
* - state anchor: the state to anchor the address to
*
* Examples:
*
* Targets three named ui-views in the parent state's template
*
* #### Example:
* ```js
* views: {
* header: {
* controller: "headerCtrl",
* templateUrl: "header.html"
* },
* body: {
* controller: "bodyCtrl",
* templateUrl: "body.html"
* },
* footer: "footerComponent"
* }
* ```
*
* #### Example:
* ```js
* // Targets named ui-view="header" in the template of the ancestor state 'top'
* // and the named `ui-view="body" from the parent state's template.
* views: {
* 'header@top': {
* controller: "msgHeaderCtrl",
* templateUrl: "msgHeader.html"
* },
* 'body': {
* controller: "messagesCtrl",
* templateUrl: "messages.html"
* }
* }
* ```
*
* ## View targeting details
*
* There are a few styles of view addressing/targeting.
* The most common is a simple `ui-view` name
*
* #### Simple ui-view name
*
* Addresses without an `@` are anchored to the parent state.
*
* #### Example:
* ```js
* // target the `<div ui-view='foo'></div>` created in the parent state's view
* views: {
* foo: {...}
* }
* ```
*
* #### View name anchored to a state
*
* You can anchor the `ui-view` name to a specific state by including an `@`
*
* #### Example:
* targets the `<div ui-view='foo'></div>` which was created in a view owned by the state `bar.baz`
* ```js
* views: {
* 'foo@bar.baz': {...}
* }
* ```
*
* #### Absolute addressing
*
* You can address a `ui-view` absolutely, using dotted notation, by prefixing the address with a `!`.
* Dotted addresses traverse the hierarchy of `ui-view`s active in the DOM:
*
* #### Example:
* absolutely targets the `<div ui-view='nested'></div>`
* ... which was created in the unnamed/$default root `<ui-view></ui-view>`
* ```js
* views: {
* '!$default.nested': {...}
* }
* ```
*
* #### Relative addressing
*
* Absolute addressing is actually relative addressing, anchored to the unnamed root state (`""`).
* You can also use relative addressing anchored to *any state*, in order to target a target deeply nested `ui-views`:
* The `ui-view` is targeted relative to the anchored state by traversing the nested `ui-view` names.
*
* #### Example:
* targets the `<div ui-view='bar'></div>`
* ... which was created inside the
* `<div ui-view='foo'></div>`
* ... which was created inside the parent state's template.
* ```js
* views: {
* 'foo.bar': {...}
* }
* ```
*
* #### Example:
* targets the `<div ui-view='bar'></div>`
* ... which was created in `<div ui-view='foo'></div>`
* ... which was created in a template from the state `baz.qux`
* ```js
* views: {
* 'foo.bar@baz.qux': {...}
* }
* ```
*
* #### Example:
* a view can relatively target a named `ui-view` defined on an ancestor using `^` (meaning "parent")
* ```js
* views: {
* 'foo@^': {...}, // foo@(parent state) (same as simply 'foo')
* 'bar@^.^': {...}, // bar@(grandparent state)
* 'baz@^.^.^': {...}, // baz@(great-grandparent state)
* }
* ```
*
* For additional in-depth details about how `ui-view` addressing works, see the internal api [[ViewService.match]].
*
* ---
*
* ## State template+controller and `views:` incompatiblity
*
* If a state has a `views` object, any state-level view properties ([[Ng1ViewDeclaration]]) are ignored. Therefore,
* if _any view_ for a state is declared in the `views` object, then _all of the state's views_ must be defined in
* the `views` object. The state declaration must not have any of the following fields:
* - component
* - bindings
* - resolveAs
* - template
* - templateUrl
* - templateProvider
* - controller
* - controllerAs
* - controllerProvider
*/
views?: {
[key: string]: string | Ng1ViewDeclaration;
};
/**
* A state hook invoked when a state is being entered.
*
* The hook can inject global services.
* It can also inject `$transition$` or `$state$` (from the current transition).
*
* ### Example:
* ```js
* $stateProvider.state({
* name: 'mystate',
* onEnter: (MyService, $transition$, $state$) => {
* return MyService.doSomething($state$.name, $transition$.params());
* }
* });
* ```
*
* #### Example:`
* ```js
* $stateProvider.state({
* name: 'mystate',
* onEnter: [ 'MyService', '$transition$', '$state$', function (MyService, $transition$, $state$) {
* return MyService.doSomething($state$.name, $transition$.params());
* } ]
* });
* ```
*/
onEnter?: Ng1StateTransitionHook | IInjectable;
/**
* A state hook invoked when a state is being exited.
*
* The hook can inject global services.
* It can also inject `$transition$` or `$state$` (from the current transition).
*
* ### Example:
* ```js
* $stateProvider.state({
* name: 'mystate',
* onExit: (MyService, $transition$, $state$) => {
* return MyService.doSomething($state$.name, $transition$.params());
* }
* });
* ```
*
* #### Example:`
* ```js
* $stateProvider.state({
* name: 'mystate',
* onExit: [ 'MyService', '$transition$', '$state$', function (MyService, $transition$, $state$) {
* return MyService.doSomething($state$.name, $transition$.params());
* } ]
* });
* ```
*/
onExit?: Ng1StateTransitionHook | IInjectable;
/**
* A state hook invoked when a state is being retained.
*
* The hook can inject global services.
* It can also inject `$transition$` or `$state$` (from the current transition).
*
* #### Example:
* ```js
* $stateProvider.state({
* name: 'mystate',
* onRetain: (MyService, $transition$, $state$) => {
* return MyService.doSomething($state$.name, $transition$.params());
* }
* });
* ```
*
* #### Example:`
* ```js
* $stateProvider.state({
* name: 'mystate',
* onRetain: [ 'MyService', '$transition$', '$state$', function (MyService, $transition$, $state$) {
* return MyService.doSomething($state$.name, $transition$.params());
* } ]
* });
* ```
*/
onRetain?: Ng1StateTransitionHook | IInjectable;
/**
* Makes all search/query parameters `dynamic`
*
* ### Deprecation warning: use [[ParamDeclaration.dynamic]] instead
*
* @deprecated
*/
reloadOnSearch?: boolean;
}
export interface Ng1ViewDeclaration extends _ViewDeclaration {
/**
* The name of the component to use for this view.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* The name of an [angular 1.5+ `.component()`](https://docs.angularjs.org/guide/component) (or directive with
* bindToController and/or scope declaration) which will be used for this view.
*
* Resolve data can be provided to the component via the component's `bindings` object (for 1.3+ directives, the
* `bindToController` is used; for other directives, the `scope` declaration is used). For each binding declared
* on the component, any resolve with the same name is set on the component's controller instance. The binding
* is provided to the component as a one-time-binding. In general, components should likewise declare their
* input bindings as [one-way ("&lt;")](https://docs.angularjs.org/api/ng/service/$compile#-scope-).
*
* Note: inside a "views:" block, a bare string `"foo"` is shorthand for `{ component: "foo" }`
*
* Note: Mapping from resolve names to component inputs may be specified using [[bindings]].
*
* #### Example:
* ```js
* .state('profile', {
* // Use the <my-profile></my-profile> component for the Unnamed view
* component: 'MyProfile',
* }
*
* .state('messages', {
* // use the <nav-bar></nav-bar> component for the view named 'header'
* // use the <message-list></message-list> component for the view named 'content'
* views: {
* header: { component: 'NavBar' },
* content: { component: 'MessageList' }
* }
* }
*
* .state('contacts', {
* // Inside a "views:" block, a bare string "NavBar" is shorthand for { component: "NavBar" }
* // use the <nav-bar></nav-bar> component for the view named 'header'
* // use the <contact-list></contact-list> component for the view named 'content'
* views: {
* header: 'NavBar',
* content: 'ContactList'
* }
* }
* ```
*
*
* Note: When using `component` to define a view, you may _not_ use any of: `template`, `templateUrl`,
* `templateProvider`, `controller`, `controllerProvider`, `controllerAs`.
*
*
* See also: Todd Motto's angular 1.3 and 1.4 [backport of .component()](https://github.com/toddmotto/angular-component)
*/
component?: string;
/**
* An object which maps `resolve`s to [[component]] `bindings`.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* When using a [[component]] declaration (`component: 'myComponent'`), each input binding for the component is supplied
* data from a resolve of the same name, by default. You may supply data from a different resolve name by mapping it here.
*
* Each key in this object is the name of one of the component's input bindings.
* Each value is the name of the resolve that should be provided to that binding.
*
* Any component bindings that are omitted from this map get the default behavior of mapping to a resolve of the
* same name.
*
* #### Example:
* ```js
* $stateProvider.state('foo', {
* resolve: {
* foo: function(FooService) { return FooService.get(); },
* bar: function(BarService) { return BarService.get(); }
* },
* component: 'Baz',
* // The component's `baz` binding gets data from the `bar` resolve
* // The component's `foo` binding gets data from the `foo` resolve (default behavior)
* bindings: {
* baz: 'bar'
* }
* });
*
* app.component('Baz', {
* templateUrl: 'baz.html',
* controller: 'BazController',
* bindings: {
* foo: '<', // foo binding
* baz: '<' // baz binding
* }
* });
* ```
*
*/
bindings?: {
[key: string]: string;
};
/**
* Dynamic component provider function.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* This is an injectable provider function which returns the name of the component to use.
* The provider will invoked during a Transition in which the view's state is entered.
* The provider is called after the resolve data is fetched.
*
* #### Example:
* ```js
* componentProvider: function(MyResolveData, $transition$) {
* if (MyResolveData.foo) {
* return "fooComponent"
* } else if ($transition$.to().name === 'bar') {
* return "barComponent";
* }
* }
* ```
*/
componentProvider?: IInjectable;
/**
* The view's controller function or name
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* The controller function, or the name of a registered controller. The controller function will be used
* to control the contents of the [[directives.uiView]] directive.
*
* If specified as a string, controllerAs can be declared here, i.e., "FooController as foo" instead of in
* a separate [[controllerAs]] property.
*
* See: [[Ng1Controller]] for information about component-level router hooks.
*/
controller?: (IInjectable | string);
/**
* A controller alias name.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* If present, the controller will be published to scope under the `controllerAs` name.
* See: https://docs.angularjs.org/api/ng/directive/ngController
*/
controllerAs?: string;
/**
* Dynamic controller provider function.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* This is an injectable provider function which returns the actual controller function, or the name
* of a registered controller. The provider will invoked during a Transition in which the view's state is
* entered. The provider is called after the resolve data is fetched.
*
* #### Example:
* ```js
* controllerProvider: function(MyResolveData, $transition$) {
* if (MyResolveData.foo) {
* return "FooCtrl"
* } else if ($transition$.to().name === 'bar') {
* return "BarCtrl";
* } else {
* return function($scope) {
* $scope.baz = "Qux";
* }
* }
* }
* ```
*/
controllerProvider?: IInjectable;
/**
* The scope variable name to use for resolve data.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* When a view is activated, the resolved data for the state which the view belongs to is put on the scope.
* This property sets the name of the scope variable to use for the resolved data.
*
* Defaults to `$resolve`.
*/
resolveAs?: string;
/**
* The HTML template for the view.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* HTML template as a string, or a function which returns an html template as a string.
* This template will be used to render the corresponding [[directives.uiView]] directive.
*
* This property takes precedence over templateUrl.
*
* If `template` is a function, it will be called with the Transition parameters as the first argument.
*
* #### Example:
* ```js
* template: "<h1>inline template definition</h1><div ui-view></div>"
* ```
*
* #### Example:
* ```js
* template: function(params) {
* return "<h1>generated template</h1>";
* }
* ```
*/
template?: (Function | string);
/**
* The URL for the HTML template for the view.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* A path or a function that returns a path to an html template.
* The template will be fetched and used to render the corresponding [[directives.uiView]] directive.
*
* If `templateUrl` is a function, it will be called with the Transition parameters as the first argument.
*
* #### Example:
* ```js
* templateUrl: "/templates/home.html"
* ```
*
* #### Example:
* ```js
* templateUrl: function(params) {
* return myTemplates[params.pageId];
* }
* ```
*/
templateUrl?: (string | Function);
/**
* Injected function which returns the HTML template.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* Injected function which returns the HTML template.
* The template will be used to render the corresponding [[directives.uiView]] directive.
*
* #### Example:
* ```js
* templateProvider: function(MyTemplateService, $transition$) {
* return MyTemplateService.getTemplate($transition$.params().pageId);
* }
* ```
*/
templateProvider?: IInjectable;
}
/**
* The shape of a controller for a view (and/or component), defining the controller callbacks.
*
* A view in UI-Router is comprised of either a `component` ([[Ng1ViewDeclaration.component]]) or a combination of a
* `template` (or `templateProvider`) and a `controller` (or `controllerProvider`).
*
* The `controller` object (or the `component`'s controller object) can define component-level controller callbacks,
* which UI-Router will call at the appropriate times. These callbacks are similar to Transition Hooks
* ([[IHookRegistry]]), but are only called if the view is currently active.
*
* This interface defines the UI-Router component callbacks.
*
*/
export interface Ng1Controller {
/** @hidden */
$onInit(): void;
/**
* This callback is called when parameter values have changed.
*
* This callback can be used to respond to changing parameter values in the current state, or in parent/child states.
* This callback is especially handy when using dynamic parameters ([[ParamDeclaration.dynamic]])
*
* Called when:
* - The view is still active
* - A new transition has completed successfully
* - The state for the view (controller) was not reloaded
* - At least one parameter value was changed
*
* Called with:
* @param newValues an object containing the changed parameter values
* @param $transition$ the new Transition which triggered this callback
*
* #### Example:
* ```js
* angular.module('foo').controller('FancyCtrl', function() {
* this.uiOnParamsChanged = function(newParams) {
* console.log("new params: ", newParams);
* }
* });
* ```
*/
uiOnParamsChanged(newValues: any, $transition$: Transition): void;
/**
* This callback is called when the view's state is about to be exited.
*
* This callback is used to inform a view that it is about to be exited, due to a new [[Transition]].
* The callback can ask for user confirmation, and cancel or alter the new Transition. The callback should
* return a value, or a promise for a value. If a promise is returned, the new Transition waits until the
* promise settles.
*
*
* Called when:
* - The view is still active
* - A new Transition is about to run
* - The new Transition will exit the view's state
*
* Called with:
* - The new Transition
*
* Relevant return Values:
* - `false`: The transition is cancelled.
* - A rejected promise: The transition is cancelled.
* - [[TargetState]]: The transition is redirected to the new target state.
* - Anything else: the transition will continue normally (the state and view will be deactivated)
*
* #### Example:
* ```js
* app.component('myComponent', {
* template: '<input ng-model="$ctrl.data" type="text">',
* bindings: { 'data': '<' },
* controller: function() {
*
* this.originalData = angular.copy(this.data);
*
* this.uiCanExit = function() {
* if (!angular.equals(this.data, this.originalData)) {
* // Note: This could also return a Promise and request async
* // confirmation using something like ui-bootstrap $modal
* return window.confirm("Data has changed. Exit anyway and lose changes?");
* }
* }
* }
* }
* ```
*
* @param transition the new Transition that is about to exit the component's state
* @return a HookResult, or a promise for a HookResult
*/
uiCanExit(transition: Transition): HookResult;
}
/**
* Manages which template-loading mechanism to use.
*
* Defaults to `$templateRequest` on Angular versions starting from 1.3, `$http` otherwise.
*/
export interface TemplateFactoryProvider {
/**
* Forces $templateFactory to use $http instead of $templateRequest.
*
* UI-Router uses `$templateRequest` by default on angular 1.3+.
* Use this method to choose to use `$http` instead.
*
* ---
*
* ## Security warning
*
* This might cause XSS, as $http doesn't enforce the regular security checks for
* templates that have been introduced in Angular 1.3.
*
* See the $sce documentation, section
* <a href="https://docs.angularjs.org/api/ng/service/$sce#impact-on-loading-templates">
* Impact on loading templates</a> for more details about this mechanism.
*
* *Note: forcing this to `false` on Angular 1.2.x will crash, because `$templateRequest` is not implemented.*
*
* @param useUnsafeHttpService `true` to use `$http` to fetch templates
*/
useHttpService(useUnsafeHttpService: boolean): any;
}
declare module "@uirouter/core/lib/state/stateRegistry" {
interface StateRegistry {
register(state: Ng1StateDeclaration): any;
}
}

View file

@ -0,0 +1 @@
//# sourceMappingURL=interface.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,6 @@
/** @hidden */
export declare const resolveFactory: () => {
resolve: (invocables: {
[key: string]: Function;
}, locals?: {}, parent?: Promise<any>) => Promise<{}>;
};

View file

@ -0,0 +1,67 @@
/** @module ng1 */ /** */
import { StateObject, PathNode, ResolveContext, mapObj, resolvablesBuilder } from "@uirouter/core";
import * as angular from "angular";
/**
* Implementation of the legacy `$resolve` service for angular 1.
*/
var $resolve = {
/**
* Asynchronously injects a resolve block.
*
* This emulates most of the behavior of the ui-router 0.2.x $resolve.resolve() service API.
*
* ### Not bundled by default
*
* This API is no longer not part of the standard `@uirouter/angularjs` bundle.
* For users of the prebuilt bundles, add the `release/resolveService.min.js` UMD bundle.
* For bundlers (webpack, browserify, etc), add `@uirouter/angularjs/lib/legacy/resolveService`.
*
* ---
*
* Given an object `invocables`, where keys are strings and values are injectable functions,
* injects each function, and waits for the resulting promise to resolve.
* When all resulting promises are resolved, returns the results as an object.
*
* #### Example:
* ```js
* let invocables = {
* foo: [ '$http', ($http) =>
* $http.get('/api/foo').then(resp => resp.data) ],
* bar: [ 'foo', '$http', (foo, $http) =>
* $http.get('/api/bar/' + foo.barId).then(resp => resp.data) ]
* }
* $resolve.resolve(invocables)
* .then(results => console.log(results.foo, results.bar))
* // Logs foo and bar:
* // { id: 123, barId: 456, fooData: 'foo data' }
* // { id: 456, barData: 'bar data' }
* ```
*
* @param invocables an object which looks like an [[StateDeclaration.resolve]] object; keys are resolve names and values are injectable functions
* @param locals key/value pre-resolved data (locals)
* @param parent a promise for a "parent resolve"
*/
resolve: function (invocables, locals, parent) {
if (locals === void 0) { locals = {}; }
var parentNode = new PathNode(new StateObject({ params: {}, resolvables: [] }));
var node = new PathNode(new StateObject({ params: {}, resolvables: [] }));
var context = new ResolveContext([parentNode, node]);
context.addResolvables(resolvablesBuilder({ resolve: invocables }), node.state);
var resolveData = function (parentLocals) {
var rewrap = function (_locals) { return resolvablesBuilder({ resolve: mapObj(_locals, function (local) { return function () { return local; }; }) }); };
context.addResolvables(rewrap(parentLocals), parentNode.state);
context.addResolvables(rewrap(locals), node.state);
var tuples2ObjR = function (acc, tuple) {
acc[tuple.token] = tuple.value;
return acc;
};
return context.resolvePath().then(function (results) { return results.reduce(tuples2ObjR, {}); });
};
return parent ? parent.then(resolveData) : resolveData({});
}
};
/** @hidden */
export var resolveFactory = function () { return $resolve; };
// The old $resolve service
angular.module('ui.router').factory('$resolve', resolveFactory);
//# sourceMappingURL=resolveService.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "resolveService.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/legacy/resolveService.ts"
],
"names": [],
"mappings": "AAAA,kBAAkB,CAAC,MAAM;AACzB,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,cAAc,EAAO,MAAM,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACxG,OAAO,KAAK,OAAO,MAAM,SAAS,CAAC;AAEnC;;GAEG;AACH,IAAI,QAAQ,GAAG;IACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IACH,OAAO,EAAE,UAAC,UAAuC,EAAE,MAAW,EAAE,MAAqB;QAAlC,uBAAA,EAAA,WAAW;QAC5D,IAAI,UAAU,GAAG,IAAI,QAAQ,CAAC,IAAI,WAAW,CAAO,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;QACtF,IAAI,IAAI,GAAG,IAAI,QAAQ,CAAC,IAAI,WAAW,CAAO,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;QAChF,IAAI,OAAO,GAAG,IAAI,cAAc,CAAC,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;QAErD,OAAO,CAAC,cAAc,CAAC,kBAAkB,CAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAEtF,IAAM,WAAW,GAAG,UAAC,YAAiB;YACpC,IAAM,MAAM,GAAG,UAAC,OAAY,IAAK,OAAA,kBAAkB,CAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,UAAA,KAAK,IAAI,OAAA,cAAM,OAAA,KAAK,EAAL,CAAK,EAAX,CAAW,CAAC,EAAE,CAAC,EAA5E,CAA4E,CAAC;YAC9G,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC;YAC/D,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;YAEnD,IAAM,WAAW,GAAG,UAAC,GAAQ,EAAE,KAAiC;gBAC9D,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC;gBAC/B,MAAM,CAAC,GAAG,CAAC;YACb,CAAC,CAAC;YACF,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,UAAA,OAAO,IAAI,OAAA,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC,EAA/B,CAA+B,CAAC,CAAC;QAChF,CAAC,CAAC;QAEF,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF,CAAC;AAEF,cAAc;AACd,MAAM,CAAC,IAAM,cAAc,GAAG,cAAM,OAAA,QAAQ,EAAR,CAAQ,CAAC;AAE7C,2BAA2B;AAC3B,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC,UAAU,EAAQ,cAAc,CAAC,CAAC",
"sourcesContent": [
"/** @module ng1 */ /** */\nimport { StateObject, PathNode, ResolveContext, Obj, mapObj, resolvablesBuilder } from \"@uirouter/core\";\nimport * as angular from \"angular\";\n\n/**\n * Implementation of the legacy `$resolve` service for angular 1.\n */\nvar $resolve = {\n /**\n * Asynchronously injects a resolve block.\n *\n * This emulates most of the behavior of the ui-router 0.2.x $resolve.resolve() service API.\n *\n * ### Not bundled by default\n *\n * This API is no longer not part of the standard `@uirouter/angularjs` bundle.\n * For users of the prebuilt bundles, add the `release/resolveService.min.js` UMD bundle.\n * For bundlers (webpack, browserify, etc), add `@uirouter/angularjs/lib/legacy/resolveService`.\n *\n * ---\n *\n * Given an object `invocables`, where keys are strings and values are injectable functions,\n * injects each function, and waits for the resulting promise to resolve.\n * When all resulting promises are resolved, returns the results as an object.\n *\n * #### Example:\n * ```js\n * let invocables = {\n * foo: [ '$http', ($http) =>\n * $http.get('/api/foo').then(resp => resp.data) ],\n * bar: [ 'foo', '$http', (foo, $http) =>\n * $http.get('/api/bar/' + foo.barId).then(resp => resp.data) ]\n * }\n * $resolve.resolve(invocables)\n * .then(results => console.log(results.foo, results.bar))\n * // Logs foo and bar:\n * // { id: 123, barId: 456, fooData: 'foo data' }\n * // { id: 456, barData: 'bar data' }\n * ```\n *\n * @param invocables an object which looks like an [[StateDeclaration.resolve]] object; keys are resolve names and values are injectable functions\n * @param locals key/value pre-resolved data (locals)\n * @param parent a promise for a \"parent resolve\"\n */\n resolve: (invocables: { [key: string]: Function }, locals = {}, parent?: Promise<any>) => {\n let parentNode = new PathNode(new StateObject(<any> { params: {}, resolvables: [] }));\n let node = new PathNode(new StateObject(<any> { params: {}, resolvables: [] }));\n let context = new ResolveContext([parentNode, node]);\n\n context.addResolvables(resolvablesBuilder(<any> { resolve: invocables }), node.state);\n\n const resolveData = (parentLocals: Obj) => {\n const rewrap = (_locals: Obj) => resolvablesBuilder(<any> { resolve: mapObj(_locals, local => () => local) });\n context.addResolvables(rewrap(parentLocals), parentNode.state);\n context.addResolvables(rewrap(locals), node.state);\n\n const tuples2ObjR = (acc: Obj, tuple: { token: any, value: any }) => {\n acc[tuple.token] = tuple.value;\n return acc;\n };\n return context.resolvePath().then(results => results.reduce(tuples2ObjR, {}));\n };\n\n return parent ? parent.then(resolveData) : resolveData({});\n }\n};\n\n/** @hidden */\nexport const resolveFactory = () => $resolve;\n\n// The old $resolve service\nangular.module('ui.router').factory('$resolve', <any> resolveFactory);\n"
]
}

View file

@ -0,0 +1,124 @@
import { IAngularEvent } from "angular";
/**
* An event broadcast on `$rootScope` when the state transition **begins**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] instead
*
* You can use `event.preventDefault()`
* to prevent the transition from happening and then the transition promise will be
* rejected with a `'transition prevented'` value.
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]]
*
* #### Example:
* ```js
* $rootScope.$on('$stateChangeStart', function(event, transition) {
* event.preventDefault();
* // transitionTo() promise will be rejected with
* // a 'transition prevented' error
* })
* ```
*
* @event $stateChangeStart
* @deprecated
*/
export declare var $stateChangeStart: IAngularEvent;
/**
* An event broadcast on `$rootScope` if a transition is **cancelled**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] instead
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that was cancelled
*
* @event $stateChangeCancel
* @deprecated
*/
export declare var $stateChangeCancel: IAngularEvent;
/**
* An event broadcast on `$rootScope` once the state transition is **complete**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] and [[Transition.promise]], or [[Transition.onSuccess]]
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that just succeeded
*
* @event $stateChangeSuccess
* @deprecated
*/
export declare var $stateChangeSuccess: IAngularEvent;
/**
* An event broadcast on `$rootScope` when an **error occurs** during transition.
*
* ### Deprecation warning: use [[TransitionService.onStart]] and [[Transition.promise]], or [[Transition.onError]]
*
* It's important to note that if you
* have any errors in your resolve functions (javascript errors, non-existent services, etc)
* they will not throw traditionally. You must listen for this $stateChangeError event to
* catch **ALL** errors.
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `error`: The reason the transition errored.
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that errored
*
* @event $stateChangeError
* @deprecated
*/
export declare var $stateChangeError: IAngularEvent;
/**
* An event broadcast on `$rootScope` when a requested state **cannot be found** using the provided state name.
*
* ### Deprecation warning: use [[StateService.onInvalid]] instead
*
* The event is broadcast allowing any handlers a single chance to deal with the error (usually by
* lazy-loading the unfound state). A `TargetState` object is passed to the listener handler,
* you can see its properties in the example. You can use `event.preventDefault()` to abort the
* transition and the promise returned from `transitionTo()` will be rejected with a
* `'transition aborted'` error.
*
* Additional arguments to the event handler are provided:
* - `unfoundState` Unfound State information. Contains: `to, toParams, options` properties.
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
*
* #### Example:
* ```js
* // somewhere, assume lazy.state has not been defined
* $state.go("lazy.state", { a: 1, b: 2 }, { inherit: false });
*
* // somewhere else
* $scope.$on('$stateNotFound', function(event, transition) {
* function(event, unfoundState, fromState, fromParams){
* console.log(unfoundState.to); // "lazy.state"
* console.log(unfoundState.toParams); // {a:1, b:2}
* console.log(unfoundState.options); // {inherit:false} + default options
* });
* ```
*
* @event $stateNotFound
* @deprecated
*/
export declare var $stateNotFound: IAngularEvent;

View file

@ -0,0 +1,270 @@
/**
* # Legacy state events
*
* Polyfill implementation of the UI-Router 0.2.x state events.
*
* The 0.2.x state events are deprecated. We recommend moving to Transition Hooks instead, as they
* provide much more flexibility, support async, and provide the context (the Transition, etc) necessary
* to implement meaningful application behaviors.
*
* To enable these state events, include the `stateEvents.js` file in your project, e.g.,
* ```
* <script src="stateEvents.js"></script>
* ```
* and also make sure you depend on the `ui.router.state.events` angular module, e.g.,
* ```
* angular.module("myApplication", ['ui.router', 'ui.router.state.events']
* ```
*
* @module ng1_state_events
*/ /** */
import { ng as angular } from "../angular";
/**
* An event broadcast on `$rootScope` when the state transition **begins**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] instead
*
* You can use `event.preventDefault()`
* to prevent the transition from happening and then the transition promise will be
* rejected with a `'transition prevented'` value.
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]]
*
* #### Example:
* ```js
* $rootScope.$on('$stateChangeStart', function(event, transition) {
* event.preventDefault();
* // transitionTo() promise will be rejected with
* // a 'transition prevented' error
* })
* ```
*
* @event $stateChangeStart
* @deprecated
*/
export var $stateChangeStart;
/**
* An event broadcast on `$rootScope` if a transition is **cancelled**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] instead
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that was cancelled
*
* @event $stateChangeCancel
* @deprecated
*/
export var $stateChangeCancel;
/**
* An event broadcast on `$rootScope` once the state transition is **complete**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] and [[Transition.promise]], or [[Transition.onSuccess]]
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that just succeeded
*
* @event $stateChangeSuccess
* @deprecated
*/
export var $stateChangeSuccess;
/**
* An event broadcast on `$rootScope` when an **error occurs** during transition.
*
* ### Deprecation warning: use [[TransitionService.onStart]] and [[Transition.promise]], or [[Transition.onError]]
*
* It's important to note that if you
* have any errors in your resolve functions (javascript errors, non-existent services, etc)
* they will not throw traditionally. You must listen for this $stateChangeError event to
* catch **ALL** errors.
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `error`: The reason the transition errored.
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that errored
*
* @event $stateChangeError
* @deprecated
*/
export var $stateChangeError;
/**
* An event broadcast on `$rootScope` when a requested state **cannot be found** using the provided state name.
*
* ### Deprecation warning: use [[StateService.onInvalid]] instead
*
* The event is broadcast allowing any handlers a single chance to deal with the error (usually by
* lazy-loading the unfound state). A `TargetState` object is passed to the listener handler,
* you can see its properties in the example. You can use `event.preventDefault()` to abort the
* transition and the promise returned from `transitionTo()` will be rejected with a
* `'transition aborted'` error.
*
* Additional arguments to the event handler are provided:
* - `unfoundState` Unfound State information. Contains: `to, toParams, options` properties.
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
*
* #### Example:
* ```js
* // somewhere, assume lazy.state has not been defined
* $state.go("lazy.state", { a: 1, b: 2 }, { inherit: false });
*
* // somewhere else
* $scope.$on('$stateNotFound', function(event, transition) {
* function(event, unfoundState, fromState, fromParams){
* console.log(unfoundState.to); // "lazy.state"
* console.log(unfoundState.toParams); // {a:1, b:2}
* console.log(unfoundState.options); // {inherit:false} + default options
* });
* ```
*
* @event $stateNotFound
* @deprecated
*/
export var $stateNotFound;
(function () {
var isFunction = angular.isFunction, isString = angular.isString;
function applyPairs(memo, keyValTuple) {
var key, value;
if (Array.isArray(keyValTuple))
key = keyValTuple[0], value = keyValTuple[1];
if (!isString(key))
throw new Error("invalid parameters to applyPairs");
memo[key] = value;
return memo;
}
function stateChangeStartHandler($transition$) {
if (!$transition$.options().notify || !$transition$.valid() || $transition$.ignored())
return;
var $injector = $transition$.injector();
var $stateEvents = $injector.get('$stateEvents');
var $rootScope = $injector.get('$rootScope');
var $state = $injector.get('$state');
var $urlRouter = $injector.get('$urlRouter');
var enabledEvents = $stateEvents.provider.enabled();
var toParams = $transition$.params("to");
var fromParams = $transition$.params("from");
if (enabledEvents.$stateChangeSuccess) {
var startEvent = $rootScope.$broadcast('$stateChangeStart', $transition$.to(), toParams, $transition$.from(), fromParams, $transition$.options(), $transition$);
if (startEvent.defaultPrevented) {
if (enabledEvents.$stateChangeCancel) {
$rootScope.$broadcast('$stateChangeCancel', $transition$.to(), toParams, $transition$.from(), fromParams, $transition$.options(), $transition$);
}
//Don't update and resync url if there's been a new transition started. see issue #2238, #600
if ($state.transition == null)
$urlRouter.update();
return false;
}
// right after global state is updated
var successOpts = { priority: 9999 };
$transition$.onSuccess({}, function () {
$rootScope.$broadcast('$stateChangeSuccess', $transition$.to(), toParams, $transition$.from(), fromParams, $transition$.options(), $transition$);
}, successOpts);
}
if (enabledEvents.$stateChangeError) {
$transition$.promise["catch"](function (error) {
if (error && (error.type === 2 /* RejectType.SUPERSEDED */ || error.type === 3 /* RejectType.ABORTED */))
return;
var evt = $rootScope.$broadcast('$stateChangeError', $transition$.to(), toParams, $transition$.from(), fromParams, error, $transition$.options(), $transition$);
if (!evt.defaultPrevented) {
$urlRouter.update();
}
});
}
}
stateNotFoundHandler.$inject = ['$to$', '$from$', '$state', '$rootScope', '$urlRouter'];
function stateNotFoundHandler($to$, $from$, injector) {
var $state = injector.get('$state');
var $rootScope = injector.get('$rootScope');
var $urlRouter = injector.get('$urlRouter');
var redirect = { to: $to$.identifier(), toParams: $to$.params(), options: $to$.options() };
var e = $rootScope.$broadcast('$stateNotFound', redirect, $from$.state(), $from$.params());
if (e.defaultPrevented || e.retry)
$urlRouter.update();
function redirectFn() {
return $state.target(redirect.to, redirect.toParams, redirect.options);
}
if (e.defaultPrevented) {
return false;
}
else if (e.retry || !!$state.get(redirect.to)) {
return e.retry && isFunction(e.retry.then) ? e.retry.then(redirectFn) : redirectFn();
}
}
$StateEventsProvider.$inject = ['$stateProvider'];
function $StateEventsProvider($stateProvider) {
$StateEventsProvider.prototype.instance = this;
var runtime = false;
var allEvents = ['$stateChangeStart', '$stateNotFound', '$stateChangeSuccess', '$stateChangeError'];
var enabledStateEvents = allEvents.map(function (e) { return [e, true]; }).reduce(applyPairs, {});
function assertNotRuntime() {
if (runtime)
throw new Error("Cannot enable events at runtime (use $stateEventsProvider");
}
/**
* Enables the deprecated UI-Router 0.2.x State Events
* [ '$stateChangeStart', '$stateNotFound', '$stateChangeSuccess', '$stateChangeError' ]
*/
this.enable = function () {
var events = [];
for (var _i = 0; _i < arguments.length; _i++) {
events[_i] = arguments[_i];
}
assertNotRuntime();
if (!events || !events.length)
events = allEvents;
events.forEach(function (event) { return enabledStateEvents[event] = true; });
};
/**
* Disables the deprecated UI-Router 0.2.x State Events
* [ '$stateChangeStart', '$stateNotFound', '$stateChangeSuccess', '$stateChangeError' ]
*/
this.disable = function () {
var events = [];
for (var _i = 0; _i < arguments.length; _i++) {
events[_i] = arguments[_i];
}
assertNotRuntime();
if (!events || !events.length)
events = allEvents;
events.forEach(function (event) { return delete enabledStateEvents[event]; });
};
this.enabled = function () { return enabledStateEvents; };
this.$get = $get;
$get.$inject = ['$transitions'];
function $get($transitions) {
runtime = true;
if (enabledStateEvents["$stateNotFound"])
$stateProvider.onInvalid(stateNotFoundHandler);
if (enabledStateEvents.$stateChangeStart)
$transitions.onBefore({}, stateChangeStartHandler, { priority: 1000 });
return {
provider: $StateEventsProvider.prototype.instance
};
}
}
angular.module('ui.router.state.events', ['ui.router.state'])
.provider("$stateEvents", $StateEventsProvider)
.run(['$stateEvents', function ($stateEvents) {
}]);
})();
//# sourceMappingURL=stateEvents.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,43 @@
/**
* @internalapi
* @module ng1
*/ /** */
import { LocationConfig, LocationServices, UIRouter } from "@uirouter/core";
import { ILocationService, ILocationProvider } from "angular";
/**
* Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service
*/
export declare class Ng1LocationServices implements LocationConfig, LocationServices {
private $locationProvider;
private $location;
private $sniffer;
path: any;
search: any;
hash: any;
hashPrefix: any;
port: any;
protocol: any;
host: any;
baseHref: any;
private _urlListeners;
dispose(): void;
constructor($locationProvider: ILocationProvider);
onChange(callback: Function): () => Function[];
html5Mode(): any;
url(newUrl?: string, replace?: boolean, state?: any): string;
_runtimeServices($rootScope: any, $location: ILocationService, $sniffer: any, $browser: any): void;
/**
* Applys ng1-specific path parameter encoding
*
* The Angular 1 `$location` service is a bit weird.
* It doesn't allow slashes to be encoded/decoded bi-directionally.
*
* See the writeup at https://github.com/angular-ui/ui-router/issues/2598
*
* This code patches the `path` parameter type so it encoded/decodes slashes as ~2F
*
* @param router
*/
static monkeyPatchPathParameterType(router: UIRouter): void;
}

View file

@ -0,0 +1,73 @@
import { val, createProxyFunctions, removeFrom, isObject } from "@uirouter/core";
/**
* Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service
*/
var Ng1LocationServices = /** @class */ (function () {
function Ng1LocationServices($locationProvider) {
// .onChange() registry
this._urlListeners = [];
this.$locationProvider = $locationProvider;
var _lp = val($locationProvider);
createProxyFunctions(_lp, this, _lp, ['hashPrefix']);
}
Ng1LocationServices.prototype.dispose = function () { };
Ng1LocationServices.prototype.onChange = function (callback) {
var _this = this;
this._urlListeners.push(callback);
return function () { return removeFrom(_this._urlListeners)(callback); };
};
Ng1LocationServices.prototype.html5Mode = function () {
var html5Mode = this.$locationProvider.html5Mode();
html5Mode = isObject(html5Mode) ? html5Mode.enabled : html5Mode;
return html5Mode && this.$sniffer.history;
};
Ng1LocationServices.prototype.url = function (newUrl, replace, state) {
if (replace === void 0) { replace = false; }
if (newUrl)
this.$location.url(newUrl);
if (replace)
this.$location.replace();
if (state)
this.$location.state(state);
return this.$location.url();
};
Ng1LocationServices.prototype._runtimeServices = function ($rootScope, $location, $sniffer, $browser) {
var _this = this;
this.$location = $location;
this.$sniffer = $sniffer;
// Bind $locationChangeSuccess to the listeners registered in LocationService.onChange
$rootScope.$on("$locationChangeSuccess", function (evt) { return _this._urlListeners.forEach(function (fn) { return fn(evt); }); });
var _loc = val($location);
var _browser = val($browser);
// Bind these LocationService functions to $location
createProxyFunctions(_loc, this, _loc, ["replace", "path", "search", "hash"]);
// Bind these LocationConfig functions to $location
createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']);
// Bind these LocationConfig functions to $browser
createProxyFunctions(_browser, this, _browser, ['baseHref']);
};
/**
* Applys ng1-specific path parameter encoding
*
* The Angular 1 `$location` service is a bit weird.
* It doesn't allow slashes to be encoded/decoded bi-directionally.
*
* See the writeup at https://github.com/angular-ui/ui-router/issues/2598
*
* This code patches the `path` parameter type so it encoded/decodes slashes as ~2F
*
* @param router
*/
Ng1LocationServices.monkeyPatchPathParameterType = function (router) {
var pathType = router.urlMatcherFactory.type('path');
pathType.encode = function (val) {
return val != null ? val.toString().replace(/(~|\/)/g, function (m) { return ({ '~': '~~', '/': '~2F' }[m]); }) : val;
};
pathType.decode = function (val) {
return val != null ? val.toString().replace(/(~~|~2F)/g, function (m) { return ({ '~~': '~', '~2F': '/' }[m]); }) : val;
};
};
return Ng1LocationServices;
}());
export { Ng1LocationServices };
//# sourceMappingURL=locationServices.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "locationServices.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/locationServices.ts"
],
"names": [],
"mappings": "AAKA,OAAO,EAAE,GAAG,EAAE,oBAAoB,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAGjF;;GAEG;AACH;IAmBE,6BAAY,iBAAoC;QALhD,uBAAuB;QACf,kBAAa,GAAe,EAAE,CAAC;QAKrC,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,GAAG,GAAG,GAAG,CAAC,iBAAiB,CAAC,CAAC;QACjC,oBAAoB,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC;IACvD,CAAC;IAND,qCAAO,GAAP,cAAY,CAAC;IAQb,sCAAQ,GAAR,UAAS,QAAkB;QAA3B,iBAGC;QAFC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAClC,MAAM,CAAC,cAAM,OAAA,UAAU,CAAC,KAAI,CAAC,aAAa,CAAC,CAAC,QAAQ,CAAC,EAAxC,CAAwC,CAAC;IACxD,CAAC;IAED,uCAAS,GAAT;QACE,IAAI,SAAS,GAAQ,IAAI,CAAC,iBAAiB,CAAC,SAAS,EAAE,CAAC;QACxD,SAAS,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;QAChE,MAAM,CAAC,SAAS,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;IAC5C,CAAC;IAED,iCAAG,GAAH,UAAI,MAAe,EAAE,OAAe,EAAE,KAAM;QAAvB,wBAAA,EAAA,eAAe;QAClC,EAAE,CAAC,CAAC,MAAM,CAAC;YAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACvC,EAAE,CAAC,CAAC,OAAO,CAAC;YAAC,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;QACtC,EAAE,CAAC,CAAC,KAAK,CAAC;YAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACvC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC;IAC9B,CAAC;IAED,8CAAgB,GAAhB,UAAiB,UAAU,EAAE,SAA2B,EAAE,QAAQ,EAAE,QAAQ;QAA5E,iBAeC;QAdC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,sFAAsF;QACtF,UAAU,CAAC,GAAG,CAAC,wBAAwB,EAAE,UAAA,GAAG,IAAI,OAAA,KAAI,CAAC,aAAa,CAAC,OAAO,CAAC,UAAA,EAAE,IAAI,OAAA,EAAE,CAAC,GAAG,CAAC,EAAP,CAAO,CAAC,EAAzC,CAAyC,CAAC,CAAC;QAC3F,IAAI,IAAI,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QAC1B,IAAI,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC;QAE7B,oDAAoD;QACpD,oBAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC;QAC9E,mDAAmD;QACnD,oBAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;QACrE,kDAAkD;QAClD,oBAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;IAC/D,CAAC;IAED;;;;;;;;;;;OAWG;IACI,gDAA4B,GAAnC,UAAoC,MAAgB;QAClD,IAAI,QAAQ,GAAc,MAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAEhE,QAAQ,CAAC,MAAM,GAAG,UAAC,GAAQ;YACvB,OAAA,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,SAAS,EAAE,UAAA,CAAC,IAAI,OAAA,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,EAA9B,CAA8B,CAAC,CAAC,CAAC,CAAC,GAAG;QAA1F,CAA0F,CAAC;QAE/F,QAAQ,CAAC,MAAM,GAAG,UAAC,GAAW;YAC1B,OAAA,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,UAAA,CAAC,IAAI,OAAA,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,EAA9B,CAA8B,CAAC,CAAC,CAAC,CAAC,GAAG;QAA5F,CAA4F,CAAC;IAEnG,CAAC;IACH,0BAAC;AAAD,CAAC,AAlFD,IAkFC",
"sourcesContent": [
"/**\n * @internalapi\n * @module ng1\n */ /** */\nimport { LocationConfig, LocationServices, UIRouter, ParamType } from \"@uirouter/core\";\nimport { val, createProxyFunctions, removeFrom, isObject } from \"@uirouter/core\";\nimport { ILocationService, ILocationProvider } from \"angular\";\n\n/**\n * Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service\n */\nexport class Ng1LocationServices implements LocationConfig, LocationServices {\n private $locationProvider: ILocationProvider;\n private $location: ILocationService;\n private $sniffer;\n\n path;\n search;\n hash;\n hashPrefix;\n port;\n protocol;\n host;\n baseHref;\n\n // .onChange() registry\n private _urlListeners: Function[] = [];\n\n dispose() { }\n\n constructor($locationProvider: ILocationProvider) {\n this.$locationProvider = $locationProvider;\n let _lp = val($locationProvider);\n createProxyFunctions(_lp, this, _lp, ['hashPrefix']);\n }\n\n onChange(callback: Function) {\n this._urlListeners.push(callback);\n return () => removeFrom(this._urlListeners)(callback);\n }\n\n html5Mode() {\n let html5Mode: any = this.$locationProvider.html5Mode();\n html5Mode = isObject(html5Mode) ? html5Mode.enabled : html5Mode;\n return html5Mode && this.$sniffer.history;\n }\n\n url(newUrl?: string, replace = false, state?) {\n if (newUrl) this.$location.url(newUrl);\n if (replace) this.$location.replace();\n if (state) this.$location.state(state);\n return this.$location.url();\n }\n\n _runtimeServices($rootScope, $location: ILocationService, $sniffer, $browser) {\n this.$location = $location;\n this.$sniffer = $sniffer;\n\n // Bind $locationChangeSuccess to the listeners registered in LocationService.onChange\n $rootScope.$on(\"$locationChangeSuccess\", evt => this._urlListeners.forEach(fn => fn(evt)));\n let _loc = val($location);\n let _browser = val($browser);\n\n // Bind these LocationService functions to $location\n createProxyFunctions(_loc, this, _loc, [\"replace\", \"path\", \"search\", \"hash\"]);\n // Bind these LocationConfig functions to $location\n createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']);\n // Bind these LocationConfig functions to $browser\n createProxyFunctions(_browser, this, _browser, ['baseHref']);\n }\n\n /**\n * Applys ng1-specific path parameter encoding\n *\n * The Angular 1 `$location` service is a bit weird.\n * It doesn't allow slashes to be encoded/decoded bi-directionally.\n *\n * See the writeup at https://github.com/angular-ui/ui-router/issues/2598\n *\n * This code patches the `path` parameter type so it encoded/decodes slashes as ~2F\n *\n * @param router\n */\n static monkeyPatchPathParameterType(router: UIRouter) {\n let pathType: ParamType = router.urlMatcherFactory.type('path');\n\n pathType.encode = (val: any) =>\n val != null ? val.toString().replace(/(~|\\/)/g, m => ({ '~': '~~', '/': '~2F' }[m])) : val;\n\n pathType.decode = (val: string) =>\n val != null ? val.toString().replace(/(~~|~2F)/g, m => ({ '~~': '~', '~2F': '/' }[m])) : val;\n\n }\n}\n"
]
}

View file

@ -0,0 +1,16 @@
import { IRootScopeService } from "angular";
import { ResolveContext, TypedMap } from "@uirouter/core";
import { StateProvider } from "./stateProvider";
import { UrlRouterProvider } from "./urlRouterProvider";
declare module '@uirouter/core/lib/router' {
interface UIRouter {
/** @hidden */
stateProvider: StateProvider;
/** @hidden */
urlRouterProvider: UrlRouterProvider;
}
}
export declare function watchDigests($rootScope: IRootScopeService): void;
/** @hidden TODO: find a place to move this */
export declare const getLocals: (ctx: ResolveContext) => TypedMap<any>;

View file

@ -0,0 +1,113 @@
/**
* # Angular 1 types
*
* UI-Router core provides various Typescript types which you can use for code completion and validating parameter values, etc.
* The customizations to the core types for Angular UI-Router are documented here.
*
* The optional [[$resolve]] service is also documented here.
*
* @module ng1
* @preferred
*/
/** for typedoc */
import { ng as angular } from "./angular";
import { services, applyPairs, isString, trace, extend, UIRouter, unnestR } from "@uirouter/core";
import { ng1ViewsBuilder, getNg1ViewConfigFactory } from "./statebuilders/views";
import { TemplateFactory } from "./templateFactory";
import { StateProvider } from "./stateProvider";
import { getStateHookBuilder } from "./statebuilders/onEnterExitRetain";
import { Ng1LocationServices } from "./locationServices";
import { UrlRouterProvider } from "./urlRouterProvider";
angular.module("ui.router.angular1", []);
var mod_init = angular.module('ui.router.init', []);
var mod_util = angular.module('ui.router.util', ['ng', 'ui.router.init']);
var mod_rtr = angular.module('ui.router.router', ['ui.router.util']);
var mod_state = angular.module('ui.router.state', ['ui.router.router', 'ui.router.util', 'ui.router.angular1']);
var mod_main = angular.module('ui.router', ['ui.router.init', 'ui.router.state', 'ui.router.angular1']);
var mod_cmpt = angular.module('ui.router.compat', ['ui.router']); // tslint:disable-line
var router = null;
$uiRouter.$inject = ['$locationProvider'];
/** This angular 1 provider instantiates a Router and exposes its services via the angular injector */
function $uiRouter($locationProvider) {
// Create a new instance of the Router when the $uiRouterProvider is initialized
router = this.router = new UIRouter();
router.stateProvider = new StateProvider(router.stateRegistry, router.stateService);
// Apply ng1 specific StateBuilder code for `views`, `resolve`, and `onExit/Retain/Enter` properties
router.stateRegistry.decorator("views", ng1ViewsBuilder);
router.stateRegistry.decorator("onExit", getStateHookBuilder("onExit"));
router.stateRegistry.decorator("onRetain", getStateHookBuilder("onRetain"));
router.stateRegistry.decorator("onEnter", getStateHookBuilder("onEnter"));
router.viewService._pluginapi._viewConfigFactory('ng1', getNg1ViewConfigFactory());
var ng1LocationService = router.locationService = router.locationConfig = new Ng1LocationServices($locationProvider);
Ng1LocationServices.monkeyPatchPathParameterType(router);
// backwards compat: also expose router instance as $uiRouterProvider.router
router['router'] = router;
router['$get'] = $get;
$get.$inject = ['$location', '$browser', '$sniffer', '$rootScope', '$http', '$templateCache'];
function $get($location, $browser, $sniffer, $rootScope, $http, $templateCache) {
ng1LocationService._runtimeServices($rootScope, $location, $sniffer, $browser);
delete router['router'];
delete router['$get'];
return router;
}
return router;
}
var getProviderFor = function (serviceName) { return ['$uiRouterProvider', function ($urp) {
var service = $urp.router[serviceName];
service["$get"] = function () { return service; };
return service;
}]; };
// This effectively calls $get() on `$uiRouterProvider` to trigger init (when ng enters runtime)
runBlock.$inject = ['$injector', '$q', '$uiRouter'];
function runBlock($injector, $q, $uiRouter) {
services.$injector = $injector;
services.$q = $q;
// The $injector is now available.
// Find any resolvables that had dependency annotation deferred
$uiRouter.stateRegistry.get()
.map(function (x) { return x.$$state().resolvables; })
.reduce(unnestR, [])
.filter(function (x) { return x.deps === "deferred"; })
.forEach(function (resolvable) { return resolvable.deps = $injector.annotate(resolvable.resolveFn, $injector.strictDi); });
}
// $urlRouter service and $urlRouterProvider
var getUrlRouterProvider = function (uiRouter) {
return uiRouter.urlRouterProvider = new UrlRouterProvider(uiRouter);
};
// $state service and $stateProvider
// $urlRouter service and $urlRouterProvider
var getStateProvider = function () {
return extend(router.stateProvider, { $get: function () { return router.stateService; } });
};
watchDigests.$inject = ['$rootScope'];
export function watchDigests($rootScope) {
$rootScope.$watch(function () { trace.approximateDigests++; });
}
mod_init.provider("$uiRouter", $uiRouter);
mod_rtr.provider('$urlRouter', ['$uiRouterProvider', getUrlRouterProvider]);
mod_util.provider('$urlService', getProviderFor('urlService'));
mod_util.provider('$urlMatcherFactory', ['$uiRouterProvider', function () { return router.urlMatcherFactory; }]);
mod_util.provider('$templateFactory', function () { return new TemplateFactory(); });
mod_state.provider('$stateRegistry', getProviderFor('stateRegistry'));
mod_state.provider('$uiRouterGlobals', getProviderFor('globals'));
mod_state.provider('$transitions', getProviderFor('transitionService'));
mod_state.provider('$state', ['$uiRouterProvider', getStateProvider]);
mod_state.factory('$stateParams', ['$uiRouter', function ($uiRouter) { return $uiRouter.globals.params; }]);
mod_main.factory('$view', function () { return router.viewService; });
mod_main.service("$trace", function () { return trace; });
mod_main.run(watchDigests);
mod_util.run(['$urlMatcherFactory', function ($urlMatcherFactory) { }]);
mod_state.run(['$state', function ($state) { }]);
mod_rtr.run(['$urlRouter', function ($urlRouter) { }]);
mod_init.run(runBlock);
/** @hidden TODO: find a place to move this */
export var getLocals = function (ctx) {
var tokens = ctx.getTokens().filter(isString);
var tuples = tokens.map(function (key) {
var resolvable = ctx.getResolvable(key);
var waitPolicy = ctx.getPolicy(resolvable).async;
return [key, waitPolicy === 'NOWAIT' ? resolvable.promise : resolvable.data];
});
return tuples.reduce(applyPairs, {});
};
//# sourceMappingURL=services.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,3 @@
import { StateService } from "@uirouter/core";
export declare function $IsStateFilter($state: StateService): any;
export declare function $IncludedByStateFilter($state: StateService): any;

View file

@ -0,0 +1,42 @@
/** @module ng1 */ /** for typedoc */
import { ng as angular } from "./angular";
/**
* `isState` Filter: truthy if the current state is the parameter
*
* Translates to [[StateService.is]] `$state.is("stateName")`.
*
* #### Example:
* ```html
* <div ng-if="'stateName' | isState">show if state is 'stateName'</div>
* ```
*/
$IsStateFilter.$inject = ['$state'];
export function $IsStateFilter($state) {
var isFilter = function (state, params, options) {
return $state.is(state, params, options);
};
isFilter.$stateful = true;
return isFilter;
}
/**
* `includedByState` Filter: truthy if the current state includes the parameter
*
* Translates to [[StateService.includes]]` $state.is("fullOrPartialStateName")`.
*
* #### Example:
* ```html
* <div ng-if="'fullOrPartialStateName' | includedByState">show if state includes 'fullOrPartialStateName'</div>
* ```
*/
$IncludedByStateFilter.$inject = ['$state'];
export function $IncludedByStateFilter($state) {
var includesFilter = function (state, params, options) {
return $state.includes(state, params, options);
};
includesFilter.$stateful = true;
return includesFilter;
}
angular.module('ui.router.state')
.filter('isState', $IsStateFilter)
.filter('includedByState', $IncludedByStateFilter);
//# sourceMappingURL=stateFilters.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "stateFilters.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/stateFilters.ts"
],
"names": [],
"mappings": "AAAA,kBAAkB,CAAC,kBAAkB;AAErC,OAAO,EAAE,EAAE,IAAI,OAAO,EAAE,MAAM,WAAW,CAAC;AAG1C;;;;;;;;;GASG;AACH,cAAc,CAAC,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,yBAAyB,MAAoB;IACjD,IAAI,QAAQ,GAAQ,UAAS,KAAkB,EAAE,MAAW,EAAE,OAAoC;QAChG,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAC3C,CAAC,CAAC;IACF,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC;IAC1B,MAAM,CAAC,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;;GASG;AACH,sBAAsB,CAAC,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC;AAC5C,MAAM,iCAAiC,MAAoB;IACzD,IAAI,cAAc,GAAQ,UAAS,KAAkB,EAAE,MAAW,EAAE,OAAmC;QACrG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC,CAAC;IACF,cAAc,CAAC,SAAS,GAAG,IAAI,CAAC;IAChC,MAAM,CAAE,cAAc,CAAC;AACzB,CAAC;AAED,OAAO,CAAC,MAAM,CAAC,iBAAiB,CAAC;KAC9B,MAAM,CAAC,SAAS,EAAE,cAAc,CAAC;KACjC,MAAM,CAAC,iBAAiB,EAAE,sBAAsB,CAAC,CAAC",
"sourcesContent": [
"/** @module ng1 */ /** for typedoc */\n\nimport { ng as angular } from \"./angular\";\nimport { Obj, StateService, StateOrName } from \"@uirouter/core\";\n\n/**\n * `isState` Filter: truthy if the current state is the parameter\n *\n * Translates to [[StateService.is]] `$state.is(\"stateName\")`.\n *\n * #### Example:\n * ```html\n * <div ng-if=\"'stateName' | isState\">show if state is 'stateName'</div>\n * ```\n */\n$IsStateFilter.$inject = ['$state'];\nexport function $IsStateFilter($state: StateService) {\n var isFilter: any = function(state: StateOrName, params: Obj, options?: { relative?: StateOrName }) {\n return $state.is(state, params, options);\n };\n isFilter.$stateful = true;\n return isFilter;\n}\n\n/**\n * `includedByState` Filter: truthy if the current state includes the parameter\n *\n * Translates to [[StateService.includes]]` $state.is(\"fullOrPartialStateName\")`.\n *\n * #### Example:\n * ```html\n * <div ng-if=\"'fullOrPartialStateName' | includedByState\">show if state includes 'fullOrPartialStateName'</div>\n * ```\n */\n$IncludedByStateFilter.$inject = ['$state'];\nexport function $IncludedByStateFilter($state: StateService) {\n var includesFilter: any = function(state: StateOrName, params: Obj, options: { relative?: StateOrName }) {\n return $state.includes(state, params, options);\n };\n includesFilter.$stateful = true;\n return includesFilter;\n}\n\nangular.module('ui.router.state')\n .filter('isState', $IsStateFilter)\n .filter('includedByState', $IncludedByStateFilter);\n"
]
}

View file

@ -0,0 +1,254 @@
/** @module ng1 */ /** for typedoc */
import { BuilderFunction, StateRegistry, StateService, OnInvalidCallback } from "@uirouter/core";
import { Ng1StateDeclaration } from "./interface";
/**
* The Angular 1 `StateProvider`
*
* The `$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.
*/
export declare class StateProvider {
private stateRegistry;
private stateService;
constructor(stateRegistry: StateRegistry, stateService: StateService);
/**
* Decorates states when they are registered
*
* Allows you to extend (carefully) or override (at your own peril) the
* `stateBuilder` object used internally by [[StateRegistry]].
* This can be used to add custom functionality to ui-router,
* for example inferring templateUrl based on the state name.
*
* When passing only a name, it returns the current (original or decorated) builder
* function that matches `name`.
*
* The builder functions that can be decorated are listed below. Though not all
* necessarily have a good use case for decoration, that is up to you to decide.
*
* In addition, users can attach custom decorators, which will generate new
* properties within the state's internal definition. There is currently no clear
* use-case for this beyond accessing internal states (i.e. $state.$current),
* however, expect this to become increasingly relevant as we introduce additional
* meta-programming features.
*
* **Warning**: Decorators should not be interdependent because the order of
* execution of the builder functions in non-deterministic. Builder functions
* should only be dependent on the state definition object and super function.
*
*
* Existing builder functions and current return values:
*
* - **parent** `{object}` - returns the parent state object.
* - **data** `{object}` - returns state data, including any inherited data that is not
* overridden by own values (if any).
* - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
* or `null`.
* - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
* navigable).
* - **params** `{object}` - returns an array of state params that are ensured to
* be a super-set of parent's params.
* - **views** `{object}` - returns a views object where each key is an absolute view
* name (i.e. "viewName@stateName") and each value is the config object
* (template, controller) for the view. Even when you don't use the views object
* explicitly on a state config, one is still created for you internally.
* So by decorating this builder function you have access to decorating template
* and controller properties.
* - **ownParams** `{object}` - returns an array of params that belong to the state,
* not including any params defined by ancestor states.
* - **path** `{string}` - returns the full path from the root down to this state.
* Needed for state activation.
* - **includes** `{object}` - returns an object that includes every state that
* would pass a `$state.includes()` test.
*
* #### Example:
* Override the internal 'views' builder with a function that takes the state
* definition, and a reference to the internal function being overridden:
* ```js
* $stateProvider.decorator('views', function (state, parent) {
* let result = {},
* views = parent(state);
*
* angular.forEach(views, function (config, name) {
* let autoName = (state.name + '.' + name).replace('.', '/');
* config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
* result[name] = config;
* });
* return result;
* });
*
* $stateProvider.state('home', {
* views: {
* 'contact.list': { controller: 'ListController' },
* 'contact.item': { controller: 'ItemController' }
* }
* });
* ```
*
*
* ```js
* // Auto-populates list and item views with /partials/home/contact/list.html,
* // and /partials/home/contact/item.html, respectively.
* $state.go('home');
* ```
*
* @param {string} name The name of the builder function to decorate.
* @param {object} func A function that is responsible for decorating the original
* builder function. The function receives two parameters:
*
* - `{object}` - state - The state config object.
* - `{object}` - super - The original builder function.
*
* @return {object} $stateProvider - $stateProvider instance
*/
decorator(name: string, func: BuilderFunction): Function | this | BuilderFunction[];
/**
* Registers a state
*
* ### This is a passthrough to [[StateRegistry.register]].
*
* Registers a state configuration under a given state name.
* The stateConfig object has the following acceptable properties.
*
* <a id='template'></a>
*
* - **`template`** - {string|function=} - html template as a string or a function that returns
* an html template as a string which should be used by the uiView directives. This property
* takes precedence over templateUrl.
*
* If `template` is a function, it will be called with the following parameters:
*
* - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <a id='templateUrl'></a>
*
* - **`templateUrl`** - {string|function=} - path or function that returns a path to an html
* template that should be used by uiView.
*
* If `templateUrl` is a function, it will be called with the following parameters:
*
* - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <a id='templateProvider'></a>
*
* - **`templateProvider`** - {function=} - Provider function that returns HTML content
* string.
*
* <a id='controller'></a>
*
* - **`controller`** - {string|function=} - Controller fn that should be associated with newly
* related scope or the name of a registered controller if passed as a string.
*
* <a id='controllerProvider'></a>
*
* - **`controllerProvider`** - {function=} - Injectable provider function that returns
* the actual controller or string.
*
* <a id='controllerAs'></a>
*
* - **`controllerAs`** {string=} A controller alias name. If present the controller will be
* published to scope under the controllerAs name.
*
* <a id='resolve'></a>
*
* - **`resolve`** - {object.&lt;string, function&gt;=} - An optional map of dependencies which
* should be injected into the controller. If any of these dependencies are promises,
* the router will wait for them all to be resolved or one to be rejected before the
* controller is instantiated. If all the promises are resolved successfully, the values
* of the resolved promises are injected and $stateChangeSuccess event is fired. If any
* of the promises are rejected the $stateChangeError event is fired. The map object is:
*
* - key - {string}: name of dependency to be injected into controller
* - factory - {string|function}: If string then it is alias for service. Otherwise if function,
* it is injected and return value it treated as dependency. If result is a promise, it is
* resolved before its value is injected into controller.
*
* <a id='url'></a>
*
* - **`url`** - {string=} - A url with optional parameters. When a state is navigated or
* transitioned to, the `$stateParams` service will be populated with any
* parameters that were passed.
*
* <a id='params'></a>
*
* - **`params`** - {object=} - An array of parameter names or regular expressions. Only
* use this within a state if you are not using url. Otherwise you can specify your
* parameters within the url. When a state is navigated or transitioned to, the
* $stateParams service will be populated with any parameters that were passed.
*
* <a id='views'></a>
*
* - **`views`** - {object=} - Use the views property to set up multiple views or to target views
* manually/explicitly.
*
* <a id='abstract'></a>
*
* - **`abstract`** - {boolean=} - An abstract state will never be directly activated,
* but can provide inherited properties to its common children states.
*
* <a id='onEnter'></a>
*
* - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way
* to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.
*
* <a id='onExit'></a>
*
* - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to
* trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.
*
* <a id='reloadOnSearch'></a>
*
* - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state
* just because a search/query parameter has changed (via $location.search() or $location.hash()).
* Useful for when you'd like to modify $location.search() without triggering a reload.
*
* <a id='data'></a>
*
* - **`data`** - {object=} - Arbitrary data object, useful for custom configuration.
*
* #### Example:
* Some state name examples
* ```js
* // stateName can be a single top-level name (must be unique).
* $stateProvider.state("home", {});
*
* // Or it can be a nested state name. This state is a child of the
* // above "home" state.
* $stateProvider.state("home.newest", {});
*
* // Nest states as deeply as needed.
* $stateProvider.state("home.newest.abc.xyz.inception", {});
*
* // state() returns $stateProvider, so you can chain state declarations.
* $stateProvider
* .state("home", {})
* .state("about", {})
* .state("contacts", {});
* ```
*
* @param {string} name A unique state name, e.g. "home", "about", "contacts".
* To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
* @param {object} definition State configuration object.
*/
state(name: string, definition: Ng1StateDeclaration): StateProvider;
state(definition: Ng1StateDeclaration): StateProvider;
/**
* Registers an invalid state handler
*
* This is a passthrough to [[StateService.onInvalid]] for ng1.
*/
onInvalid(callback: OnInvalidCallback): Function;
}

View file

@ -0,0 +1,138 @@
/** @module ng1 */ /** for typedoc */
import { val, isObject, createProxyFunctions } from "@uirouter/core";
/**
* The Angular 1 `StateProvider`
*
* The `$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.
*/
var StateProvider = /** @class */ (function () {
function StateProvider(stateRegistry, stateService) {
this.stateRegistry = stateRegistry;
this.stateService = stateService;
createProxyFunctions(val(StateProvider.prototype), this, val(this));
}
/**
* Decorates states when they are registered
*
* Allows you to extend (carefully) or override (at your own peril) the
* `stateBuilder` object used internally by [[StateRegistry]].
* This can be used to add custom functionality to ui-router,
* for example inferring templateUrl based on the state name.
*
* When passing only a name, it returns the current (original or decorated) builder
* function that matches `name`.
*
* The builder functions that can be decorated are listed below. Though not all
* necessarily have a good use case for decoration, that is up to you to decide.
*
* In addition, users can attach custom decorators, which will generate new
* properties within the state's internal definition. There is currently no clear
* use-case for this beyond accessing internal states (i.e. $state.$current),
* however, expect this to become increasingly relevant as we introduce additional
* meta-programming features.
*
* **Warning**: Decorators should not be interdependent because the order of
* execution of the builder functions in non-deterministic. Builder functions
* should only be dependent on the state definition object and super function.
*
*
* Existing builder functions and current return values:
*
* - **parent** `{object}` - returns the parent state object.
* - **data** `{object}` - returns state data, including any inherited data that is not
* overridden by own values (if any).
* - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
* or `null`.
* - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
* navigable).
* - **params** `{object}` - returns an array of state params that are ensured to
* be a super-set of parent's params.
* - **views** `{object}` - returns a views object where each key is an absolute view
* name (i.e. "viewName@stateName") and each value is the config object
* (template, controller) for the view. Even when you don't use the views object
* explicitly on a state config, one is still created for you internally.
* So by decorating this builder function you have access to decorating template
* and controller properties.
* - **ownParams** `{object}` - returns an array of params that belong to the state,
* not including any params defined by ancestor states.
* - **path** `{string}` - returns the full path from the root down to this state.
* Needed for state activation.
* - **includes** `{object}` - returns an object that includes every state that
* would pass a `$state.includes()` test.
*
* #### Example:
* Override the internal 'views' builder with a function that takes the state
* definition, and a reference to the internal function being overridden:
* ```js
* $stateProvider.decorator('views', function (state, parent) {
* let result = {},
* views = parent(state);
*
* angular.forEach(views, function (config, name) {
* let autoName = (state.name + '.' + name).replace('.', '/');
* config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
* result[name] = config;
* });
* return result;
* });
*
* $stateProvider.state('home', {
* views: {
* 'contact.list': { controller: 'ListController' },
* 'contact.item': { controller: 'ItemController' }
* }
* });
* ```
*
*
* ```js
* // Auto-populates list and item views with /partials/home/contact/list.html,
* // and /partials/home/contact/item.html, respectively.
* $state.go('home');
* ```
*
* @param {string} name The name of the builder function to decorate.
* @param {object} func A function that is responsible for decorating the original
* builder function. The function receives two parameters:
*
* - `{object}` - state - The state config object.
* - `{object}` - super - The original builder function.
*
* @return {object} $stateProvider - $stateProvider instance
*/
StateProvider.prototype.decorator = function (name, func) {
return this.stateRegistry.decorator(name, func) || this;
};
StateProvider.prototype.state = function (name, definition) {
if (isObject(name)) {
definition = name;
}
else {
definition.name = name;
}
this.stateRegistry.register(definition);
return this;
};
/**
* Registers an invalid state handler
*
* This is a passthrough to [[StateService.onInvalid]] for ng1.
*/
StateProvider.prototype.onInvalid = function (callback) {
return this.stateService.onInvalid(callback);
};
return StateProvider;
}());
export { StateProvider };
//# sourceMappingURL=stateProvider.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,10 @@
/** @module ng1 */ /** */
import { StateObject, TransitionStateHookFn, BuilderFunction } from "@uirouter/core";
/**
* This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`,
* `onRetain` callback hooks on a [[Ng1StateDeclaration]].
*
* When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder
* ensures that those hooks are injectable for @uirouter/angularjs (ng1).
*/
export declare const getStateHookBuilder: (hookName: "onEnter" | "onExit" | "onRetain") => (state: StateObject, parentFn: BuilderFunction) => TransitionStateHookFn;

View file

@ -0,0 +1,23 @@
/** @module ng1 */ /** */
import { services, ResolveContext, extend } from "@uirouter/core";
import { getLocals } from "../services";
/**
* This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`,
* `onRetain` callback hooks on a [[Ng1StateDeclaration]].
*
* When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder
* ensures that those hooks are injectable for @uirouter/angularjs (ng1).
*/
export var getStateHookBuilder = function (hookName) {
return function stateHookBuilder(state, parentFn) {
var hook = state[hookName];
var pathname = hookName === 'onExit' ? 'from' : 'to';
function decoratedNg1Hook(trans, state) {
var resolveContext = new ResolveContext(trans.treeChanges(pathname));
var locals = extend(getLocals(resolveContext), { $state$: state, $transition$: trans });
return services.$injector.invoke(hook, this, locals);
}
return hook ? decoratedNg1Hook : undefined;
};
};
//# sourceMappingURL=onEnterExitRetain.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "onEnterExitRetain.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/statebuilders/onEnterExitRetain.ts"
],
"names": [],
"mappings": "AAAA,kBAAkB,CAAC,MAAM;AACzB,OAAO,EACuD,QAAQ,EAAE,cAAc,EAAE,MAAM,EAC7F,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAGxC;;;;;;GAMG;AACH,MAAM,CAAC,IAAM,mBAAmB,GAAG,UAAC,QAAuC;IAC3E,OAAA,0BAA0B,KAAkB,EAAE,QAAyB;QACrE,IAAI,IAAI,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC3B,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;QAErD,0BAA0B,KAAiB,EAAE,KAA0B;YACrE,IAAI,cAAc,GAAG,IAAI,cAAc,CAAC,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC;YACrE,IAAI,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;YACxF,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QACvD,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,SAAS,CAAC;IAC7C,CAAC;AAXD,CAWC,CAAC",
"sourcesContent": [
"/** @module ng1 */ /** */\nimport {\n StateObject, TransitionStateHookFn, HookResult, Transition, services, ResolveContext, extend, BuilderFunction\n} from \"@uirouter/core\";\nimport { getLocals } from \"../services\";\nimport { Ng1StateDeclaration } from '../interface';\n\n/**\n * This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`,\n * `onRetain` callback hooks on a [[Ng1StateDeclaration]].\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * ensures that those hooks are injectable for @uirouter/angularjs (ng1).\n */\nexport const getStateHookBuilder = (hookName: \"onEnter\"|\"onExit\"|\"onRetain\") =>\nfunction stateHookBuilder(state: StateObject, parentFn: BuilderFunction): TransitionStateHookFn {\n let hook = state[hookName];\n let pathname = hookName === 'onExit' ? 'from' : 'to';\n\n function decoratedNg1Hook(trans: Transition, state: Ng1StateDeclaration): HookResult {\n let resolveContext = new ResolveContext(trans.treeChanges(pathname));\n let locals = extend(getLocals(resolveContext), { $state$: state, $transition$: trans });\n return services.$injector.invoke(hook, this, locals);\n }\n\n return hook ? decoratedNg1Hook : undefined;\n};\n"
]
}

View file

@ -0,0 +1,34 @@
import { StateObject, ViewConfig, ViewConfigFactory, PathNode, ResolveContext, IInjectable } from "@uirouter/core";
import { Ng1ViewDeclaration } from "../interface";
import { TemplateFactory } from "../templateFactory";
export declare function getNg1ViewConfigFactory(): ViewConfigFactory;
/**
* This is a [[StateBuilder.builder]] function for angular1 `views`.
*
* When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder
* handles the `views` property with logic specific to @uirouter/angularjs (ng1).
*
* If no `views: {}` property exists on the [[StateDeclaration]], then it creates the `views` object
* and applies the state-level configuration to a view named `$default`.
*/
export declare function ng1ViewsBuilder(state: StateObject): {};
export declare class Ng1ViewConfig implements ViewConfig {
path: PathNode[];
viewDecl: Ng1ViewDeclaration;
factory: TemplateFactory;
$id: number;
loaded: boolean;
controller: Function;
template: string;
component: string;
locals: any;
constructor(path: PathNode[], viewDecl: Ng1ViewDeclaration, factory: TemplateFactory);
load(): Promise<this>;
getTemplate: (uiView: any, context: ResolveContext) => string;
/**
* Gets the controller for a view configuration.
*
* @returns {Function|Promise.<Function>} Returns a controller, or a promise that resolves to a controller.
*/
getController(context: ResolveContext): (IInjectable | string | Promise<IInjectable | string>);
}

View file

@ -0,0 +1,105 @@
import { pick, forEach, tail, extend, isArray, isInjectable, isDefined, isString, services, trace, ViewService, ResolveContext, Resolvable } from "@uirouter/core";
export function getNg1ViewConfigFactory() {
var templateFactory = null;
return function (path, view) {
templateFactory = templateFactory || services.$injector.get("$templateFactory");
return [new Ng1ViewConfig(path, view, templateFactory)];
};
}
var hasAnyKey = function (keys, obj) {
return keys.reduce(function (acc, key) { return acc || isDefined(obj[key]); }, false);
};
/**
* This is a [[StateBuilder.builder]] function for angular1 `views`.
*
* When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder
* handles the `views` property with logic specific to @uirouter/angularjs (ng1).
*
* If no `views: {}` property exists on the [[StateDeclaration]], then it creates the `views` object
* and applies the state-level configuration to a view named `$default`.
*/
export function ng1ViewsBuilder(state) {
// Do not process root state
if (!state.parent)
return {};
var tplKeys = ['templateProvider', 'templateUrl', 'template', 'notify', 'async'], ctrlKeys = ['controller', 'controllerProvider', 'controllerAs', 'resolveAs'], compKeys = ['component', 'bindings', 'componentProvider'], nonCompKeys = tplKeys.concat(ctrlKeys), allViewKeys = compKeys.concat(nonCompKeys);
// Do not allow a state to have both state-level props and also a `views: {}` property.
// A state without a `views: {}` property can declare properties for the `$default` view as properties of the state.
// However, the `$default` approach should not be mixed with a separate `views: ` block.
if (isDefined(state.views) && hasAnyKey(allViewKeys, state)) {
throw new Error("State '" + state.name + "' has a 'views' object. " +
"It cannot also have \"view properties\" at the state level. " +
"Move the following properties into a view (in the 'views' object): " +
(" " + allViewKeys.filter(function (key) { return isDefined(state[key]); }).join(", ")));
}
var views = {}, viewsObject = state.views || { "$default": pick(state, allViewKeys) };
forEach(viewsObject, function (config, name) {
// Account for views: { "": { template... } }
name = name || "$default";
// Account for views: { header: "headerComponent" }
if (isString(config))
config = { component: config };
// Make a shallow copy of the config object
config = extend({}, config);
// Do not allow a view to mix props for component-style view with props for template/controller-style view
if (hasAnyKey(compKeys, config) && hasAnyKey(nonCompKeys, config)) {
throw new Error("Cannot combine: " + compKeys.join("|") + " with: " + nonCompKeys.join("|") + " in stateview: '" + name + "@" + state.name + "'");
}
config.resolveAs = config.resolveAs || '$resolve';
config.$type = "ng1";
config.$context = state;
config.$name = name;
var normalized = ViewService.normalizeUIViewTarget(config.$context, config.$name);
config.$uiViewName = normalized.uiViewName;
config.$uiViewContextAnchor = normalized.uiViewContextAnchor;
views[name] = config;
});
return views;
}
var id = 0;
var Ng1ViewConfig = /** @class */ (function () {
function Ng1ViewConfig(path, viewDecl, factory) {
var _this = this;
this.path = path;
this.viewDecl = viewDecl;
this.factory = factory;
this.$id = id++;
this.loaded = false;
this.getTemplate = function (uiView, context) {
return _this.component ? _this.factory.makeComponentTemplate(uiView, context, _this.component, _this.viewDecl.bindings) : _this.template;
};
}
Ng1ViewConfig.prototype.load = function () {
var _this = this;
var $q = services.$q;
var context = new ResolveContext(this.path);
var params = this.path.reduce(function (acc, node) { return extend(acc, node.paramValues); }, {});
var promises = {
template: $q.when(this.factory.fromConfig(this.viewDecl, params, context)),
controller: $q.when(this.getController(context))
};
return $q.all(promises).then(function (results) {
trace.traceViewServiceEvent("Loaded", _this);
_this.controller = results.controller;
extend(_this, results.template); // Either { template: "tpl" } or { component: "cmpName" }
return _this;
});
};
/**
* Gets the controller for a view configuration.
*
* @returns {Function|Promise.<Function>} Returns a controller, or a promise that resolves to a controller.
*/
Ng1ViewConfig.prototype.getController = function (context) {
var provider = this.viewDecl.controllerProvider;
if (!isInjectable(provider))
return this.viewDecl.controller;
var deps = services.$injector.annotate(provider);
var providerFn = isArray(provider) ? tail(provider) : provider;
var resolvable = new Resolvable("", providerFn, deps);
return resolvable.get(context);
};
return Ng1ViewConfig;
}());
export { Ng1ViewConfig };
//# sourceMappingURL=views.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,85 @@
import { IAugmentedJQuery } from "angular";
import { IInjectable, ResolveContext, RawParams } from "@uirouter/core";
import { Ng1ViewDeclaration, TemplateFactoryProvider } from "./interface";
/**
* Service which manages loading of templates from a ViewConfig.
*/
export declare class TemplateFactory implements TemplateFactoryProvider {
/** @hidden */ private _useHttp;
/** @hidden */ private $templateRequest;
/** @hidden */ private $templateCache;
/** @hidden */ private $http;
/** @hidden */ $get: (string | (($http: any, $templateCache: any, $injector: any) => this))[];
/** @hidden */
useHttpService(value: boolean): void;
/**
* Creates a template from a configuration object.
*
* @param 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 params Parameters to pass to the template function.
* @param context The resolve context associated with the template's view
*
* @return {string|object} The template html as a string, or a promise for
* that string,or `null` if no template is configured.
*/
fromConfig(config: Ng1ViewDeclaration, params: any, context: ResolveContext): Promise<{
template?: string;
component?: string;
}>;
/**
* Creates a template from a string or a function returning a string.
*
* @param template html template as a string or function that returns an html template as a string.
* @param params Parameters to pass to the template function.
*
* @return {string|object} The template html as a string, or a promise for that
* string.
*/
fromString(template: (string | Function), params?: RawParams): any;
/**
* 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.
*/
fromUrl(url: (string | Function), params: any): any;
/**
* Creates a template by invoking an injectable provider function.
*
* @param provider Function to invoke via `locals`
* @param {Function} injectFn a function used to invoke the template provider
* @return {string|Promise.<string>} The template html as a string, or a promise
* for that string.
*/
fromProvider(provider: IInjectable, params: any, context: ResolveContext): Promise<any>;
/**
* Creates a component's template by invoking an injectable provider function.
*
* @param provider Function to invoke via `locals`
* @param {Function} injectFn a function used to invoke the template provider
* @return {string} The template html as a string: "<component-name input1='::$resolve.foo'></component-name>".
*/
fromComponentProvider(provider: IInjectable, params: any, context: ResolveContext): Promise<any>;
/**
* Creates a template from a component's name
*
* This implements route-to-component.
* It works by retrieving the component (directive) metadata from the injector.
* It analyses the component's bindings, then constructs a template that instantiates the component.
* The template wires input and output bindings to resolves or from the parent component.
*
* @param uiView {object} The parent ui-view (for binding outputs to callbacks)
* @param context The ResolveContext (for binding outputs to callbacks returned from resolves)
* @param component {string} Component's name in camel case.
* @param bindings An object defining the component's bindings: {foo: '<'}
* @return {string} The template as a string: "<component-name input1='::$resolve.foo'></component-name>".
*/
makeComponentTemplate(uiView: IAugmentedJQuery, context: ResolveContext, component: string, bindings?: any): string;
}

View file

@ -0,0 +1,192 @@
/** @module view */
/** for typedoc */
import { ng as angular } from "./angular";
import { isArray, isDefined, isFunction, isObject, services, tail, kebobString, unnestR, Resolvable } from "@uirouter/core";
/**
* Service which manages loading of templates from a ViewConfig.
*/
var TemplateFactory = /** @class */ (function () {
function TemplateFactory() {
var _this = this;
/** @hidden */ this._useHttp = angular.version.minor < 3;
/** @hidden */ this.$get = ['$http', '$templateCache', '$injector', function ($http, $templateCache, $injector) {
_this.$templateRequest = $injector.has && $injector.has('$templateRequest') && $injector.get('$templateRequest');
_this.$http = $http;
_this.$templateCache = $templateCache;
return _this;
}];
}
/** @hidden */
TemplateFactory.prototype.useHttpService = function (value) {
this._useHttp = value;
};
;
/**
* Creates a template from a configuration object.
*
* @param 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 params Parameters to pass to the template function.
* @param context The resolve context associated with the template's view
*
* @return {string|object} The template html as a string, or a promise for
* that string,or `null` if no template is configured.
*/
TemplateFactory.prototype.fromConfig = function (config, params, context) {
var defaultTemplate = "<ui-view></ui-view>";
var asTemplate = function (result) { return services.$q.when(result).then(function (str) { return ({ template: str }); }); };
var asComponent = function (result) { return services.$q.when(result).then(function (str) { return ({ component: str }); }); };
return (isDefined(config.template) ? asTemplate(this.fromString(config.template, params)) :
isDefined(config.templateUrl) ? asTemplate(this.fromUrl(config.templateUrl, params)) :
isDefined(config.templateProvider) ? asTemplate(this.fromProvider(config.templateProvider, params, context)) :
isDefined(config.component) ? asComponent(config.component) :
isDefined(config.componentProvider) ? asComponent(this.fromComponentProvider(config.componentProvider, params, context)) :
asTemplate(defaultTemplate));
};
;
/**
* Creates a template from a string or a function returning a string.
*
* @param template html template as a string or function that returns an html template as a string.
* @param params Parameters to pass to the template function.
*
* @return {string|object} The template html as a string, or a promise for that
* string.
*/
TemplateFactory.prototype.fromString = function (template, params) {
return isFunction(template) ? template(params) : template;
};
;
/**
* 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.
*/
TemplateFactory.prototype.fromUrl = function (url, params) {
if (isFunction(url))
url = url(params);
if (url == null)
return null;
if (this._useHttp) {
return this.$http.get(url, { cache: this.$templateCache, headers: { Accept: 'text/html' } })
.then(function (response) {
return response.data;
});
}
return this.$templateRequest(url);
};
;
/**
* Creates a template by invoking an injectable provider function.
*
* @param provider Function to invoke via `locals`
* @param {Function} injectFn a function used to invoke the template provider
* @return {string|Promise.<string>} The template html as a string, or a promise
* for that string.
*/
TemplateFactory.prototype.fromProvider = function (provider, params, context) {
var deps = services.$injector.annotate(provider);
var providerFn = isArray(provider) ? tail(provider) : provider;
var resolvable = new Resolvable("", providerFn, deps);
return resolvable.get(context);
};
;
/**
* Creates a component's template by invoking an injectable provider function.
*
* @param provider Function to invoke via `locals`
* @param {Function} injectFn a function used to invoke the template provider
* @return {string} The template html as a string: "<component-name input1='::$resolve.foo'></component-name>".
*/
TemplateFactory.prototype.fromComponentProvider = function (provider, params, context) {
var deps = services.$injector.annotate(provider);
var providerFn = isArray(provider) ? tail(provider) : provider;
var resolvable = new Resolvable("", providerFn, deps);
return resolvable.get(context);
};
;
/**
* Creates a template from a component's name
*
* This implements route-to-component.
* It works by retrieving the component (directive) metadata from the injector.
* It analyses the component's bindings, then constructs a template that instantiates the component.
* The template wires input and output bindings to resolves or from the parent component.
*
* @param uiView {object} The parent ui-view (for binding outputs to callbacks)
* @param context The ResolveContext (for binding outputs to callbacks returned from resolves)
* @param component {string} Component's name in camel case.
* @param bindings An object defining the component's bindings: {foo: '<'}
* @return {string} The template as a string: "<component-name input1='::$resolve.foo'></component-name>".
*/
TemplateFactory.prototype.makeComponentTemplate = function (uiView, context, component, bindings) {
bindings = bindings || {};
// Bind once prefix
var prefix = angular.version.minor >= 3 ? "::" : "";
// Convert to kebob name. Add x- prefix if the string starts with `x-` or `data-`
var kebob = function (camelCase) {
var kebobed = kebobString(camelCase);
return /^(x|data)-/.exec(kebobed) ? "x-" + kebobed : kebobed;
};
var attributeTpl = function (input) {
var name = input.name, type = input.type;
var attrName = kebob(name);
// If the ui-view has an attribute which matches a binding on the routed component
// then pass that attribute through to the routed component template.
// Prefer ui-view wired mappings to resolve data, unless the resolve was explicitly bound using `bindings:`
if (uiView.attr(attrName) && !bindings[name])
return attrName + "='" + uiView.attr(attrName) + "'";
var resolveName = bindings[name] || name;
// Pre-evaluate the expression for "@" bindings by enclosing in {{ }}
// some-attr="{{ ::$resolve.someResolveName }}"
if (type === '@')
return attrName + "='{{" + prefix + "$resolve." + resolveName + "}}'";
// Wire "&" callbacks to resolves that return a callback function
// Get the result of the resolve (should be a function) and annotate it to get its arguments.
// some-attr="$resolve.someResolveResultName(foo, bar)"
if (type === '&') {
var res = context.getResolvable(resolveName);
var fn = res && res.data;
var args = fn && services.$injector.annotate(fn) || [];
// account for array style injection, i.e., ['foo', function(foo) {}]
var arrayIdxStr = isArray(fn) ? "[" + (fn.length - 1) + "]" : '';
return attrName + "='$resolve." + resolveName + arrayIdxStr + "(" + args.join(",") + ")'";
}
// some-attr="::$resolve.someResolveName"
return attrName + "='" + prefix + "$resolve." + resolveName + "'";
};
var attrs = getComponentBindings(component).map(attributeTpl).join(" ");
var kebobName = kebob(component);
return "<" + kebobName + " " + attrs + "></" + kebobName + ">";
};
;
return TemplateFactory;
}());
export { TemplateFactory };
// Gets all the directive(s)' inputs ('@', '=', and '<') and outputs ('&')
function getComponentBindings(name) {
var cmpDefs = services.$injector.get(name + "Directive"); // could be multiple
if (!cmpDefs || !cmpDefs.length)
throw new Error("Unable to find component named '" + name + "'");
return cmpDefs.map(getBindings).reduce(unnestR, []);
}
// Given a directive definition, find its object input attributes
// Use different properties, depending on the type of directive (component, bindToController, normal)
var getBindings = function (def) {
if (isObject(def.bindToController))
return scopeBindings(def.bindToController);
return scopeBindings(def.scope);
};
// for ng 1.2 style, process the scope: { input: "=foo" }
// for ng 1.3 through ng 1.5, process the component's bindToController: { input: "=foo" } object
var scopeBindings = function (bindingsObj) { return Object.keys(bindingsObj || {})
.map(function (key) { return [key, /^([=<@&])[?]?(.*)/.exec(bindingsObj[key])]; })
.filter(function (tuple) { return isDefined(tuple) && isArray(tuple[1]); })
.map(function (tuple) { return ({ name: tuple[1][2] || tuple[0], type: tuple[1][1] }); }); };
//# sourceMappingURL=templateFactory.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,157 @@
/** @module url */ /** */
import { UIRouter, UrlRouter, LocationServices, $InjectorLike, UrlRuleHandlerFn, UrlMatcher, IInjectable } from "@uirouter/core";
export interface RawNg1RuleFunction {
($injector: $InjectorLike, $location: LocationServices): string | void;
}
/**
* Manages rules for client-side URL
*
* ### Deprecation warning:
* This class is now considered to be an internal API
* Use the [[UrlService]] instead.
* For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].
*
* This class manages the router rules for what to do when the URL changes.
*
* This provider remains for backwards compatibility.
*
* @deprecated
*/
export declare class UrlRouterProvider {
/** @hidden */ _router: UIRouter;
/** @hidden */ _urlRouter: UrlRouter;
/** @hidden */
constructor(router: UIRouter);
/** @hidden */
$get(): UrlRouter;
/**
* Registers a url handler function.
*
* Registers a low level url handler (a `rule`).
* A rule detects specific URL patterns and returns a redirect, or performs some action.
*
* If a rule returns a string, the URL is replaced with the string, and all rules are fired again.
*
* #### Example:
* ```js
* 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;
* }
* });
* });
* ```
*
* @param ruleFn
* Handler function that takes `$injector` and `$location` services as arguments.
* You can use them to detect a url and return a different url as a string.
*
* @return [[UrlRouterProvider]] (`this`)
*/
rule(ruleFn: RawNg1RuleFunction): UrlRouterProvider;
/**
* Defines the path or behavior to use when no url can be matched.
*
* #### Example:
* ```js
* 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) {
* return '/a/valid/url';
* });
* });
* ```
*
* @param rule
* The url path you want to redirect to or a function rule that returns the url path or performs a `$state.go()`.
* The function version is passed two params: `$injector` and `$location` services, and should return a url string.
*
* @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
*/
otherwise(rule: string | RawNg1RuleFunction): UrlRouterProvider;
/**
* Registers a handler for a given url matching.
*
* If the handler is a string, it is
* treated as a redirect, and is interpolated according to the syntax 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:
* ```js
* 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);
* }
* });
* });
* ```
*
* @param what A pattern string to match, compiled as a [[UrlMatcher]].
* @param handler The path (or function that returns a path) that you want to redirect your user to.
* @param ruleCallback [optional] A callback that receives the `rule` registered with [[UrlMatcher.rule]]
*
* Note: the handler may also invoke arbitrary code, such as `$state.go()`
*/
when(what: (RegExp | UrlMatcher | string), handler: string | IInjectable): this;
static injectableHandler(router: UIRouter, handler: any): UrlRuleHandlerFn;
/**
* Disables monitoring of the URL.
*
* Call this method before UI-Router has bootstrapped.
* It will stop UI-Router from performing the initial url sync.
*
* This can be useful to perform some asynchronous initialization before the router starts.
* Once the initialization is complete, call [[listen]] to tell UI-Router to start watching and synchronizing the URL.
*
* #### Example:
* ```js
* var app = angular.module('app', ['ui.router']);
*
* app.config(function ($urlRouterProvider) {
* // Prevent $urlRouter from automatically intercepting URL changes;
* $urlRouterProvider.deferIntercept();
* })
*
* app.run(function (MyService, $urlRouter, $http) {
* $http.get("/stuff").then(function(resp) {
* MyService.doStuff(resp.data);
* $urlRouter.listen();
* $urlRouter.sync();
* });
* });
* ```
*
* @param defer Indicates whether to defer location change interception.
* Passing no parameter is equivalent to `true`.
*/
deferIntercept(defer?: boolean): void;
}

View file

@ -0,0 +1,204 @@
/** @module url */ /** */
import { BaseUrlRule } from "@uirouter/core";
import { services, isString, isFunction, isArray, identity } from "@uirouter/core";
/**
* Manages rules for client-side URL
*
* ### Deprecation warning:
* This class is now considered to be an internal API
* Use the [[UrlService]] instead.
* For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].
*
* This class manages the router rules for what to do when the URL changes.
*
* This provider remains for backwards compatibility.
*
* @deprecated
*/
var UrlRouterProvider = /** @class */ (function () {
/** @hidden */
function UrlRouterProvider(router) {
this._router = router;
this._urlRouter = router.urlRouter;
}
/** @hidden */
UrlRouterProvider.prototype.$get = function () {
var urlRouter = this._urlRouter;
urlRouter.update(true);
if (!urlRouter.interceptDeferred)
urlRouter.listen();
return urlRouter;
};
/**
* Registers a url handler function.
*
* Registers a low level url handler (a `rule`).
* A rule detects specific URL patterns and returns a redirect, or performs some action.
*
* If a rule returns a string, the URL is replaced with the string, and all rules are fired again.
*
* #### Example:
* ```js
* 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;
* }
* });
* });
* ```
*
* @param ruleFn
* Handler function that takes `$injector` and `$location` services as arguments.
* You can use them to detect a url and return a different url as a string.
*
* @return [[UrlRouterProvider]] (`this`)
*/
UrlRouterProvider.prototype.rule = function (ruleFn) {
var _this = this;
if (!isFunction(ruleFn))
throw new Error("'rule' must be a function");
var match = function () {
return ruleFn(services.$injector, _this._router.locationService);
};
var rule = new BaseUrlRule(match, identity);
this._urlRouter.rule(rule);
return this;
};
;
/**
* Defines the path or behavior to use when no url can be matched.
*
* #### Example:
* ```js
* 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) {
* return '/a/valid/url';
* });
* });
* ```
*
* @param rule
* The url path you want to redirect to or a function rule that returns the url path or performs a `$state.go()`.
* The function version is passed two params: `$injector` and `$location` services, and should return a url string.
*
* @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
*/
UrlRouterProvider.prototype.otherwise = function (rule) {
var _this = this;
var urlRouter = this._urlRouter;
if (isString(rule)) {
urlRouter.otherwise(rule);
}
else if (isFunction(rule)) {
urlRouter.otherwise(function () { return rule(services.$injector, _this._router.locationService); });
}
else {
throw new Error("'rule' must be a string or function");
}
return this;
};
;
/**
* Registers a handler for a given url matching.
*
* If the handler is a string, it is
* treated as a redirect, and is interpolated according to the syntax 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:
* ```js
* 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);
* }
* });
* });
* ```
*
* @param what A pattern string to match, compiled as a [[UrlMatcher]].
* @param handler The path (or function that returns a path) that you want to redirect your user to.
* @param ruleCallback [optional] A callback that receives the `rule` registered with [[UrlMatcher.rule]]
*
* Note: the handler may also invoke arbitrary code, such as `$state.go()`
*/
UrlRouterProvider.prototype.when = function (what, handler) {
if (isArray(handler) || isFunction(handler)) {
handler = UrlRouterProvider.injectableHandler(this._router, handler);
}
this._urlRouter.when(what, handler);
return this;
};
;
UrlRouterProvider.injectableHandler = function (router, handler) {
return function (match) {
return services.$injector.invoke(handler, null, { $match: match, $stateParams: router.globals.params });
};
};
/**
* Disables monitoring of the URL.
*
* Call this method before UI-Router has bootstrapped.
* It will stop UI-Router from performing the initial url sync.
*
* This can be useful to perform some asynchronous initialization before the router starts.
* Once the initialization is complete, call [[listen]] to tell UI-Router to start watching and synchronizing the URL.
*
* #### Example:
* ```js
* var app = angular.module('app', ['ui.router']);
*
* app.config(function ($urlRouterProvider) {
* // Prevent $urlRouter from automatically intercepting URL changes;
* $urlRouterProvider.deferIntercept();
* })
*
* app.run(function (MyService, $urlRouter, $http) {
* $http.get("/stuff").then(function(resp) {
* MyService.doStuff(resp.data);
* $urlRouter.listen();
* $urlRouter.sync();
* });
* });
* ```
*
* @param defer Indicates whether to defer location change interception.
* Passing no parameter is equivalent to `true`.
*/
UrlRouterProvider.prototype.deferIntercept = function (defer) {
this._urlRouter.deferIntercept(defer);
};
;
return UrlRouterProvider;
}());
export { UrlRouterProvider };
//# sourceMappingURL=urlRouterProvider.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,9 @@
export interface UIViewScrollProvider {
/**
* Uses standard anchorScroll behavior
*
* Reverts [[$uiViewScroll]] back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
* service for scrolling based on the url anchor.
*/
useAnchorScroll(): void;
}

View file

@ -0,0 +1,21 @@
/** @module ng1 */ /** */
import { ng as angular } from "./angular";
/** @hidden */
function $ViewScrollProvider() {
var useAnchorScroll = false;
this.useAnchorScroll = function () {
useAnchorScroll = true;
};
this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
if (useAnchorScroll) {
return $anchorScroll;
}
return function ($element) {
return $timeout(function () {
$element[0].scrollIntoView();
}, 0, false);
};
}];
}
angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
//# sourceMappingURL=viewScroll.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "viewScroll.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/viewScroll.ts"
],
"names": [],
"mappings": "AAAA,kBAAkB,CAAC,MAAM;AACzB,OAAO,EAAE,EAAE,IAAI,OAAO,EAAE,MAAM,WAAW,CAAC;AAgB1C,cAAc;AACd;IAEE,IAAI,eAAe,GAAG,KAAK,CAAC;IAE5B,IAAI,CAAC,eAAe,GAAG;QACrB,eAAe,GAAG,IAAI,CAAC;IACzB,CAAC,CAAC;IAEF,IAAI,CAAC,IAAI,GAAG,CAAC,eAAe,EAAE,UAAU,EAAE,UAAU,aAAmC,EAAE,QAAyB;YAChH,EAAE,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC;gBACpB,MAAM,CAAC,aAAa,CAAC;YACvB,CAAC;YAED,MAAM,CAAC,UAAU,QAAgB;gBAC/B,MAAM,CAAC,QAAQ,CAAC;oBACd,QAAQ,CAAC,CAAC,CAAC,CAAC,cAAc,EAAE,CAAC;gBAC/B,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;YACf,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,OAAO,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC,QAAQ,CAAC,eAAe,EAA4B,mBAAmB,CAAC,CAAC",
"sourcesContent": [
"/** @module ng1 */ /** */\nimport { ng as angular } from \"./angular\";\nimport { IServiceProviderFactory } from \"angular\";\nimport IAnchorScrollService = angular.IAnchorScrollService;\nimport ITimeoutService = angular.ITimeoutService;\n\nexport interface UIViewScrollProvider {\n /**\n * Uses standard anchorScroll behavior\n *\n * Reverts [[$uiViewScroll]] back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\n * service for scrolling based on the url anchor.\n */\n useAnchorScroll(): void;\n}\n\n\n/** @hidden */\nfunction $ViewScrollProvider() {\n\n var useAnchorScroll = false;\n\n this.useAnchorScroll = function () {\n useAnchorScroll = true;\n };\n\n this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll: IAnchorScrollService, $timeout: ITimeoutService): Function {\n if (useAnchorScroll) {\n return $anchorScroll;\n }\n\n return function ($element: JQuery) {\n return $timeout(function () {\n $element[0].scrollIntoView();\n }, 0, false);\n };\n }];\n}\n\nangular.module('ui.router.state').provider('$uiViewScroll', <IServiceProviderFactory> $ViewScrollProvider);\n"
]
}

View file

@ -0,0 +1 @@
export declare const ng: any;

View file

@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ng_from_import = require("angular");
var ng_from_global = angular;
exports.ng = (ng_from_import && ng_from_import.module) ? ng_from_import : ng_from_global;
//# sourceMappingURL=angular.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "angular.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/angular.ts"
],
"names": [],
"mappings": ";;AAKA,wCAA0C;AAC1C,IAAI,cAAc,GAAG,OAAO,CAAC;AAEhB,QAAA,EAAE,GAAG,CAAC,cAAc,IAAI,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC",
"sourcesContent": [
"/**\n * @hidden\n * @module ng1\n */ /** */\ndeclare var angular;\nimport * as ng_from_import from \"angular\";\nlet ng_from_global = angular;\n\nexport const ng = (ng_from_import && ng_from_import.module) ? ng_from_import : ng_from_global;\n"
]
}

View file

@ -0,0 +1,3 @@
/** @hidden Used for typedoc */
export interface ng1_directive {
}

View file

@ -0,0 +1,571 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* # Angular 1 Directives
*
* These are the directives included in UI-Router for Angular 1.
* These directives are used in templates to create viewports and link/navigate to states.
*
* @ng1api
* @preferred
* @module directives
*/ /** for typedoc */
var angular_1 = require("../angular");
var core_1 = require("@uirouter/core");
/** @hidden */
function parseStateRef(ref) {
var paramsOnly = ref.match(/^\s*({[^}]*})\s*$/), parsed;
if (paramsOnly)
ref = '(' + paramsOnly[1] + ')';
parsed = ref.replace(/\n/g, " ").match(/^\s*([^(]*?)\s*(\((.*)\))?\s*$/);
if (!parsed || parsed.length !== 4)
throw new Error("Invalid state ref '" + ref + "'");
return { state: parsed[1] || null, paramExpr: parsed[3] || null };
}
/** @hidden */
function stateContext(el) {
var $uiView = el.parent().inheritedData('$uiView');
var path = core_1.parse('$cfg.path')($uiView);
return path ? core_1.tail(path).state.name : undefined;
}
/** @hidden */
function processedDef($state, $element, def) {
var uiState = def.uiState || $state.current.name;
var uiStateOpts = core_1.extend(defaultOpts($element, $state), def.uiStateOpts || {});
var href = $state.href(uiState, def.uiStateParams, uiStateOpts);
return { uiState: uiState, uiStateParams: def.uiStateParams, uiStateOpts: uiStateOpts, href: href };
}
/** @hidden */
function getTypeInfo(el) {
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';
var isForm = el[0].nodeName === "FORM";
return {
attr: isForm ? "action" : (isSvg ? 'xlink:href' : 'href'),
isAnchor: el.prop("tagName").toUpperCase() === "A",
clickable: !isForm
};
}
/** @hidden */
function clickHook(el, $state, $timeout, type, getDef) {
return function (e) {
var button = e.which || e.button, target = getDef();
if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {
// HACK: This is to allow ng-clicks to be processed before the transition is initiated:
var transition = $timeout(function () {
$state.go(target.uiState, target.uiStateParams, target.uiStateOpts);
});
e.preventDefault();
// if the state has no URL, ignore one preventDefault from the <a> directive.
var ignorePreventDefaultCount = type.isAnchor && !target.href ? 1 : 0;
e.preventDefault = function () {
if (ignorePreventDefaultCount-- <= 0)
$timeout.cancel(transition);
};
}
};
}
/** @hidden */
function defaultOpts(el, $state) {
return {
relative: stateContext(el) || $state.$current,
inherit: true,
source: "sref"
};
}
/** @hidden */
function bindEvents(element, scope, hookFn, uiStateOpts) {
var events;
if (uiStateOpts) {
events = uiStateOpts.events;
}
if (!core_1.isArray(events)) {
events = ['click'];
}
var on = element.on ? 'on' : 'bind';
for (var _i = 0, events_1 = events; _i < events_1.length; _i++) {
var event_1 = events_1[_i];
element[on](event_1, hookFn);
}
scope.$on('$destroy', function () {
var off = element.off ? 'off' : 'unbind';
for (var _i = 0, events_2 = events; _i < events_2.length; _i++) {
var event_2 = events_2[_i];
element[off](event_2, hookFn);
}
});
}
/**
* `ui-sref`: A directive for linking to a state
*
* A directive which links to a state (and optionally, parameters).
* When clicked, this directive activates the linked state with the supplied parameter values.
*
* ### Linked State
* The attribute value of the `ui-sref` is the name of the state to link to.
*
* #### Example:
* This will activate the `home` state when the link is clicked.
* ```html
* <a ui-sref="home">Home</a>
* ```
*
* ### Relative Links
* You can also use relative state paths within `ui-sref`, just like a relative path passed to `$state.go()` ([[StateService.go]]).
* You just need to be aware that the path is relative to the state that *created* the link.
* This allows a state to create a relative `ui-sref` which always targets the same destination.
*
* #### Example:
* Both these links are relative to the parent state, even when a child state is currently active.
* ```html
* <a ui-sref=".child1">child 1 state</a>
* <a ui-sref=".child2">child 2 state</a>
* ```
*
* This link activates the parent state.
* ```html
* <a ui-sref="^">Return</a>
* ```
*
* ### hrefs
* If the linked state has a URL, the directive will automatically generate and
* update the `href` attribute (using the [[StateService.href]] method).
*
* #### Example:
* Assuming the `users` state has a url of `/users/`
* ```html
* <a ui-sref="users" href="/users/">Users</a>
* ```
*
* ### Parameter Values
* In addition to the state name, a `ui-sref` can include parameter values which are applied when activating the state.
* Param values can be provided in the `ui-sref` value after the state name, enclosed by parentheses.
* The content inside the parentheses is an expression, evaluated to the parameter values.
*
* #### Example:
* This example renders a list of links to users.
* The state's `userId` parameter value comes from each user's `user.id` property.
* ```html
* <li ng-repeat="user in users">
* <a ui-sref="users.detail({ userId: user.id })">{{ user.displayName }}</a>
* </li>
* ```
*
* Note:
* The parameter values expression is `$watch`ed for updates.
*
* ### Transition Options
* You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-sref-opts` attribute.
* Options are restricted to `location`, `inherit`, and `reload`.
*
* #### Example:
* ```html
* <a ui-sref="home" ui-sref-opts="{ reload: true }">Home</a>
* ```
*
* ### Other DOM Events
*
* You can also customize which DOM events to respond to (instead of `click`) by
* providing an `events` array in the `ui-sref-opts` attribute.
*
* #### Example:
* ```html
* <input type="text" ui-sref="contacts" ui-sref-opts="{ events: ['change', 'blur'] }">
* ```
*
* ### Highlighting the active link
* This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.
*
* ### Examples
* If you have the following template:
*
* ```html
* <a ui-sref="home">Home</a>
* <a ui-sref="about">About</a>
* <a ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
* </li>
* </ul>
* ```
*
* Then (assuming the current state is `contacts`) the rendered html including hrefs would be:
*
* ```html
* <a href="#/home" ui-sref="home">Home</a>
* <a href="#/about" ui-sref="about">About</a>
* <a href="#/contacts?page=2" ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
* </li>
* </ul>
*
* <a href="#/home" ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
* ```
*
* ### Notes
*
* - You can use `ui-sref` to change **only the parameter values** by omitting the state name and parentheses.
* #### Example:
* Sets the `lang` parameter to `en` and remains on the same state.
*
* ```html
* <a ui-sref="{ lang: 'en' }">English</a>
* ```
*
* - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.
*
* - Unlike the parameter values expression, the state name is not `$watch`ed (for performance reasons).
* If you need to dynamically update the state being linked to, use the fully dynamic [[uiState]] directive.
*/
var uiSref;
uiSref = ['$uiRouter', '$timeout',
function $StateRefDirective($uiRouter, $timeout) {
var $state = $uiRouter.stateService;
return {
restrict: 'A',
require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
link: function (scope, element, attrs, uiSrefActive) {
var type = getTypeInfo(element);
var active = uiSrefActive[1] || uiSrefActive[0];
var unlinkInfoFn = null;
var hookFn;
var rawDef = {};
var getDef = function () { return processedDef($state, element, rawDef); };
var ref = parseStateRef(attrs.uiSref);
rawDef.uiState = ref.state;
rawDef.uiStateOpts = attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {};
function update() {
var def = getDef();
if (unlinkInfoFn)
unlinkInfoFn();
if (active)
unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);
if (def.href != null)
attrs.$set(type.attr, def.href);
}
if (ref.paramExpr) {
scope.$watch(ref.paramExpr, function (val) {
rawDef.uiStateParams = core_1.extend({}, val);
update();
}, true);
rawDef.uiStateParams = core_1.extend({}, scope.$eval(ref.paramExpr));
}
update();
scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));
scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));
if (!type.clickable)
return;
hookFn = clickHook(element, $state, $timeout, type, getDef);
bindEvents(element, scope, hookFn, rawDef.uiStateOpts);
}
};
}];
/**
* `ui-state`: A fully dynamic directive for linking to a state
*
* A directive which links to a state (and optionally, parameters).
* When clicked, this directive activates the linked state with the supplied parameter values.
*
* **This directive is very similar to [[uiSref]], but it `$observe`s and `$watch`es/evaluates all its inputs.**
*
* A directive which links to a state (and optionally, parameters).
* When clicked, this directive activates the linked state with the supplied parameter values.
*
* ### Linked State
* The attribute value of `ui-state` is an expression which is `$watch`ed and evaluated as the state to link to.
* **This is in contrast with `ui-sref`, which takes a state name as a string literal.**
*
* #### Example:
* Create a list of links.
* ```html
* <li ng-repeat="link in navlinks">
* <a ui-state="link.state">{{ link.displayName }}</a>
* </li>
* ```
*
* ### Relative Links
* If the expression evaluates to a relative path, it is processed like [[uiSref]].
* You just need to be aware that the path is relative to the state that *created* the link.
* This allows a state to create relative `ui-state` which always targets the same destination.
*
* ### hrefs
* If the linked state has a URL, the directive will automatically generate and
* update the `href` attribute (using the [[StateService.href]] method).
*
* ### Parameter Values
* In addition to the state name expression, a `ui-state` can include parameter values which are applied when activating the state.
* Param values should be provided using the `ui-state-params` attribute.
* The `ui-state-params` attribute value is `$watch`ed and evaluated as an expression.
*
* #### Example:
* This example renders a list of links with param values.
* The state's `userId` parameter value comes from each user's `user.id` property.
* ```html
* <li ng-repeat="link in navlinks">
* <a ui-state="link.state" ui-state-params="link.params">{{ link.displayName }}</a>
* </li>
* ```
*
* ### Transition Options
* You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-state-opts` attribute.
* Options are restricted to `location`, `inherit`, and `reload`.
* The value of the `ui-state-opts` is `$watch`ed and evaluated as an expression.
*
* #### Example:
* ```html
* <a ui-state="returnto.state" ui-state-opts="{ reload: true }">Home</a>
* ```
*
* ### Other DOM Events
*
* You can also customize which DOM events to respond to (instead of `click`) by
* providing an `events` array in the `ui-state-opts` attribute.
*
* #### Example:
* ```html
* <input type="text" ui-state="contacts" ui-state-opts="{ events: ['change', 'blur'] }">
* ```
*
* ### Highlighting the active link
* This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.
*
* ### Notes
*
* - You can use `ui-params` to change **only the parameter values** by omitting the state name and supplying only `ui-state-params`.
* However, it might be simpler to use [[uiSref]] parameter-only links.
*
* #### Example:
* Sets the `lang` parameter to `en` and remains on the same state.
*
* ```html
* <a ui-state="" ui-state-params="{ lang: 'en' }">English</a>
* ```
*
* - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.
* ```
*/
var uiState;
uiState = ['$uiRouter', '$timeout',
function $StateRefDynamicDirective($uiRouter, $timeout) {
var $state = $uiRouter.stateService;
return {
restrict: 'A',
require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
link: function (scope, element, attrs, uiSrefActive) {
var type = getTypeInfo(element);
var active = uiSrefActive[1] || uiSrefActive[0];
var unlinkInfoFn = null;
var hookFn;
var rawDef = {};
var getDef = function () { return processedDef($state, element, rawDef); };
var inputAttrs = ['uiState', 'uiStateParams', 'uiStateOpts'];
var watchDeregFns = inputAttrs.reduce(function (acc, attr) { return (acc[attr] = core_1.noop, acc); }, {});
function update() {
var def = getDef();
if (unlinkInfoFn)
unlinkInfoFn();
if (active)
unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);
if (def.href != null)
attrs.$set(type.attr, def.href);
}
inputAttrs.forEach(function (field) {
rawDef[field] = attrs[field] ? scope.$eval(attrs[field]) : null;
attrs.$observe(field, function (expr) {
watchDeregFns[field]();
watchDeregFns[field] = scope.$watch(expr, function (newval) {
rawDef[field] = newval;
update();
}, true);
});
});
update();
scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));
scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));
if (!type.clickable)
return;
hookFn = clickHook(element, $state, $timeout, type, getDef);
bindEvents(element, scope, hookFn, rawDef.uiStateOpts);
}
};
}];
/**
* `ui-sref-active` and `ui-sref-active-eq`: A directive that adds a CSS class when a `ui-sref` is active
*
* A directive working alongside [[uiSref]] and [[uiState]] to add classes to an element when the
* related directive's state is active (and remove them when it is inactive).
*
* The primary use-case is to highlight the active link in navigation menus,
* distinguishing it from the inactive menu items.
*
* ### Linking to a `ui-sref` or `ui-state`
* `ui-sref-active` can live on the same element as `ui-sref`/`ui-state`, or it can be on a parent element.
* If a `ui-sref-active` is a parent to more than one `ui-sref`/`ui-state`, it will apply the CSS class when **any of the links are active**.
*
* ### Matching
*
* The `ui-sref-active` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state **or any child state is active**.
* This is a "fuzzy match" which uses [[StateService.includes]].
*
* The `ui-sref-active-eq` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state is directly active (not when child states are active).
* This is an "exact match" which uses [[StateService.is]].
*
* ### Parameter values
* If the `ui-sref`/`ui-state` includes parameter values, the current parameter values must match the link's values for the link to be highlighted.
* This allows a list of links to the same state with different parameters to be rendered, and the correct one highlighted.
*
* #### Example:
* ```html
* <li ng-repeat="user in users" ui-sref-active="active">
* <a ui-sref="user.details({ userId: user.id })">{{ user.lastName }}</a>
* </li>
* ```
*
* ### Examples
*
* Given the following template:
* #### Example:
* ```html
* <ul>
* <li ui-sref-active="active" class="item">
* <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
* </li>
* </ul>
* ```
*
* When the app state is `app.user` (or any child state),
* and contains the state parameter "user" with value "bilbobaggins",
* the resulting HTML will appear as (note the 'active' class):
*
* ```html
* <ul>
* <li ui-sref-active="active" class="item active">
* <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
* </li>
* </ul>
* ```
*
* ### Glob mode
*
* It is possible to pass `ui-sref-active` an expression that evaluates to an object.
* The objects keys represent active class names and values represent the respective state names/globs.
* `ui-sref-active` will match if the current active state **includes** any of
* the specified state names/globs, even the abstract ones.
*
* #### Example:
* Given the following template, with "admin" being an abstract state:
* ```html
* <div ui-sref-active="{'active': 'admin.**'}">
* <a ui-sref-active="active" ui-sref="admin.roles">Roles</a>
* </div>
* ```
*
* When the current state is "admin.roles" the "active" class will be applied to both the <div> and <a> elements.
* It is important to note that the state names/globs passed to `ui-sref-active` override any state provided by a linked `ui-sref`.
*
* ### Notes:
*
* - The class name is interpolated **once** during the directives link time (any further changes to the
* interpolated value are ignored).
*
* - Multiple classes may be specified in a space-separated format: `ui-sref-active='class1 class2 class3'`
*/
var uiSrefActive;
uiSrefActive = ['$state', '$stateParams', '$interpolate', '$uiRouter',
function $StateRefActiveDirective($state, $stateParams, $interpolate, $uiRouter) {
return {
restrict: "A",
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
var states = [], activeEqClass, uiSrefActive;
// There probably isn't much point in $observing this
// uiSrefActive and uiSrefActiveEq share the same directive object with some
// slight difference in logic routing
activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);
try {
uiSrefActive = $scope.$eval($attrs.uiSrefActive);
}
catch (e) {
// Do nothing. uiSrefActive is not a valid expression.
// Fall back to using $interpolate below
}
uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);
if (core_1.isObject(uiSrefActive)) {
core_1.forEach(uiSrefActive, function (stateOrName, activeClass) {
if (core_1.isString(stateOrName)) {
var ref = parseStateRef(stateOrName);
addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);
}
});
}
// Allow uiSref to communicate with uiSrefActive[Equals]
this.$$addStateInfo = function (newState, newParams) {
// we already got an explicit state provided by ui-sref-active, so we
// shadow the one that comes from ui-sref
if (core_1.isObject(uiSrefActive) && states.length > 0) {
return;
}
var deregister = addState(newState, newParams, uiSrefActive);
update();
return deregister;
};
function updateAfterTransition(trans) {
trans.promise.then(update, core_1.noop);
}
$scope.$on('$stateChangeSuccess', update);
$scope.$on('$destroy', $uiRouter.transitionService.onStart({}, updateAfterTransition));
if ($uiRouter.globals.transition) {
updateAfterTransition($uiRouter.globals.transition);
}
function addState(stateName, stateParams, activeClass) {
var state = $state.get(stateName, stateContext($element));
var stateInfo = {
state: state || { name: stateName },
params: stateParams,
activeClass: activeClass
};
states.push(stateInfo);
return function removeState() {
core_1.removeFrom(states)(stateInfo);
};
}
// Update route state
function update() {
var splitClasses = function (str) {
return str.split(/\s/).filter(core_1.identity);
};
var getClasses = function (stateList) {
return stateList.map(function (x) { return x.activeClass; }).map(splitClasses).reduce(core_1.unnestR, []);
};
var allClasses = getClasses(states).concat(splitClasses(activeEqClass)).reduce(core_1.uniqR, []);
var fuzzyClasses = getClasses(states.filter(function (x) { return $state.includes(x.state.name, x.params); }));
var exactlyMatchesAny = !!states.filter(function (x) { return $state.is(x.state.name, x.params); }).length;
var exactClasses = exactlyMatchesAny ? splitClasses(activeEqClass) : [];
var addClasses = fuzzyClasses.concat(exactClasses).reduce(core_1.uniqR, []);
var removeClasses = allClasses.filter(function (cls) { return !core_1.inArray(addClasses, cls); });
$scope.$evalAsync(function () {
addClasses.forEach(function (className) { return $element.addClass(className); });
removeClasses.forEach(function (className) { return $element.removeClass(className); });
});
}
update();
}]
};
}];
angular_1.ng.module('ui.router.state')
.directive('uiSref', uiSref)
.directive('uiSrefActive', uiSrefActive)
.directive('uiSrefActiveEq', uiSrefActive)
.directive('uiState', uiState);
//# sourceMappingURL=stateDirectives.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,142 @@
import { ActiveUIView } from "@uirouter/core";
import { Ng1ViewConfig } from "../statebuilders/views";
import { ng1_directive } from "./stateDirectives";
/** @hidden */
export declare type UIViewData = {
$cfg: Ng1ViewConfig;
$uiView: ActiveUIView;
};
/** @hidden */
export declare type UIViewAnimData = {
$animEnter: Promise<any>;
$animLeave: Promise<any>;
$$animLeave: {
resolve: () => any;
};
};
/**
* `ui-view`: A viewport directive which is filled in by a view from the active state.
*
* ### Attributes
*
* - `name`: (Optional) A view name.
* The name should be unique amongst the other views in the same state.
* You can have views of the same name that live in different states.
* The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]).
*
* - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated.
* Uses [[$uiViewScroll]] to do the scrolling.
*
* - `onload`: Expression to evaluate whenever the view updates.
*
* #### Example:
* A view can be unnamed or named.
* ```html
* <!-- Unnamed -->
* <div ui-view></div>
*
* <!-- Named -->
* <div ui-view="viewName"></div>
*
* <!-- Named (different style) -->
* <ui-view name="viewName"></ui-view>
* ```
*
* You can only have one unnamed view within any template (or root html). If you are only using a
* single view and it is unnamed then you can populate it like so:
*
* ```html
* <div ui-view></div>
* $stateProvider.state("home", {
* template: "<h1>HELLO!</h1>"
* })
* ```
*
* The above is a convenient shortcut equivalent to specifying your view explicitly with the
* [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name:
*
* ```js
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* ```
*
* But typically you'll only use the views property if you name your view or have more than one view
* in the same template. There's not really a compelling reason to name a view if its the only one,
* but you could if you wanted, like so:
*
* ```html
* <div ui-view="main"></div>
* ```
*
* ```js
* $stateProvider.state("home", {
* views: {
* "main": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* ```
*
* Really though, you'll use views to set up multiple views:
*
* ```html
* <div ui-view></div>
* <div ui-view="chart"></div>
* <div ui-view="data"></div>
* ```
*
* ```js
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* },
* "chart": {
* template: "<chart_thing/>"
* },
* "data": {
* template: "<data_thing/>"
* }
* }
* })
* ```
*
* #### Examples for `autoscroll`:
* ```html
* <!-- If autoscroll present with no expression,
* then scroll ui-view into view -->
* <ui-view autoscroll/>
*
* <!-- If autoscroll present with valid expression,
* then scroll ui-view into view if expression evaluates to true -->
* <ui-view autoscroll='true'/>
* <ui-view autoscroll='false'/>
* <ui-view autoscroll='scopeVariable'/>
* ```
*
* Resolve data:
*
* The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this
* can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template.
*
* Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the
* controller is instantiated. The `$onInit()` hook can be used to perform initialization code which
* depends on `$resolve` data.
*
* #### Example:
* ```js
* $stateProvider.state('home', {
* template: '<my-component user="$resolve.user"></my-component>',
* resolve: {
* user: function(UserService) { return UserService.fetchUser(); }
* }
* });
* ```
*/
export declare let uiView: ng1_directive;

View file

@ -0,0 +1,290 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @ng1api
* @module directives
*/ /** for typedoc */
var angular_1 = require("../angular");
var angular_2 = require("angular");
var core_1 = require("@uirouter/core");
var views_1 = require("../statebuilders/views");
var services_1 = require("../services");
exports.uiView = ['$view', '$animate', '$uiViewScroll', '$interpolate', '$q',
function $ViewDirective($view, $animate, $uiViewScroll, $interpolate, $q) {
function getRenderer(attrs, scope) {
return {
enter: function (element, target, cb) {
if (angular_1.ng.version.minor > 2) {
$animate.enter(element, null, target).then(cb);
}
else {
$animate.enter(element, null, target, cb);
}
},
leave: function (element, cb) {
if (angular_1.ng.version.minor > 2) {
$animate.leave(element).then(cb);
}
else {
$animate.leave(element, cb);
}
}
};
}
function configsEqual(config1, config2) {
return config1 === config2;
}
var rootData = {
$cfg: { viewDecl: { $context: $view._pluginapi._rootViewContext() } },
$uiView: {}
};
var directive = {
count: 0,
restrict: 'ECA',
terminal: true,
priority: 400,
transclude: 'element',
compile: function (tElement, tAttrs, $transclude) {
return function (scope, $element, attrs) {
var previousEl, currentEl, currentScope, unregister, onloadExp = attrs['onload'] || '', autoScrollExp = attrs['autoscroll'], renderer = getRenderer(attrs, scope), viewConfig = undefined, inherited = $element.inheritedData('$uiView') || rootData, name = $interpolate(attrs['uiView'] || attrs['name'] || '')(scope) || '$default';
var activeUIView = {
$type: 'ng1',
id: directive.count++,
name: name,
fqn: inherited.$uiView.fqn ? inherited.$uiView.fqn + "." + name : name,
config: null,
configUpdated: configUpdatedCallback,
get creationContext() {
var fromParentTagConfig = core_1.parse('$cfg.viewDecl.$context')(inherited);
// Allow <ui-view name="foo"><ui-view name="bar"></ui-view></ui-view>
// See https://github.com/angular-ui/ui-router/issues/3355
var fromParentTag = core_1.parse('$uiView.creationContext')(inherited);
return fromParentTagConfig || fromParentTag;
}
};
core_1.trace.traceUIViewEvent("Linking", activeUIView);
function configUpdatedCallback(config) {
if (config && !(config instanceof views_1.Ng1ViewConfig))
return;
if (configsEqual(viewConfig, config))
return;
core_1.trace.traceUIViewConfigUpdated(activeUIView, config && config.viewDecl && config.viewDecl.$context);
viewConfig = config;
updateView(config);
}
$element.data('$uiView', { $uiView: activeUIView });
updateView();
unregister = $view.registerUIView(activeUIView);
scope.$on("$destroy", function () {
core_1.trace.traceUIViewEvent("Destroying/Unregistering", activeUIView);
unregister();
});
function cleanupLastView() {
if (previousEl) {
core_1.trace.traceUIViewEvent("Removing (previous) el", previousEl.data('$uiView'));
previousEl.remove();
previousEl = null;
}
if (currentScope) {
core_1.trace.traceUIViewEvent("Destroying scope", activeUIView);
currentScope.$destroy();
currentScope = null;
}
if (currentEl) {
var _viewData_1 = currentEl.data('$uiViewAnim');
core_1.trace.traceUIViewEvent("Animate out", _viewData_1);
renderer.leave(currentEl, function () {
_viewData_1.$$animLeave.resolve();
previousEl = null;
});
previousEl = currentEl;
currentEl = null;
}
}
function updateView(config) {
var newScope = scope.$new();
var animEnter = $q.defer(), animLeave = $q.defer();
var $uiViewData = {
$cfg: config,
$uiView: activeUIView,
};
var $uiViewAnim = {
$animEnter: animEnter.promise,
$animLeave: animLeave.promise,
$$animLeave: animLeave
};
/**
* @ngdoc event
* @name ui.router.state.directive:ui-view#$viewContentLoading
* @eventOf ui.router.state.directive:ui-view
* @eventType emits on ui-view directive scope
* @description
*
* Fired once the view **begins loading**, *before* the DOM is rendered.
*
* @param {Object} event Event object.
* @param {string} viewName Name of the view.
*/
newScope.$emit('$viewContentLoading', name);
var cloned = $transclude(newScope, function (clone) {
clone.data('$uiViewAnim', $uiViewAnim);
clone.data('$uiView', $uiViewData);
renderer.enter(clone, $element, function onUIViewEnter() {
animEnter.resolve();
if (currentScope)
currentScope.$emit('$viewContentAnimationEnded');
if (core_1.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
$uiViewScroll(clone);
}
});
cleanupLastView();
});
currentEl = cloned;
currentScope = newScope;
/**
* @ngdoc event
* @name ui.router.state.directive:ui-view#$viewContentLoaded
* @eventOf ui.router.state.directive:ui-view
* @eventType emits on ui-view directive scope
* @description *
* Fired once the view is **loaded**, *after* the DOM is rendered.
*
* @param {Object} event Event object.
*/
currentScope.$emit('$viewContentLoaded', config || viewConfig);
currentScope.$eval(onloadExp);
}
};
}
};
return directive;
}];
$ViewDirectiveFill.$inject = ['$compile', '$controller', '$transitions', '$view', '$q', '$timeout'];
/** @hidden */
function $ViewDirectiveFill($compile, $controller, $transitions, $view, $q, $timeout) {
var getControllerAs = core_1.parse('viewDecl.controllerAs');
var getResolveAs = core_1.parse('viewDecl.resolveAs');
return {
restrict: 'ECA',
priority: -400,
compile: function (tElement) {
var initial = tElement.html();
tElement.empty();
return function (scope, $element) {
var data = $element.data('$uiView');
if (!data) {
$element.html(initial);
$compile($element.contents())(scope);
return;
}
var cfg = data.$cfg || { viewDecl: {}, getTemplate: angular_2.noop };
var resolveCtx = cfg.path && new core_1.ResolveContext(cfg.path);
$element.html(cfg.getTemplate($element, resolveCtx) || initial);
core_1.trace.traceUIViewFill(data.$uiView, $element.html());
var link = $compile($element.contents());
var controller = cfg.controller;
var controllerAs = getControllerAs(cfg);
var resolveAs = getResolveAs(cfg);
var locals = resolveCtx && services_1.getLocals(resolveCtx);
scope[resolveAs] = locals;
if (controller) {
var controllerInstance = $controller(controller, core_1.extend({}, locals, { $scope: scope, $element: $element }));
if (controllerAs) {
scope[controllerAs] = controllerInstance;
scope[controllerAs][resolveAs] = locals;
}
// TODO: Use $view service as a central point for registering component-level hooks
// Then, when a component is created, tell the $view service, so it can invoke hooks
// $view.componentLoaded(controllerInstance, { $scope: scope, $element: $element });
// scope.$on('$destroy', () => $view.componentUnloaded(controllerInstance, { $scope: scope, $element: $element }));
$element.data('$ngControllerController', controllerInstance);
$element.children().data('$ngControllerController', controllerInstance);
registerControllerCallbacks($q, $transitions, controllerInstance, scope, cfg);
}
// Wait for the component to appear in the DOM
if (core_1.isString(cfg.viewDecl.component)) {
var cmp_1 = cfg.viewDecl.component;
var kebobName = core_1.kebobString(cmp_1);
var tagRegexp_1 = new RegExp("^(x-|data-)?" + kebobName + "$", "i");
var getComponentController = function () {
var directiveEl = [].slice.call($element[0].children)
.filter(function (el) { return el && el.tagName && tagRegexp_1.exec(el.tagName); });
return directiveEl && angular_1.ng.element(directiveEl).data("$" + cmp_1 + "Controller");
};
var deregisterWatch_1 = scope.$watch(getComponentController, function (ctrlInstance) {
if (!ctrlInstance)
return;
registerControllerCallbacks($q, $transitions, ctrlInstance, scope, cfg);
deregisterWatch_1();
});
}
link(scope);
};
}
};
}
/** @hidden */
var hasComponentImpl = typeof angular_1.ng.module('ui.router')['component'] === 'function';
/** @hidden incrementing id */
var _uiCanExitId = 0;
/** @hidden TODO: move these callbacks to $view and/or `/hooks/components.ts` or something */
function registerControllerCallbacks($q, $transitions, controllerInstance, $scope, cfg) {
// Call $onInit() ASAP
if (core_1.isFunction(controllerInstance.$onInit) && !(cfg.viewDecl.component && hasComponentImpl)) {
controllerInstance.$onInit();
}
var viewState = core_1.tail(cfg.path).state.self;
var hookOptions = { bind: controllerInstance };
// Add component-level hook for onParamsChange
if (core_1.isFunction(controllerInstance.uiOnParamsChanged)) {
var resolveContext = new core_1.ResolveContext(cfg.path);
var viewCreationTrans_1 = resolveContext.getResolvable('$transition$').data;
// Fire callback on any successful transition
var paramsUpdated = function ($transition$) {
// Exit early if the $transition$ is the same as the view was created within.
// Exit early if the $transition$ will exit the state the view is for.
if ($transition$ === viewCreationTrans_1 || $transition$.exiting().indexOf(viewState) !== -1)
return;
var toParams = $transition$.params("to");
var fromParams = $transition$.params("from");
var toSchema = $transition$.treeChanges().to.map(function (node) { return node.paramSchema; }).reduce(core_1.unnestR, []);
var fromSchema = $transition$.treeChanges().from.map(function (node) { return node.paramSchema; }).reduce(core_1.unnestR, []);
// Find the to params that have different values than the from params
var changedToParams = toSchema.filter(function (param) {
var idx = fromSchema.indexOf(param);
return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]);
});
// Only trigger callback if a to param has changed or is new
if (changedToParams.length) {
var changedKeys_1 = changedToParams.map(function (x) { return x.id; });
// Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params.
var newValues = core_1.filter(toParams, function (val, key) { return changedKeys_1.indexOf(key) !== -1; });
controllerInstance.uiOnParamsChanged(newValues, $transition$);
}
};
$scope.$on('$destroy', $transitions.onSuccess({}, paramsUpdated, hookOptions));
}
// Add component-level hook for uiCanExit
if (core_1.isFunction(controllerInstance.uiCanExit)) {
var id_1 = _uiCanExitId++;
var cacheProp_1 = '_uiCanExitIds';
// Returns true if a redirect transition already answered truthy
var prevTruthyAnswer_1 = function (trans) {
return !!trans && (trans[cacheProp_1] && trans[cacheProp_1][id_1] === true || prevTruthyAnswer_1(trans.redirectedFrom()));
};
// If a user answered yes, but the transition was later redirected, don't also ask for the new redirect transition
var wrappedHook = function (trans) {
var promise, ids = trans[cacheProp_1] = trans[cacheProp_1] || {};
if (!prevTruthyAnswer_1(trans)) {
promise = $q.when(controllerInstance.uiCanExit(trans));
promise.then(function (val) { return ids[id_1] = (val !== false); });
}
return promise;
};
var criteria = { exiting: viewState.name };
$scope.$on('$destroy', $transitions.onBefore(criteria, wrappedHook, hookOptions));
}
}
angular_1.ng.module('ui.router.state').directive('uiView', exports.uiView);
angular_1.ng.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
//# sourceMappingURL=viewDirective.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,19 @@
/**
* Main entry point for angular 1.x build
* @module ng1
*/ /** */
export * from "./interface";
export * from "./services";
export * from "./statebuilders/views";
export * from "./stateProvider";
export * from "./urlRouterProvider";
import "./injectables";
import "./directives/stateDirectives";
import "./stateFilters";
import "./directives/viewDirective";
import "./viewScroll";
declare const _default: "ui.router";
export default _default;
import * as core from "@uirouter/core";
export { core };
export * from "@uirouter/core";

View file

@ -0,0 +1,23 @@
"use strict";
/**
* Main entry point for angular 1.x build
* @module ng1
*/ /** */
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./services"));
__export(require("./statebuilders/views"));
__export(require("./stateProvider"));
__export(require("./urlRouterProvider"));
require("./injectables");
require("./directives/stateDirectives");
require("./stateFilters");
require("./directives/viewDirective");
require("./viewScroll");
exports.default = "ui.router";
var core = require("@uirouter/core");
exports.core = core;
__export(require("@uirouter/core"));
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "index.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/index.ts"
],
"names": [],
"mappings": ";AAAA;;;GAGG,CAAC,MAAM;;;;;AAGV,gCAA2B;AAC3B,2CAAsC;AACtC,qCAAgC;AAChC,yCAAoC;AAEpC,yBAAuB;AACvB,wCAAsC;AACtC,0BAAwB;AACxB,sCAAoC;AACpC,wBAAsB;AAEtB,kBAAe,WAAW,CAAC;AAE3B,qCAAuC;AAC9B,oBAAI;AACb,oCAA+B",
"sourcesContent": [
"/**\n * Main entry point for angular 1.x build\n * @module ng1\n */ /** */\n\nexport * from \"./interface\";\nexport * from \"./services\";\nexport * from \"./statebuilders/views\";\nexport * from \"./stateProvider\";\nexport * from \"./urlRouterProvider\";\n\nimport \"./injectables\";\nimport \"./directives/stateDirectives\";\nimport \"./stateFilters\";\nimport \"./directives/viewDirective\";\nimport \"./viewScroll\";\n\nexport default \"ui.router\";\n\nimport * as core from \"@uirouter/core\";\nexport { core };\nexport * from \"@uirouter/core\";\n\n"
]
}

View file

@ -0,0 +1,368 @@
"use strict";
/**
* # Angular 1 injectable services
*
* This is a list of the objects which can be injected using angular's injector.
*
* There are three different kind of injectable objects:
*
* ## **Provider** objects
* #### injectable into a `.config()` block during configtime
*
* - [[$uiRouterProvider]]: The UI-Router instance
* - [[$stateProvider]]: State registration
* - [[$transitionsProvider]]: Transition hooks
* - [[$urlServiceProvider]]: All URL related public APIs
*
* - [[$uiViewScrollProvider]]: Disable ui-router view scrolling
* - [[$urlRouterProvider]]: (deprecated) Url matching rules
* - [[$urlMatcherFactoryProvider]]: (deprecated) Url parsing config
*
* ## **Service** objects
* #### injectable globally during runtime
*
* - [[$uiRouter]]: The UI-Router instance
* - [[$trace]]: Enable transition trace/debug
* - [[$transitions]]: Transition hooks
* - [[$state]]: Imperative state related APIs
* - [[$stateRegistry]]: State registration
* - [[$urlService]]: All URL related public APIs
* - [[$uiRouterGlobals]]: Global variables
* - [[$uiViewScroll]]: Scroll an element into view
*
* - [[$stateParams]]: (deprecated) Global state param values
* - [[$urlRouter]]: (deprecated) URL synchronization
* - [[$urlMatcherFactory]]: (deprecated) URL parsing config
*
* ## **Per-Transition** objects
*
* - These kind of objects are injectable into:
* - Resolves ([[Ng1StateDeclaration.resolve]]),
* - Transition Hooks ([[TransitionService.onStart]], etc),
* - Routed Controllers ([[Ng1ViewDeclaration.controller]])
*
* #### Different instances are injected based on the [[Transition]]
*
* - [[$transition$]]: The current Transition object
* - [[$stateParams]]: State param values for pending Transition (deprecated)
* - Any resolve data defined using [[Ng1StateDeclaration.resolve]]
*
* @ng1api
* @preferred
* @module injectables
*/ /** */
Object.defineProperty(exports, "__esModule", { value: true });
/**
* The current (or pending) State Parameters
*
* An injectable global **Service Object** which holds the state parameters for the latest **SUCCESSFUL** transition.
*
* The values are not updated until *after* a `Transition` successfully completes.
*
* **Also:** an injectable **Per-Transition Object** object which holds the pending state parameters for the pending `Transition` currently running.
*
* ### Deprecation warning:
*
* The value injected for `$stateParams` is different depending on where it is injected.
*
* - When injected into an angular service, the object injected is the global **Service Object** with the parameter values for the latest successful `Transition`.
* - When injected into transition hooks, resolves, or view controllers, the object is the **Per-Transition Object** with the parameter values for the running `Transition`.
*
* Because of these confusing details, this service is deprecated.
*
* ### Instead of using the global `$stateParams` service object,
* inject [[$uiRouterGlobals]] and use [[UIRouterGlobals.params]]
*
* ```js
* MyService.$inject = ['$uiRouterGlobals'];
* function MyService($uiRouterGlobals) {
* return {
* paramValues: function () {
* return $uiRouterGlobals.params;
* }
* }
* }
* ```
*
* ### Instead of using the per-transition `$stateParams` object,
* inject the current `Transition` (as [[$transition$]]) and use [[Transition.params]]
*
* ```js
* MyController.$inject = ['$transition$'];
* function MyController($transition$) {
* var username = $transition$.params().username;
* // .. do something with username
* }
* ```
*
* ---
*
* This object can be injected into other services.
*
* #### Deprecated Example:
* ```js
* SomeService.$inject = ['$http', '$stateParams'];
* function SomeService($http, $stateParams) {
* return {
* getUser: function() {
* return $http.get('/api/users/' + $stateParams.username);
* }
* }
* };
* angular.service('SomeService', SomeService);
* ```
* @deprecated
*/
var $stateParams;
/**
* Global UI-Router variables
*
* The router global state as a **Service Object** (injectable during runtime).
*
* This object contains globals such as the current state and current parameter values.
*/
var $uiRouterGlobals;
/**
* The UI-Router instance
*
* The [[UIRouter]] singleton (the router instance) as a **Service Object** (injectable during runtime).
*
* This object is the UI-Router singleton instance, created by angular dependency injection during application bootstrap.
* It has references to the other UI-Router services
*
* #### Note: This object is also exposed as [[$uiRouterProvider]] for injection during angular config time.
*/
var $uiRouter;
/**
* The UI-Router instance
*
* The [[UIRouter]] singleton (the router instance) as a **Provider Object** (injectable during config phase).
*
* This object is the UI-Router singleton instance, created by angular dependency injection during application bootstrap.
* It has references to the other UI-Router services
*
* #### Note: This object is also exposed as [[$uiRouter]] for injection during runtime.
*/
var $uiRouterProvider;
/**
* Transition debug/tracing
*
* The [[Trace]] singleton as a **Service Object** (injectable during runtime).
*
* Enables or disables Transition tracing which can help to debug issues.
*/
var $trace;
/**
* The Transition Service
*
* The [[TransitionService]] singleton as a **Service Object** (injectable during runtime).
*
* This angular service exposes the [[TransitionService]] singleton, which is primarily
* used to register global transition hooks.
*
* #### Note: This object is also exposed as [[$transitionsProvider]] for injection during the config phase.
*/
var $transitions;
/**
* The Transition Service
*
* The [[TransitionService]] singleton as a **Provider Object** (injectable during config phase)
*
* This angular service exposes the [[TransitionService]] singleton, which is primarily
* used to register global transition hooks.
*
* #### Note: This object is also exposed as [[$transitions]] for injection during runtime.
*/
var $transitionsProvider;
/**
* The current [[Transition]] object
*
* The current [[Transition]] object as a **Per-Transition Object** (injectable into Resolve, Hooks, Controllers)
*
* This object returns information about the current transition, including:
*
* - To/from states
* - To/from parameters
* - Transition options
* - States being entered, exited, and retained
* - Resolve data
* - A Promise for the transition
* - Any transition failure information
* - An injector for both Service and Per-Transition Objects
*/
var $transition$;
/**
* The State Service
*
* The [[StateService]] singleton as a **Service Object** (injectable during runtime).
*
* This service used to manage and query information on registered states.
* It exposes state related APIs including:
*
* - Start a [[Transition]]
* - Imperatively lazy load states
* - Check if a state is currently active
* - Look up states by name
* - Build URLs for a state+parameters
* - Configure the global Transition error handler
*
* This angular service exposes the [[StateService]] singleton.
*/
var $state;
/**
* The State Registry
*
* The [[StateRegistry]] singleton as a **Service Object** (injectable during runtime).
*
* This service is used to register/deregister states.
* It has state registration related APIs including:
*
* - Register/deregister states
* - Listen for state registration/deregistration
* - Get states by name
* - Add state decorators (to customize the state creation process)
*
* #### Note: This object is also exposed as [[$stateRegistryProvider]] for injection during the config phase.
*/
var $stateRegistry;
/**
* The State Registry
*
* The [[StateRegistry]] singleton as a **Provider Object** (injectable during config time).
*
* This service is used to register/deregister states.
* It has state registration related APIs including:
*
* - Register/deregister states
* - Listen for state registration/deregistration
* - Get states by name
* - Add state decorators (to customize the state creation process)
*
* #### Note: This object is also exposed as [[$stateRegistry]] for injection during runtime.
*/
var $stateRegistryProvider;
/**
* The View Scroll provider
*
* The [[UIViewScrollProvider]] as a **Provider Object** (injectable during config time).
*
* This angular service exposes the [[UIViewScrollProvider]] singleton and is
* used to disable UI-Router's scroll behavior.
*/
var $uiViewScrollProvider;
/**
* The View Scroll function
*
* The View Scroll function as a **Service Object** (injectable during runtime).
*
* This is a function that scrolls an element into view.
* The element is scrolled after a `$timeout` so the DOM has time to refresh.
*
* If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
* this can be enabled by calling [[UIViewScrollProvider.useAnchorScroll]].
*
* Note: this function is used by the [[directives.uiView]] when the `autoscroll` expression evaluates to true.
*/
var $uiViewScroll;
/**
* The StateProvider
*
* An angular1-only [[StateProvider]] as a **Provider Object** (injectable during config time).
*
* This angular service exposes the [[StateProvider]] singleton.
*
* The `StateProvider` is primarily used to register states or add custom state decorators.
*
* ##### Note: This provider is a ng1 vestige.
* It is a passthrough to [[$stateRegistry]] and [[$state]].
*/
var $stateProvider;
/**
* The URL Service Provider
*
* The [[UrlService]] singleton as a **Provider Object** (injectable during the angular config phase).
*
* A service used to configure and interact with the URL.
* It has URL related APIs including:
*
* - register custom Parameter types `UrlService.config.type` ([[UrlConfigApi.type]])
* - add URL rules: `UrlService.rules.when` ([[UrlRulesApi.when]])
* - configure behavior when no url matches: `UrlService.rules.otherwise` ([[UrlRulesApi.otherwise]])
* - delay initial URL synchronization [[UrlService.deferIntercept]].
* - get or set the current url: [[UrlService.url]]
*
* ##### Note: This service can also be injected during runtime as [[$urlService]].
*/
var $urlServiceProvider;
/**
* The URL Service
*
* The [[UrlService]] singleton as a **Service Object** (injectable during runtime).
*
* Note: This service can also be injected during the config phase as [[$urlServiceProvider]].
*
* Used to configure the URL.
* It has URL related APIs including:
*
* - register custom Parameter types `UrlService.config.type` ([[UrlConfigApi.type]])
* - add URL rules: `UrlService.rules.when` ([[UrlRulesApi.when]])
* - configure behavior when no url matches: `UrlService.rules.otherwise` ([[UrlRulesApi.otherwise]])
* - delay initial URL synchronization [[UrlService.deferIntercept]].
* - get or set the current url: [[UrlService.url]]
*
* ##### Note: This service can also be injected during the config phase as [[$urlServiceProvider]].
*/
var $urlService;
/**
* The URL Router Provider
*
* ### Deprecation warning: This object is now considered internal. Use [[$urlServiceProvider]] instead.
*
* The [[UrlRouter]] singleton as a **Provider Object** (injectable during config time).
*
* #### Note: This object is also exposed as [[$urlRouter]] for injection during runtime.
*
* @deprecated
*/
var $urlRouterProvider;
/**
* The Url Router
*
* ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.
*
* The [[UrlRouter]] singleton as a **Service Object** (injectable during runtime).
*
* #### Note: This object is also exposed as [[$urlRouterProvider]] for injection during angular config time.
*
* @deprecated
*/
var $urlRouter;
/**
* The URL Matcher Factory
*
* ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.
*
* The [[UrlMatcherFactory]] singleton as a **Service Object** (injectable during runtime).
*
* This service is used to set url mapping options, define custom parameter types, and create [[UrlMatcher]] objects.
*
* #### Note: This object is also exposed as [[$urlMatcherFactoryProvider]] for injection during angular config time.
*
* @deprecated
*/
var $urlMatcherFactory;
/**
* The URL Matcher Factory
*
* ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.
*
* The [[UrlMatcherFactory]] singleton as a **Provider Object** (injectable during config time).
*
* This service is used to set url mapping options, define custom parameter types, and create [[UrlMatcher]] objects.
*
* #### Note: This object is also exposed as [[$urlMatcherFactory]] for injection during runtime.
*
* @deprecated
*/
var $urlMatcherFactoryProvider;
//# sourceMappingURL=injectables.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,730 @@
/**
* @ng1api
* @module ng1
*/ /** */
import { StateDeclaration, _ViewDeclaration, IInjectable, Transition, HookResult } from "@uirouter/core";
/**
* The signature for Angular 1 State Transition Hooks.
*
* State hooks are registered as onEnter/onRetain/onExit in state declarations.
* State hooks can additionally be injected with $transition$ and $state$ for
* the current [[Transition]] and [[StateObject]] in the transition.
*
* Transition State Hooks are callback functions that hook into the lifecycle events of specific states during a transition.
* As a transition runs, it may exit some states, retain (keep) states, and enter states.
* As each lifecycle event occurs, the hooks which are registered for the event and that state are called (in priority order).
*
* #### See also:
*
* - [[IHookRegistry.onExit]]
* - [[IHookRegistry.onRetain]]
* - [[IHookRegistry.onEnter]]
*
* #### Example:
* ```js
* onEnter: function() { console.log('Entering'); }
* ```
*
* Not minification-safe
* ```js
* onRetain: function($state$) { console.log('Retained ' + $state$.name); }
* ```
*
* Annotated for minification-safety
* ```js
* onExit: [ '$transition$', '$state', function($transition$, $state) {
* // always redirect to 'foo' state when being exited
* if ($transition$.to().name !== 'foo') {
* return $state.target('foo');
* }
* } ]
* ```
*
* @returns an optional [[HookResult]] which may alter the transition
*/
export interface Ng1StateTransitionHook {
(...injectables: any[]): HookResult;
}
/**
* @internalapi
* an intermediate interface.
*
* Used to reset [[StateDeclaration]] typings to `any` so the [[Ng1StateDeclaration]] interface can then narrow them */
export interface _Ng1StateDeclaration extends StateDeclaration {
onExit?: any;
onRetain?: any;
onEnter?: any;
views?: any;
}
/**
* The StateDeclaration object is used to define a state or nested state.
* It should be registered with the [[StateRegistry]].
*
* #### Example:
* ```js
* // StateDeclaration object
* var foldersState = {
* name: 'folders',
* url: '/folders',
* resolve: {
* allfolders: function(FolderService) {
* return FolderService.list();
* }
* },
* template: "<ul><li ng-repeat='folder in allfolders'>{{folder.name}}</li></ul>",
* controller: function(allfolders, $scope) {
* $scope.allfolders = allfolders;
* }
* }
* ```
*
* Since this interface extends [[Ng1ViewDeclaration]], any view declaration properties can be set directly
* on the state declaration and they will be applied to the view with the name `$default`. For example:
*
* ```js
* var state = {
* name: 'foo',
* url: '/foo',
* template: '<h1>foo</h1>',
* controller: 'FooController'
* }
* ```
*
* is simply syntactic sugar for:
*
* ```js
* var state = {
* name: 'foo',
* url: '/foo',
* views: {
* $default: {
* template: '<h1>foo</h1>',
* controller: 'FooController
* }
* }
* }
* ```
*
* If a state definition contains a `views:` object, any view properties set directly on the state are ignored.
* Thus, this is an invalid state defintion:
*
* ```js
* var state = {
* name: 'foo',
* url: '/foo',
* controller: 'FooController, // invalid because views: exists
* views: {
* header: {
* template: '<h1>header</h1>'
* }
* }
* }
* ```
*/
export interface Ng1StateDeclaration extends _Ng1StateDeclaration, Ng1ViewDeclaration {
/**
* An optional object which defines multiple named views.
*
* Each key is the name of a view, and each value is a [[Ng1ViewDeclaration]].
* Unnamed views are internally renamed to `$default`.
*
* A view's name is used to match an active `<ui-view>` directive in the DOM. When the state
* is entered, the state's views are activated and matched with active `<ui-view>` directives:
*
* - The view's name is processed into a ui-view target:
* - ui-view address: an address to a ui-view
* - state anchor: the state to anchor the address to
*
* Examples:
*
* Targets three named ui-views in the parent state's template
*
* #### Example:
* ```js
* views: {
* header: {
* controller: "headerCtrl",
* templateUrl: "header.html"
* },
* body: {
* controller: "bodyCtrl",
* templateUrl: "body.html"
* },
* footer: "footerComponent"
* }
* ```
*
* #### Example:
* ```js
* // Targets named ui-view="header" in the template of the ancestor state 'top'
* // and the named `ui-view="body" from the parent state's template.
* views: {
* 'header@top': {
* controller: "msgHeaderCtrl",
* templateUrl: "msgHeader.html"
* },
* 'body': {
* controller: "messagesCtrl",
* templateUrl: "messages.html"
* }
* }
* ```
*
* ## View targeting details
*
* There are a few styles of view addressing/targeting.
* The most common is a simple `ui-view` name
*
* #### Simple ui-view name
*
* Addresses without an `@` are anchored to the parent state.
*
* #### Example:
* ```js
* // target the `<div ui-view='foo'></div>` created in the parent state's view
* views: {
* foo: {...}
* }
* ```
*
* #### View name anchored to a state
*
* You can anchor the `ui-view` name to a specific state by including an `@`
*
* #### Example:
* targets the `<div ui-view='foo'></div>` which was created in a view owned by the state `bar.baz`
* ```js
* views: {
* 'foo@bar.baz': {...}
* }
* ```
*
* #### Absolute addressing
*
* You can address a `ui-view` absolutely, using dotted notation, by prefixing the address with a `!`.
* Dotted addresses traverse the hierarchy of `ui-view`s active in the DOM:
*
* #### Example:
* absolutely targets the `<div ui-view='nested'></div>`
* ... which was created in the unnamed/$default root `<ui-view></ui-view>`
* ```js
* views: {
* '!$default.nested': {...}
* }
* ```
*
* #### Relative addressing
*
* Absolute addressing is actually relative addressing, anchored to the unnamed root state (`""`).
* You can also use relative addressing anchored to *any state*, in order to target a target deeply nested `ui-views`:
* The `ui-view` is targeted relative to the anchored state by traversing the nested `ui-view` names.
*
* #### Example:
* targets the `<div ui-view='bar'></div>`
* ... which was created inside the
* `<div ui-view='foo'></div>`
* ... which was created inside the parent state's template.
* ```js
* views: {
* 'foo.bar': {...}
* }
* ```
*
* #### Example:
* targets the `<div ui-view='bar'></div>`
* ... which was created in `<div ui-view='foo'></div>`
* ... which was created in a template from the state `baz.qux`
* ```js
* views: {
* 'foo.bar@baz.qux': {...}
* }
* ```
*
* #### Example:
* a view can relatively target a named `ui-view` defined on an ancestor using `^` (meaning "parent")
* ```js
* views: {
* 'foo@^': {...}, // foo@(parent state) (same as simply 'foo')
* 'bar@^.^': {...}, // bar@(grandparent state)
* 'baz@^.^.^': {...}, // baz@(great-grandparent state)
* }
* ```
*
* For additional in-depth details about how `ui-view` addressing works, see the internal api [[ViewService.match]].
*
* ---
*
* ## State template+controller and `views:` incompatiblity
*
* If a state has a `views` object, any state-level view properties ([[Ng1ViewDeclaration]]) are ignored. Therefore,
* if _any view_ for a state is declared in the `views` object, then _all of the state's views_ must be defined in
* the `views` object. The state declaration must not have any of the following fields:
* - component
* - bindings
* - resolveAs
* - template
* - templateUrl
* - templateProvider
* - controller
* - controllerAs
* - controllerProvider
*/
views?: {
[key: string]: string | Ng1ViewDeclaration;
};
/**
* A state hook invoked when a state is being entered.
*
* The hook can inject global services.
* It can also inject `$transition$` or `$state$` (from the current transition).
*
* ### Example:
* ```js
* $stateProvider.state({
* name: 'mystate',
* onEnter: (MyService, $transition$, $state$) => {
* return MyService.doSomething($state$.name, $transition$.params());
* }
* });
* ```
*
* #### Example:`
* ```js
* $stateProvider.state({
* name: 'mystate',
* onEnter: [ 'MyService', '$transition$', '$state$', function (MyService, $transition$, $state$) {
* return MyService.doSomething($state$.name, $transition$.params());
* } ]
* });
* ```
*/
onEnter?: Ng1StateTransitionHook | IInjectable;
/**
* A state hook invoked when a state is being exited.
*
* The hook can inject global services.
* It can also inject `$transition$` or `$state$` (from the current transition).
*
* ### Example:
* ```js
* $stateProvider.state({
* name: 'mystate',
* onExit: (MyService, $transition$, $state$) => {
* return MyService.doSomething($state$.name, $transition$.params());
* }
* });
* ```
*
* #### Example:`
* ```js
* $stateProvider.state({
* name: 'mystate',
* onExit: [ 'MyService', '$transition$', '$state$', function (MyService, $transition$, $state$) {
* return MyService.doSomething($state$.name, $transition$.params());
* } ]
* });
* ```
*/
onExit?: Ng1StateTransitionHook | IInjectable;
/**
* A state hook invoked when a state is being retained.
*
* The hook can inject global services.
* It can also inject `$transition$` or `$state$` (from the current transition).
*
* #### Example:
* ```js
* $stateProvider.state({
* name: 'mystate',
* onRetain: (MyService, $transition$, $state$) => {
* return MyService.doSomething($state$.name, $transition$.params());
* }
* });
* ```
*
* #### Example:`
* ```js
* $stateProvider.state({
* name: 'mystate',
* onRetain: [ 'MyService', '$transition$', '$state$', function (MyService, $transition$, $state$) {
* return MyService.doSomething($state$.name, $transition$.params());
* } ]
* });
* ```
*/
onRetain?: Ng1StateTransitionHook | IInjectable;
/**
* Makes all search/query parameters `dynamic`
*
* ### Deprecation warning: use [[ParamDeclaration.dynamic]] instead
*
* @deprecated
*/
reloadOnSearch?: boolean;
}
export interface Ng1ViewDeclaration extends _ViewDeclaration {
/**
* The name of the component to use for this view.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* The name of an [angular 1.5+ `.component()`](https://docs.angularjs.org/guide/component) (or directive with
* bindToController and/or scope declaration) which will be used for this view.
*
* Resolve data can be provided to the component via the component's `bindings` object (for 1.3+ directives, the
* `bindToController` is used; for other directives, the `scope` declaration is used). For each binding declared
* on the component, any resolve with the same name is set on the component's controller instance. The binding
* is provided to the component as a one-time-binding. In general, components should likewise declare their
* input bindings as [one-way ("&lt;")](https://docs.angularjs.org/api/ng/service/$compile#-scope-).
*
* Note: inside a "views:" block, a bare string `"foo"` is shorthand for `{ component: "foo" }`
*
* Note: Mapping from resolve names to component inputs may be specified using [[bindings]].
*
* #### Example:
* ```js
* .state('profile', {
* // Use the <my-profile></my-profile> component for the Unnamed view
* component: 'MyProfile',
* }
*
* .state('messages', {
* // use the <nav-bar></nav-bar> component for the view named 'header'
* // use the <message-list></message-list> component for the view named 'content'
* views: {
* header: { component: 'NavBar' },
* content: { component: 'MessageList' }
* }
* }
*
* .state('contacts', {
* // Inside a "views:" block, a bare string "NavBar" is shorthand for { component: "NavBar" }
* // use the <nav-bar></nav-bar> component for the view named 'header'
* // use the <contact-list></contact-list> component for the view named 'content'
* views: {
* header: 'NavBar',
* content: 'ContactList'
* }
* }
* ```
*
*
* Note: When using `component` to define a view, you may _not_ use any of: `template`, `templateUrl`,
* `templateProvider`, `controller`, `controllerProvider`, `controllerAs`.
*
*
* See also: Todd Motto's angular 1.3 and 1.4 [backport of .component()](https://github.com/toddmotto/angular-component)
*/
component?: string;
/**
* An object which maps `resolve`s to [[component]] `bindings`.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* When using a [[component]] declaration (`component: 'myComponent'`), each input binding for the component is supplied
* data from a resolve of the same name, by default. You may supply data from a different resolve name by mapping it here.
*
* Each key in this object is the name of one of the component's input bindings.
* Each value is the name of the resolve that should be provided to that binding.
*
* Any component bindings that are omitted from this map get the default behavior of mapping to a resolve of the
* same name.
*
* #### Example:
* ```js
* $stateProvider.state('foo', {
* resolve: {
* foo: function(FooService) { return FooService.get(); },
* bar: function(BarService) { return BarService.get(); }
* },
* component: 'Baz',
* // The component's `baz` binding gets data from the `bar` resolve
* // The component's `foo` binding gets data from the `foo` resolve (default behavior)
* bindings: {
* baz: 'bar'
* }
* });
*
* app.component('Baz', {
* templateUrl: 'baz.html',
* controller: 'BazController',
* bindings: {
* foo: '<', // foo binding
* baz: '<' // baz binding
* }
* });
* ```
*
*/
bindings?: {
[key: string]: string;
};
/**
* Dynamic component provider function.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* This is an injectable provider function which returns the name of the component to use.
* The provider will invoked during a Transition in which the view's state is entered.
* The provider is called after the resolve data is fetched.
*
* #### Example:
* ```js
* componentProvider: function(MyResolveData, $transition$) {
* if (MyResolveData.foo) {
* return "fooComponent"
* } else if ($transition$.to().name === 'bar') {
* return "barComponent";
* }
* }
* ```
*/
componentProvider?: IInjectable;
/**
* The view's controller function or name
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* The controller function, or the name of a registered controller. The controller function will be used
* to control the contents of the [[directives.uiView]] directive.
*
* If specified as a string, controllerAs can be declared here, i.e., "FooController as foo" instead of in
* a separate [[controllerAs]] property.
*
* See: [[Ng1Controller]] for information about component-level router hooks.
*/
controller?: (IInjectable | string);
/**
* A controller alias name.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* If present, the controller will be published to scope under the `controllerAs` name.
* See: https://docs.angularjs.org/api/ng/directive/ngController
*/
controllerAs?: string;
/**
* Dynamic controller provider function.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* This is an injectable provider function which returns the actual controller function, or the name
* of a registered controller. The provider will invoked during a Transition in which the view's state is
* entered. The provider is called after the resolve data is fetched.
*
* #### Example:
* ```js
* controllerProvider: function(MyResolveData, $transition$) {
* if (MyResolveData.foo) {
* return "FooCtrl"
* } else if ($transition$.to().name === 'bar') {
* return "BarCtrl";
* } else {
* return function($scope) {
* $scope.baz = "Qux";
* }
* }
* }
* ```
*/
controllerProvider?: IInjectable;
/**
* The scope variable name to use for resolve data.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* When a view is activated, the resolved data for the state which the view belongs to is put on the scope.
* This property sets the name of the scope variable to use for the resolved data.
*
* Defaults to `$resolve`.
*/
resolveAs?: string;
/**
* The HTML template for the view.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* HTML template as a string, or a function which returns an html template as a string.
* This template will be used to render the corresponding [[directives.uiView]] directive.
*
* This property takes precedence over templateUrl.
*
* If `template` is a function, it will be called with the Transition parameters as the first argument.
*
* #### Example:
* ```js
* template: "<h1>inline template definition</h1><div ui-view></div>"
* ```
*
* #### Example:
* ```js
* template: function(params) {
* return "<h1>generated template</h1>";
* }
* ```
*/
template?: (Function | string);
/**
* The URL for the HTML template for the view.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* A path or a function that returns a path to an html template.
* The template will be fetched and used to render the corresponding [[directives.uiView]] directive.
*
* If `templateUrl` is a function, it will be called with the Transition parameters as the first argument.
*
* #### Example:
* ```js
* templateUrl: "/templates/home.html"
* ```
*
* #### Example:
* ```js
* templateUrl: function(params) {
* return myTemplates[params.pageId];
* }
* ```
*/
templateUrl?: (string | Function);
/**
* Injected function which returns the HTML template.
*
* A property of [[Ng1StateDeclaration]] or [[Ng1ViewDeclaration]]:
*
* Injected function which returns the HTML template.
* The template will be used to render the corresponding [[directives.uiView]] directive.
*
* #### Example:
* ```js
* templateProvider: function(MyTemplateService, $transition$) {
* return MyTemplateService.getTemplate($transition$.params().pageId);
* }
* ```
*/
templateProvider?: IInjectable;
}
/**
* The shape of a controller for a view (and/or component), defining the controller callbacks.
*
* A view in UI-Router is comprised of either a `component` ([[Ng1ViewDeclaration.component]]) or a combination of a
* `template` (or `templateProvider`) and a `controller` (or `controllerProvider`).
*
* The `controller` object (or the `component`'s controller object) can define component-level controller callbacks,
* which UI-Router will call at the appropriate times. These callbacks are similar to Transition Hooks
* ([[IHookRegistry]]), but are only called if the view is currently active.
*
* This interface defines the UI-Router component callbacks.
*
*/
export interface Ng1Controller {
/** @hidden */
$onInit(): void;
/**
* This callback is called when parameter values have changed.
*
* This callback can be used to respond to changing parameter values in the current state, or in parent/child states.
* This callback is especially handy when using dynamic parameters ([[ParamDeclaration.dynamic]])
*
* Called when:
* - The view is still active
* - A new transition has completed successfully
* - The state for the view (controller) was not reloaded
* - At least one parameter value was changed
*
* Called with:
* @param newValues an object containing the changed parameter values
* @param $transition$ the new Transition which triggered this callback
*
* #### Example:
* ```js
* angular.module('foo').controller('FancyCtrl', function() {
* this.uiOnParamsChanged = function(newParams) {
* console.log("new params: ", newParams);
* }
* });
* ```
*/
uiOnParamsChanged(newValues: any, $transition$: Transition): void;
/**
* This callback is called when the view's state is about to be exited.
*
* This callback is used to inform a view that it is about to be exited, due to a new [[Transition]].
* The callback can ask for user confirmation, and cancel or alter the new Transition. The callback should
* return a value, or a promise for a value. If a promise is returned, the new Transition waits until the
* promise settles.
*
*
* Called when:
* - The view is still active
* - A new Transition is about to run
* - The new Transition will exit the view's state
*
* Called with:
* - The new Transition
*
* Relevant return Values:
* - `false`: The transition is cancelled.
* - A rejected promise: The transition is cancelled.
* - [[TargetState]]: The transition is redirected to the new target state.
* - Anything else: the transition will continue normally (the state and view will be deactivated)
*
* #### Example:
* ```js
* app.component('myComponent', {
* template: '<input ng-model="$ctrl.data" type="text">',
* bindings: { 'data': '<' },
* controller: function() {
*
* this.originalData = angular.copy(this.data);
*
* this.uiCanExit = function() {
* if (!angular.equals(this.data, this.originalData)) {
* // Note: This could also return a Promise and request async
* // confirmation using something like ui-bootstrap $modal
* return window.confirm("Data has changed. Exit anyway and lose changes?");
* }
* }
* }
* }
* ```
*
* @param transition the new Transition that is about to exit the component's state
* @return a HookResult, or a promise for a HookResult
*/
uiCanExit(transition: Transition): HookResult;
}
/**
* Manages which template-loading mechanism to use.
*
* Defaults to `$templateRequest` on Angular versions starting from 1.3, `$http` otherwise.
*/
export interface TemplateFactoryProvider {
/**
* Forces $templateFactory to use $http instead of $templateRequest.
*
* UI-Router uses `$templateRequest` by default on angular 1.3+.
* Use this method to choose to use `$http` instead.
*
* ---
*
* ## Security warning
*
* This might cause XSS, as $http doesn't enforce the regular security checks for
* templates that have been introduced in Angular 1.3.
*
* See the $sce documentation, section
* <a href="https://docs.angularjs.org/api/ng/service/$sce#impact-on-loading-templates">
* Impact on loading templates</a> for more details about this mechanism.
*
* *Note: forcing this to `false` on Angular 1.2.x will crash, because `$templateRequest` is not implemented.*
*
* @param useUnsafeHttpService `true` to use `$http` to fetch templates
*/
useHttpService(useUnsafeHttpService: boolean): any;
}
declare module "@uirouter/core/lib/state/stateRegistry" {
interface StateRegistry {
register(state: Ng1StateDeclaration): any;
}
}

View file

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=interface.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,6 @@
/** @hidden */
export declare const resolveFactory: () => {
resolve: (invocables: {
[key: string]: Function;
}, locals?: {}, parent?: Promise<any>) => Promise<{}>;
};

View file

@ -0,0 +1,69 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/** @module ng1 */ /** */
var core_1 = require("@uirouter/core");
var angular = require("angular");
/**
* Implementation of the legacy `$resolve` service for angular 1.
*/
var $resolve = {
/**
* Asynchronously injects a resolve block.
*
* This emulates most of the behavior of the ui-router 0.2.x $resolve.resolve() service API.
*
* ### Not bundled by default
*
* This API is no longer not part of the standard `@uirouter/angularjs` bundle.
* For users of the prebuilt bundles, add the `release/resolveService.min.js` UMD bundle.
* For bundlers (webpack, browserify, etc), add `@uirouter/angularjs/lib/legacy/resolveService`.
*
* ---
*
* Given an object `invocables`, where keys are strings and values are injectable functions,
* injects each function, and waits for the resulting promise to resolve.
* When all resulting promises are resolved, returns the results as an object.
*
* #### Example:
* ```js
* let invocables = {
* foo: [ '$http', ($http) =>
* $http.get('/api/foo').then(resp => resp.data) ],
* bar: [ 'foo', '$http', (foo, $http) =>
* $http.get('/api/bar/' + foo.barId).then(resp => resp.data) ]
* }
* $resolve.resolve(invocables)
* .then(results => console.log(results.foo, results.bar))
* // Logs foo and bar:
* // { id: 123, barId: 456, fooData: 'foo data' }
* // { id: 456, barData: 'bar data' }
* ```
*
* @param invocables an object which looks like an [[StateDeclaration.resolve]] object; keys are resolve names and values are injectable functions
* @param locals key/value pre-resolved data (locals)
* @param parent a promise for a "parent resolve"
*/
resolve: function (invocables, locals, parent) {
if (locals === void 0) { locals = {}; }
var parentNode = new core_1.PathNode(new core_1.StateObject({ params: {}, resolvables: [] }));
var node = new core_1.PathNode(new core_1.StateObject({ params: {}, resolvables: [] }));
var context = new core_1.ResolveContext([parentNode, node]);
context.addResolvables(core_1.resolvablesBuilder({ resolve: invocables }), node.state);
var resolveData = function (parentLocals) {
var rewrap = function (_locals) { return core_1.resolvablesBuilder({ resolve: core_1.mapObj(_locals, function (local) { return function () { return local; }; }) }); };
context.addResolvables(rewrap(parentLocals), parentNode.state);
context.addResolvables(rewrap(locals), node.state);
var tuples2ObjR = function (acc, tuple) {
acc[tuple.token] = tuple.value;
return acc;
};
return context.resolvePath().then(function (results) { return results.reduce(tuples2ObjR, {}); });
};
return parent ? parent.then(resolveData) : resolveData({});
}
};
/** @hidden */
exports.resolveFactory = function () { return $resolve; };
// The old $resolve service
angular.module('ui.router').factory('$resolve', exports.resolveFactory);
//# sourceMappingURL=resolveService.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "resolveService.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/legacy/resolveService.ts"
],
"names": [],
"mappings": ";;AAAA,kBAAkB,CAAC,MAAM;AACzB,uCAAwG;AACxG,iCAAmC;AAEnC;;GAEG;AACH,IAAI,QAAQ,GAAG;IACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IACH,OAAO,EAAE,UAAC,UAAuC,EAAE,MAAW,EAAE,MAAqB;QAAlC,uBAAA,EAAA,WAAW;QAC5D,IAAI,UAAU,GAAG,IAAI,eAAQ,CAAC,IAAI,kBAAW,CAAO,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;QACtF,IAAI,IAAI,GAAG,IAAI,eAAQ,CAAC,IAAI,kBAAW,CAAO,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;QAChF,IAAI,OAAO,GAAG,IAAI,qBAAc,CAAC,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;QAErD,OAAO,CAAC,cAAc,CAAC,yBAAkB,CAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAEtF,IAAM,WAAW,GAAG,UAAC,YAAiB;YACpC,IAAM,MAAM,GAAG,UAAC,OAAY,IAAK,OAAA,yBAAkB,CAAO,EAAE,OAAO,EAAE,aAAM,CAAC,OAAO,EAAE,UAAA,KAAK,IAAI,OAAA,cAAM,OAAA,KAAK,EAAL,CAAK,EAAX,CAAW,CAAC,EAAE,CAAC,EAA5E,CAA4E,CAAC;YAC9G,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,UAAU,CAAC,KAAK,CAAC,CAAC;YAC/D,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;YAEnD,IAAM,WAAW,GAAG,UAAC,GAAQ,EAAE,KAAiC;gBAC9D,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC;gBAC/B,MAAM,CAAC,GAAG,CAAC;YACb,CAAC,CAAC;YACF,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,UAAA,OAAO,IAAI,OAAA,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC,EAA/B,CAA+B,CAAC,CAAC;QAChF,CAAC,CAAC;QAEF,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IAC7D,CAAC;CACF,CAAC;AAEF,cAAc;AACD,QAAA,cAAc,GAAG,cAAM,OAAA,QAAQ,EAAR,CAAQ,CAAC;AAE7C,2BAA2B;AAC3B,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC,UAAU,EAAQ,sBAAc,CAAC,CAAC",
"sourcesContent": [
"/** @module ng1 */ /** */\nimport { StateObject, PathNode, ResolveContext, Obj, mapObj, resolvablesBuilder } from \"@uirouter/core\";\nimport * as angular from \"angular\";\n\n/**\n * Implementation of the legacy `$resolve` service for angular 1.\n */\nvar $resolve = {\n /**\n * Asynchronously injects a resolve block.\n *\n * This emulates most of the behavior of the ui-router 0.2.x $resolve.resolve() service API.\n *\n * ### Not bundled by default\n *\n * This API is no longer not part of the standard `@uirouter/angularjs` bundle.\n * For users of the prebuilt bundles, add the `release/resolveService.min.js` UMD bundle.\n * For bundlers (webpack, browserify, etc), add `@uirouter/angularjs/lib/legacy/resolveService`.\n *\n * ---\n *\n * Given an object `invocables`, where keys are strings and values are injectable functions,\n * injects each function, and waits for the resulting promise to resolve.\n * When all resulting promises are resolved, returns the results as an object.\n *\n * #### Example:\n * ```js\n * let invocables = {\n * foo: [ '$http', ($http) =>\n * $http.get('/api/foo').then(resp => resp.data) ],\n * bar: [ 'foo', '$http', (foo, $http) =>\n * $http.get('/api/bar/' + foo.barId).then(resp => resp.data) ]\n * }\n * $resolve.resolve(invocables)\n * .then(results => console.log(results.foo, results.bar))\n * // Logs foo and bar:\n * // { id: 123, barId: 456, fooData: 'foo data' }\n * // { id: 456, barData: 'bar data' }\n * ```\n *\n * @param invocables an object which looks like an [[StateDeclaration.resolve]] object; keys are resolve names and values are injectable functions\n * @param locals key/value pre-resolved data (locals)\n * @param parent a promise for a \"parent resolve\"\n */\n resolve: (invocables: { [key: string]: Function }, locals = {}, parent?: Promise<any>) => {\n let parentNode = new PathNode(new StateObject(<any> { params: {}, resolvables: [] }));\n let node = new PathNode(new StateObject(<any> { params: {}, resolvables: [] }));\n let context = new ResolveContext([parentNode, node]);\n\n context.addResolvables(resolvablesBuilder(<any> { resolve: invocables }), node.state);\n\n const resolveData = (parentLocals: Obj) => {\n const rewrap = (_locals: Obj) => resolvablesBuilder(<any> { resolve: mapObj(_locals, local => () => local) });\n context.addResolvables(rewrap(parentLocals), parentNode.state);\n context.addResolvables(rewrap(locals), node.state);\n\n const tuples2ObjR = (acc: Obj, tuple: { token: any, value: any }) => {\n acc[tuple.token] = tuple.value;\n return acc;\n };\n return context.resolvePath().then(results => results.reduce(tuples2ObjR, {}));\n };\n\n return parent ? parent.then(resolveData) : resolveData({});\n }\n};\n\n/** @hidden */\nexport const resolveFactory = () => $resolve;\n\n// The old $resolve service\nangular.module('ui.router').factory('$resolve', <any> resolveFactory);\n"
]
}

View file

@ -0,0 +1,124 @@
import { IAngularEvent } from "angular";
/**
* An event broadcast on `$rootScope` when the state transition **begins**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] instead
*
* You can use `event.preventDefault()`
* to prevent the transition from happening and then the transition promise will be
* rejected with a `'transition prevented'` value.
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]]
*
* #### Example:
* ```js
* $rootScope.$on('$stateChangeStart', function(event, transition) {
* event.preventDefault();
* // transitionTo() promise will be rejected with
* // a 'transition prevented' error
* })
* ```
*
* @event $stateChangeStart
* @deprecated
*/
export declare var $stateChangeStart: IAngularEvent;
/**
* An event broadcast on `$rootScope` if a transition is **cancelled**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] instead
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that was cancelled
*
* @event $stateChangeCancel
* @deprecated
*/
export declare var $stateChangeCancel: IAngularEvent;
/**
* An event broadcast on `$rootScope` once the state transition is **complete**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] and [[Transition.promise]], or [[Transition.onSuccess]]
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that just succeeded
*
* @event $stateChangeSuccess
* @deprecated
*/
export declare var $stateChangeSuccess: IAngularEvent;
/**
* An event broadcast on `$rootScope` when an **error occurs** during transition.
*
* ### Deprecation warning: use [[TransitionService.onStart]] and [[Transition.promise]], or [[Transition.onError]]
*
* It's important to note that if you
* have any errors in your resolve functions (javascript errors, non-existent services, etc)
* they will not throw traditionally. You must listen for this $stateChangeError event to
* catch **ALL** errors.
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `error`: The reason the transition errored.
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that errored
*
* @event $stateChangeError
* @deprecated
*/
export declare var $stateChangeError: IAngularEvent;
/**
* An event broadcast on `$rootScope` when a requested state **cannot be found** using the provided state name.
*
* ### Deprecation warning: use [[StateService.onInvalid]] instead
*
* The event is broadcast allowing any handlers a single chance to deal with the error (usually by
* lazy-loading the unfound state). A `TargetState` object is passed to the listener handler,
* you can see its properties in the example. You can use `event.preventDefault()` to abort the
* transition and the promise returned from `transitionTo()` will be rejected with a
* `'transition aborted'` error.
*
* Additional arguments to the event handler are provided:
* - `unfoundState` Unfound State information. Contains: `to, toParams, options` properties.
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
*
* #### Example:
* ```js
* // somewhere, assume lazy.state has not been defined
* $state.go("lazy.state", { a: 1, b: 2 }, { inherit: false });
*
* // somewhere else
* $scope.$on('$stateNotFound', function(event, transition) {
* function(event, unfoundState, fromState, fromParams){
* console.log(unfoundState.to); // "lazy.state"
* console.log(unfoundState.toParams); // {a:1, b:2}
* console.log(unfoundState.options); // {inherit:false} + default options
* });
* ```
*
* @event $stateNotFound
* @deprecated
*/
export declare var $stateNotFound: IAngularEvent;

View file

@ -0,0 +1,150 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* # Legacy state events
*
* Polyfill implementation of the UI-Router 0.2.x state events.
*
* The 0.2.x state events are deprecated. We recommend moving to Transition Hooks instead, as they
* provide much more flexibility, support async, and provide the context (the Transition, etc) necessary
* to implement meaningful application behaviors.
*
* To enable these state events, include the `stateEvents.js` file in your project, e.g.,
* ```
* <script src="stateEvents.js"></script>
* ```
* and also make sure you depend on the `ui.router.state.events` angular module, e.g.,
* ```
* angular.module("myApplication", ['ui.router', 'ui.router.state.events']
* ```
*
* @module ng1_state_events
*/ /** */
var angular_1 = require("../angular");
(function () {
var isFunction = angular_1.ng.isFunction, isString = angular_1.ng.isString;
function applyPairs(memo, keyValTuple) {
var key, value;
if (Array.isArray(keyValTuple))
key = keyValTuple[0], value = keyValTuple[1];
if (!isString(key))
throw new Error("invalid parameters to applyPairs");
memo[key] = value;
return memo;
}
function stateChangeStartHandler($transition$) {
if (!$transition$.options().notify || !$transition$.valid() || $transition$.ignored())
return;
var $injector = $transition$.injector();
var $stateEvents = $injector.get('$stateEvents');
var $rootScope = $injector.get('$rootScope');
var $state = $injector.get('$state');
var $urlRouter = $injector.get('$urlRouter');
var enabledEvents = $stateEvents.provider.enabled();
var toParams = $transition$.params("to");
var fromParams = $transition$.params("from");
if (enabledEvents.$stateChangeSuccess) {
var startEvent = $rootScope.$broadcast('$stateChangeStart', $transition$.to(), toParams, $transition$.from(), fromParams, $transition$.options(), $transition$);
if (startEvent.defaultPrevented) {
if (enabledEvents.$stateChangeCancel) {
$rootScope.$broadcast('$stateChangeCancel', $transition$.to(), toParams, $transition$.from(), fromParams, $transition$.options(), $transition$);
}
//Don't update and resync url if there's been a new transition started. see issue #2238, #600
if ($state.transition == null)
$urlRouter.update();
return false;
}
// right after global state is updated
var successOpts = { priority: 9999 };
$transition$.onSuccess({}, function () {
$rootScope.$broadcast('$stateChangeSuccess', $transition$.to(), toParams, $transition$.from(), fromParams, $transition$.options(), $transition$);
}, successOpts);
}
if (enabledEvents.$stateChangeError) {
$transition$.promise["catch"](function (error) {
if (error && (error.type === 2 /* RejectType.SUPERSEDED */ || error.type === 3 /* RejectType.ABORTED */))
return;
var evt = $rootScope.$broadcast('$stateChangeError', $transition$.to(), toParams, $transition$.from(), fromParams, error, $transition$.options(), $transition$);
if (!evt.defaultPrevented) {
$urlRouter.update();
}
});
}
}
stateNotFoundHandler.$inject = ['$to$', '$from$', '$state', '$rootScope', '$urlRouter'];
function stateNotFoundHandler($to$, $from$, injector) {
var $state = injector.get('$state');
var $rootScope = injector.get('$rootScope');
var $urlRouter = injector.get('$urlRouter');
var redirect = { to: $to$.identifier(), toParams: $to$.params(), options: $to$.options() };
var e = $rootScope.$broadcast('$stateNotFound', redirect, $from$.state(), $from$.params());
if (e.defaultPrevented || e.retry)
$urlRouter.update();
function redirectFn() {
return $state.target(redirect.to, redirect.toParams, redirect.options);
}
if (e.defaultPrevented) {
return false;
}
else if (e.retry || !!$state.get(redirect.to)) {
return e.retry && isFunction(e.retry.then) ? e.retry.then(redirectFn) : redirectFn();
}
}
$StateEventsProvider.$inject = ['$stateProvider'];
function $StateEventsProvider($stateProvider) {
$StateEventsProvider.prototype.instance = this;
var runtime = false;
var allEvents = ['$stateChangeStart', '$stateNotFound', '$stateChangeSuccess', '$stateChangeError'];
var enabledStateEvents = allEvents.map(function (e) { return [e, true]; }).reduce(applyPairs, {});
function assertNotRuntime() {
if (runtime)
throw new Error("Cannot enable events at runtime (use $stateEventsProvider");
}
/**
* Enables the deprecated UI-Router 0.2.x State Events
* [ '$stateChangeStart', '$stateNotFound', '$stateChangeSuccess', '$stateChangeError' ]
*/
this.enable = function () {
var events = [];
for (var _i = 0; _i < arguments.length; _i++) {
events[_i] = arguments[_i];
}
assertNotRuntime();
if (!events || !events.length)
events = allEvents;
events.forEach(function (event) { return enabledStateEvents[event] = true; });
};
/**
* Disables the deprecated UI-Router 0.2.x State Events
* [ '$stateChangeStart', '$stateNotFound', '$stateChangeSuccess', '$stateChangeError' ]
*/
this.disable = function () {
var events = [];
for (var _i = 0; _i < arguments.length; _i++) {
events[_i] = arguments[_i];
}
assertNotRuntime();
if (!events || !events.length)
events = allEvents;
events.forEach(function (event) { return delete enabledStateEvents[event]; });
};
this.enabled = function () { return enabledStateEvents; };
this.$get = $get;
$get.$inject = ['$transitions'];
function $get($transitions) {
runtime = true;
if (enabledStateEvents["$stateNotFound"])
$stateProvider.onInvalid(stateNotFoundHandler);
if (enabledStateEvents.$stateChangeStart)
$transitions.onBefore({}, stateChangeStartHandler, { priority: 1000 });
return {
provider: $StateEventsProvider.prototype.instance
};
}
}
angular_1.ng.module('ui.router.state.events', ['ui.router.state'])
.provider("$stateEvents", $StateEventsProvider)
.run(['$stateEvents', function ($stateEvents) {
}]);
})();
//# sourceMappingURL=stateEvents.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,43 @@
/**
* @internalapi
* @module ng1
*/ /** */
import { LocationConfig, LocationServices, UIRouter } from "@uirouter/core";
import { ILocationService, ILocationProvider } from "angular";
/**
* Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service
*/
export declare class Ng1LocationServices implements LocationConfig, LocationServices {
private $locationProvider;
private $location;
private $sniffer;
path: any;
search: any;
hash: any;
hashPrefix: any;
port: any;
protocol: any;
host: any;
baseHref: any;
private _urlListeners;
dispose(): void;
constructor($locationProvider: ILocationProvider);
onChange(callback: Function): () => Function[];
html5Mode(): any;
url(newUrl?: string, replace?: boolean, state?: any): string;
_runtimeServices($rootScope: any, $location: ILocationService, $sniffer: any, $browser: any): void;
/**
* Applys ng1-specific path parameter encoding
*
* The Angular 1 `$location` service is a bit weird.
* It doesn't allow slashes to be encoded/decoded bi-directionally.
*
* See the writeup at https://github.com/angular-ui/ui-router/issues/2598
*
* This code patches the `path` parameter type so it encoded/decodes slashes as ~2F
*
* @param router
*/
static monkeyPatchPathParameterType(router: UIRouter): void;
}

View file

@ -0,0 +1,75 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@uirouter/core");
/**
* Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service
*/
var Ng1LocationServices = /** @class */ (function () {
function Ng1LocationServices($locationProvider) {
// .onChange() registry
this._urlListeners = [];
this.$locationProvider = $locationProvider;
var _lp = core_1.val($locationProvider);
core_1.createProxyFunctions(_lp, this, _lp, ['hashPrefix']);
}
Ng1LocationServices.prototype.dispose = function () { };
Ng1LocationServices.prototype.onChange = function (callback) {
var _this = this;
this._urlListeners.push(callback);
return function () { return core_1.removeFrom(_this._urlListeners)(callback); };
};
Ng1LocationServices.prototype.html5Mode = function () {
var html5Mode = this.$locationProvider.html5Mode();
html5Mode = core_1.isObject(html5Mode) ? html5Mode.enabled : html5Mode;
return html5Mode && this.$sniffer.history;
};
Ng1LocationServices.prototype.url = function (newUrl, replace, state) {
if (replace === void 0) { replace = false; }
if (newUrl)
this.$location.url(newUrl);
if (replace)
this.$location.replace();
if (state)
this.$location.state(state);
return this.$location.url();
};
Ng1LocationServices.prototype._runtimeServices = function ($rootScope, $location, $sniffer, $browser) {
var _this = this;
this.$location = $location;
this.$sniffer = $sniffer;
// Bind $locationChangeSuccess to the listeners registered in LocationService.onChange
$rootScope.$on("$locationChangeSuccess", function (evt) { return _this._urlListeners.forEach(function (fn) { return fn(evt); }); });
var _loc = core_1.val($location);
var _browser = core_1.val($browser);
// Bind these LocationService functions to $location
core_1.createProxyFunctions(_loc, this, _loc, ["replace", "path", "search", "hash"]);
// Bind these LocationConfig functions to $location
core_1.createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']);
// Bind these LocationConfig functions to $browser
core_1.createProxyFunctions(_browser, this, _browser, ['baseHref']);
};
/**
* Applys ng1-specific path parameter encoding
*
* The Angular 1 `$location` service is a bit weird.
* It doesn't allow slashes to be encoded/decoded bi-directionally.
*
* See the writeup at https://github.com/angular-ui/ui-router/issues/2598
*
* This code patches the `path` parameter type so it encoded/decodes slashes as ~2F
*
* @param router
*/
Ng1LocationServices.monkeyPatchPathParameterType = function (router) {
var pathType = router.urlMatcherFactory.type('path');
pathType.encode = function (val) {
return val != null ? val.toString().replace(/(~|\/)/g, function (m) { return ({ '~': '~~', '/': '~2F' }[m]); }) : val;
};
pathType.decode = function (val) {
return val != null ? val.toString().replace(/(~~|~2F)/g, function (m) { return ({ '~~': '~', '~2F': '/' }[m]); }) : val;
};
};
return Ng1LocationServices;
}());
exports.Ng1LocationServices = Ng1LocationServices;
//# sourceMappingURL=locationServices.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "locationServices.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/locationServices.ts"
],
"names": [],
"mappings": ";;AAKA,uCAAiF;AAGjF;;GAEG;AACH;IAmBE,6BAAY,iBAAoC;QALhD,uBAAuB;QACf,kBAAa,GAAe,EAAE,CAAC;QAKrC,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,GAAG,GAAG,UAAG,CAAC,iBAAiB,CAAC,CAAC;QACjC,2BAAoB,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC;IACvD,CAAC;IAND,qCAAO,GAAP,cAAY,CAAC;IAQb,sCAAQ,GAAR,UAAS,QAAkB;QAA3B,iBAGC;QAFC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAClC,MAAM,CAAC,cAAM,OAAA,iBAAU,CAAC,KAAI,CAAC,aAAa,CAAC,CAAC,QAAQ,CAAC,EAAxC,CAAwC,CAAC;IACxD,CAAC;IAED,uCAAS,GAAT;QACE,IAAI,SAAS,GAAQ,IAAI,CAAC,iBAAiB,CAAC,SAAS,EAAE,CAAC;QACxD,SAAS,GAAG,eAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;QAChE,MAAM,CAAC,SAAS,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;IAC5C,CAAC;IAED,iCAAG,GAAH,UAAI,MAAe,EAAE,OAAe,EAAE,KAAM;QAAvB,wBAAA,EAAA,eAAe;QAClC,EAAE,CAAC,CAAC,MAAM,CAAC;YAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACvC,EAAE,CAAC,CAAC,OAAO,CAAC;YAAC,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;QACtC,EAAE,CAAC,CAAC,KAAK,CAAC;YAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACvC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC;IAC9B,CAAC;IAED,8CAAgB,GAAhB,UAAiB,UAAU,EAAE,SAA2B,EAAE,QAAQ,EAAE,QAAQ;QAA5E,iBAeC;QAdC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,sFAAsF;QACtF,UAAU,CAAC,GAAG,CAAC,wBAAwB,EAAE,UAAA,GAAG,IAAI,OAAA,KAAI,CAAC,aAAa,CAAC,OAAO,CAAC,UAAA,EAAE,IAAI,OAAA,EAAE,CAAC,GAAG,CAAC,EAAP,CAAO,CAAC,EAAzC,CAAyC,CAAC,CAAC;QAC3F,IAAI,IAAI,GAAG,UAAG,CAAC,SAAS,CAAC,CAAC;QAC1B,IAAI,QAAQ,GAAG,UAAG,CAAC,QAAQ,CAAC,CAAC;QAE7B,oDAAoD;QACpD,2BAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC;QAC9E,mDAAmD;QACnD,2BAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;QACrE,kDAAkD;QAClD,2BAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;IAC/D,CAAC;IAED;;;;;;;;;;;OAWG;IACI,gDAA4B,GAAnC,UAAoC,MAAgB;QAClD,IAAI,QAAQ,GAAc,MAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAEhE,QAAQ,CAAC,MAAM,GAAG,UAAC,GAAQ;YACvB,OAAA,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,SAAS,EAAE,UAAA,CAAC,IAAI,OAAA,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,EAA9B,CAA8B,CAAC,CAAC,CAAC,CAAC,GAAG;QAA1F,CAA0F,CAAC;QAE/F,QAAQ,CAAC,MAAM,GAAG,UAAC,GAAW;YAC1B,OAAA,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,UAAA,CAAC,IAAI,OAAA,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,EAA9B,CAA8B,CAAC,CAAC,CAAC,CAAC,GAAG;QAA5F,CAA4F,CAAC;IAEnG,CAAC;IACH,0BAAC;AAAD,CAAC,AAlFD,IAkFC;AAlFY,kDAAmB",
"sourcesContent": [
"/**\n * @internalapi\n * @module ng1\n */ /** */\nimport { LocationConfig, LocationServices, UIRouter, ParamType } from \"@uirouter/core\";\nimport { val, createProxyFunctions, removeFrom, isObject } from \"@uirouter/core\";\nimport { ILocationService, ILocationProvider } from \"angular\";\n\n/**\n * Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service\n */\nexport class Ng1LocationServices implements LocationConfig, LocationServices {\n private $locationProvider: ILocationProvider;\n private $location: ILocationService;\n private $sniffer;\n\n path;\n search;\n hash;\n hashPrefix;\n port;\n protocol;\n host;\n baseHref;\n\n // .onChange() registry\n private _urlListeners: Function[] = [];\n\n dispose() { }\n\n constructor($locationProvider: ILocationProvider) {\n this.$locationProvider = $locationProvider;\n let _lp = val($locationProvider);\n createProxyFunctions(_lp, this, _lp, ['hashPrefix']);\n }\n\n onChange(callback: Function) {\n this._urlListeners.push(callback);\n return () => removeFrom(this._urlListeners)(callback);\n }\n\n html5Mode() {\n let html5Mode: any = this.$locationProvider.html5Mode();\n html5Mode = isObject(html5Mode) ? html5Mode.enabled : html5Mode;\n return html5Mode && this.$sniffer.history;\n }\n\n url(newUrl?: string, replace = false, state?) {\n if (newUrl) this.$location.url(newUrl);\n if (replace) this.$location.replace();\n if (state) this.$location.state(state);\n return this.$location.url();\n }\n\n _runtimeServices($rootScope, $location: ILocationService, $sniffer, $browser) {\n this.$location = $location;\n this.$sniffer = $sniffer;\n\n // Bind $locationChangeSuccess to the listeners registered in LocationService.onChange\n $rootScope.$on(\"$locationChangeSuccess\", evt => this._urlListeners.forEach(fn => fn(evt)));\n let _loc = val($location);\n let _browser = val($browser);\n\n // Bind these LocationService functions to $location\n createProxyFunctions(_loc, this, _loc, [\"replace\", \"path\", \"search\", \"hash\"]);\n // Bind these LocationConfig functions to $location\n createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']);\n // Bind these LocationConfig functions to $browser\n createProxyFunctions(_browser, this, _browser, ['baseHref']);\n }\n\n /**\n * Applys ng1-specific path parameter encoding\n *\n * The Angular 1 `$location` service is a bit weird.\n * It doesn't allow slashes to be encoded/decoded bi-directionally.\n *\n * See the writeup at https://github.com/angular-ui/ui-router/issues/2598\n *\n * This code patches the `path` parameter type so it encoded/decodes slashes as ~2F\n *\n * @param router\n */\n static monkeyPatchPathParameterType(router: UIRouter) {\n let pathType: ParamType = router.urlMatcherFactory.type('path');\n\n pathType.encode = (val: any) =>\n val != null ? val.toString().replace(/(~|\\/)/g, m => ({ '~': '~~', '/': '~2F' }[m])) : val;\n\n pathType.decode = (val: string) =>\n val != null ? val.toString().replace(/(~~|~2F)/g, m => ({ '~~': '~', '~2F': '/' }[m])) : val;\n\n }\n}\n"
]
}

View file

@ -0,0 +1,16 @@
import { IRootScopeService } from "angular";
import { ResolveContext, TypedMap } from "@uirouter/core";
import { StateProvider } from "./stateProvider";
import { UrlRouterProvider } from "./urlRouterProvider";
declare module '@uirouter/core/lib/router' {
interface UIRouter {
/** @hidden */
stateProvider: StateProvider;
/** @hidden */
urlRouterProvider: UrlRouterProvider;
}
}
export declare function watchDigests($rootScope: IRootScopeService): void;
/** @hidden TODO: find a place to move this */
export declare const getLocals: (ctx: ResolveContext) => TypedMap<any>;

View file

@ -0,0 +1,116 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* # Angular 1 types
*
* UI-Router core provides various Typescript types which you can use for code completion and validating parameter values, etc.
* The customizations to the core types for Angular UI-Router are documented here.
*
* The optional [[$resolve]] service is also documented here.
*
* @module ng1
* @preferred
*/
/** for typedoc */
var angular_1 = require("./angular");
var core_1 = require("@uirouter/core");
var views_1 = require("./statebuilders/views");
var templateFactory_1 = require("./templateFactory");
var stateProvider_1 = require("./stateProvider");
var onEnterExitRetain_1 = require("./statebuilders/onEnterExitRetain");
var locationServices_1 = require("./locationServices");
var urlRouterProvider_1 = require("./urlRouterProvider");
angular_1.ng.module("ui.router.angular1", []);
var mod_init = angular_1.ng.module('ui.router.init', []);
var mod_util = angular_1.ng.module('ui.router.util', ['ng', 'ui.router.init']);
var mod_rtr = angular_1.ng.module('ui.router.router', ['ui.router.util']);
var mod_state = angular_1.ng.module('ui.router.state', ['ui.router.router', 'ui.router.util', 'ui.router.angular1']);
var mod_main = angular_1.ng.module('ui.router', ['ui.router.init', 'ui.router.state', 'ui.router.angular1']);
var mod_cmpt = angular_1.ng.module('ui.router.compat', ['ui.router']); // tslint:disable-line
var router = null;
$uiRouter.$inject = ['$locationProvider'];
/** This angular 1 provider instantiates a Router and exposes its services via the angular injector */
function $uiRouter($locationProvider) {
// Create a new instance of the Router when the $uiRouterProvider is initialized
router = this.router = new core_1.UIRouter();
router.stateProvider = new stateProvider_1.StateProvider(router.stateRegistry, router.stateService);
// Apply ng1 specific StateBuilder code for `views`, `resolve`, and `onExit/Retain/Enter` properties
router.stateRegistry.decorator("views", views_1.ng1ViewsBuilder);
router.stateRegistry.decorator("onExit", onEnterExitRetain_1.getStateHookBuilder("onExit"));
router.stateRegistry.decorator("onRetain", onEnterExitRetain_1.getStateHookBuilder("onRetain"));
router.stateRegistry.decorator("onEnter", onEnterExitRetain_1.getStateHookBuilder("onEnter"));
router.viewService._pluginapi._viewConfigFactory('ng1', views_1.getNg1ViewConfigFactory());
var ng1LocationService = router.locationService = router.locationConfig = new locationServices_1.Ng1LocationServices($locationProvider);
locationServices_1.Ng1LocationServices.monkeyPatchPathParameterType(router);
// backwards compat: also expose router instance as $uiRouterProvider.router
router['router'] = router;
router['$get'] = $get;
$get.$inject = ['$location', '$browser', '$sniffer', '$rootScope', '$http', '$templateCache'];
function $get($location, $browser, $sniffer, $rootScope, $http, $templateCache) {
ng1LocationService._runtimeServices($rootScope, $location, $sniffer, $browser);
delete router['router'];
delete router['$get'];
return router;
}
return router;
}
var getProviderFor = function (serviceName) { return ['$uiRouterProvider', function ($urp) {
var service = $urp.router[serviceName];
service["$get"] = function () { return service; };
return service;
}]; };
// This effectively calls $get() on `$uiRouterProvider` to trigger init (when ng enters runtime)
runBlock.$inject = ['$injector', '$q', '$uiRouter'];
function runBlock($injector, $q, $uiRouter) {
core_1.services.$injector = $injector;
core_1.services.$q = $q;
// The $injector is now available.
// Find any resolvables that had dependency annotation deferred
$uiRouter.stateRegistry.get()
.map(function (x) { return x.$$state().resolvables; })
.reduce(core_1.unnestR, [])
.filter(function (x) { return x.deps === "deferred"; })
.forEach(function (resolvable) { return resolvable.deps = $injector.annotate(resolvable.resolveFn, $injector.strictDi); });
}
// $urlRouter service and $urlRouterProvider
var getUrlRouterProvider = function (uiRouter) {
return uiRouter.urlRouterProvider = new urlRouterProvider_1.UrlRouterProvider(uiRouter);
};
// $state service and $stateProvider
// $urlRouter service and $urlRouterProvider
var getStateProvider = function () {
return core_1.extend(router.stateProvider, { $get: function () { return router.stateService; } });
};
watchDigests.$inject = ['$rootScope'];
function watchDigests($rootScope) {
$rootScope.$watch(function () { core_1.trace.approximateDigests++; });
}
exports.watchDigests = watchDigests;
mod_init.provider("$uiRouter", $uiRouter);
mod_rtr.provider('$urlRouter', ['$uiRouterProvider', getUrlRouterProvider]);
mod_util.provider('$urlService', getProviderFor('urlService'));
mod_util.provider('$urlMatcherFactory', ['$uiRouterProvider', function () { return router.urlMatcherFactory; }]);
mod_util.provider('$templateFactory', function () { return new templateFactory_1.TemplateFactory(); });
mod_state.provider('$stateRegistry', getProviderFor('stateRegistry'));
mod_state.provider('$uiRouterGlobals', getProviderFor('globals'));
mod_state.provider('$transitions', getProviderFor('transitionService'));
mod_state.provider('$state', ['$uiRouterProvider', getStateProvider]);
mod_state.factory('$stateParams', ['$uiRouter', function ($uiRouter) { return $uiRouter.globals.params; }]);
mod_main.factory('$view', function () { return router.viewService; });
mod_main.service("$trace", function () { return core_1.trace; });
mod_main.run(watchDigests);
mod_util.run(['$urlMatcherFactory', function ($urlMatcherFactory) { }]);
mod_state.run(['$state', function ($state) { }]);
mod_rtr.run(['$urlRouter', function ($urlRouter) { }]);
mod_init.run(runBlock);
/** @hidden TODO: find a place to move this */
exports.getLocals = function (ctx) {
var tokens = ctx.getTokens().filter(core_1.isString);
var tuples = tokens.map(function (key) {
var resolvable = ctx.getResolvable(key);
var waitPolicy = ctx.getPolicy(resolvable).async;
return [key, waitPolicy === 'NOWAIT' ? resolvable.promise : resolvable.data];
});
return tuples.reduce(core_1.applyPairs, {});
};
//# sourceMappingURL=services.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,3 @@
import { StateService } from "@uirouter/core";
export declare function $IsStateFilter($state: StateService): any;
export declare function $IncludedByStateFilter($state: StateService): any;

View file

@ -0,0 +1,46 @@
"use strict";
/** @module ng1 */ /** for typedoc */
Object.defineProperty(exports, "__esModule", { value: true });
var angular_1 = require("./angular");
/**
* `isState` Filter: truthy if the current state is the parameter
*
* Translates to [[StateService.is]] `$state.is("stateName")`.
*
* #### Example:
* ```html
* <div ng-if="'stateName' | isState">show if state is 'stateName'</div>
* ```
*/
$IsStateFilter.$inject = ['$state'];
function $IsStateFilter($state) {
var isFilter = function (state, params, options) {
return $state.is(state, params, options);
};
isFilter.$stateful = true;
return isFilter;
}
exports.$IsStateFilter = $IsStateFilter;
/**
* `includedByState` Filter: truthy if the current state includes the parameter
*
* Translates to [[StateService.includes]]` $state.is("fullOrPartialStateName")`.
*
* #### Example:
* ```html
* <div ng-if="'fullOrPartialStateName' | includedByState">show if state includes 'fullOrPartialStateName'</div>
* ```
*/
$IncludedByStateFilter.$inject = ['$state'];
function $IncludedByStateFilter($state) {
var includesFilter = function (state, params, options) {
return $state.includes(state, params, options);
};
includesFilter.$stateful = true;
return includesFilter;
}
exports.$IncludedByStateFilter = $IncludedByStateFilter;
angular_1.ng.module('ui.router.state')
.filter('isState', $IsStateFilter)
.filter('includedByState', $IncludedByStateFilter);
//# sourceMappingURL=stateFilters.js.map

View file

@ -0,0 +1,13 @@
{
"version": 3,
"file": "stateFilters.js",
"sourceRoot": "",
"sources": [
"@uirouter/angularjs/stateFilters.ts"
],
"names": [],
"mappings": ";AAAA,kBAAkB,CAAC,kBAAkB;;AAErC,qCAA0C;AAG1C;;;;;;;;;GASG;AACH,cAAc,CAAC,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC;AACpC,wBAA+B,MAAoB;IACjD,IAAI,QAAQ,GAAQ,UAAS,KAAkB,EAAE,MAAW,EAAE,OAAoC;QAChG,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAC3C,CAAC,CAAC;IACF,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC;IAC1B,MAAM,CAAC,QAAQ,CAAC;AAClB,CAAC;AAND,wCAMC;AAED;;;;;;;;;GASG;AACH,sBAAsB,CAAC,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC;AAC5C,gCAAuC,MAAoB;IACzD,IAAI,cAAc,GAAQ,UAAS,KAAkB,EAAE,MAAW,EAAE,OAAmC;QACrG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC,CAAC;IACF,cAAc,CAAC,SAAS,GAAG,IAAI,CAAC;IAChC,MAAM,CAAE,cAAc,CAAC;AACzB,CAAC;AAND,wDAMC;AAED,YAAO,CAAC,MAAM,CAAC,iBAAiB,CAAC;KAC9B,MAAM,CAAC,SAAS,EAAE,cAAc,CAAC;KACjC,MAAM,CAAC,iBAAiB,EAAE,sBAAsB,CAAC,CAAC",
"sourcesContent": [
"/** @module ng1 */ /** for typedoc */\n\nimport { ng as angular } from \"./angular\";\nimport { Obj, StateService, StateOrName } from \"@uirouter/core\";\n\n/**\n * `isState` Filter: truthy if the current state is the parameter\n *\n * Translates to [[StateService.is]] `$state.is(\"stateName\")`.\n *\n * #### Example:\n * ```html\n * <div ng-if=\"'stateName' | isState\">show if state is 'stateName'</div>\n * ```\n */\n$IsStateFilter.$inject = ['$state'];\nexport function $IsStateFilter($state: StateService) {\n var isFilter: any = function(state: StateOrName, params: Obj, options?: { relative?: StateOrName }) {\n return $state.is(state, params, options);\n };\n isFilter.$stateful = true;\n return isFilter;\n}\n\n/**\n * `includedByState` Filter: truthy if the current state includes the parameter\n *\n * Translates to [[StateService.includes]]` $state.is(\"fullOrPartialStateName\")`.\n *\n * #### Example:\n * ```html\n * <div ng-if=\"'fullOrPartialStateName' | includedByState\">show if state includes 'fullOrPartialStateName'</div>\n * ```\n */\n$IncludedByStateFilter.$inject = ['$state'];\nexport function $IncludedByStateFilter($state: StateService) {\n var includesFilter: any = function(state: StateOrName, params: Obj, options: { relative?: StateOrName }) {\n return $state.includes(state, params, options);\n };\n includesFilter.$stateful = true;\n return includesFilter;\n}\n\nangular.module('ui.router.state')\n .filter('isState', $IsStateFilter)\n .filter('includedByState', $IncludedByStateFilter);\n"
]
}

View file

@ -0,0 +1,254 @@
/** @module ng1 */ /** for typedoc */
import { BuilderFunction, StateRegistry, StateService, OnInvalidCallback } from "@uirouter/core";
import { Ng1StateDeclaration } from "./interface";
/**
* The Angular 1 `StateProvider`
*
* The `$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.
*/
export declare class StateProvider {
private stateRegistry;
private stateService;
constructor(stateRegistry: StateRegistry, stateService: StateService);
/**
* Decorates states when they are registered
*
* Allows you to extend (carefully) or override (at your own peril) the
* `stateBuilder` object used internally by [[StateRegistry]].
* This can be used to add custom functionality to ui-router,
* for example inferring templateUrl based on the state name.
*
* When passing only a name, it returns the current (original or decorated) builder
* function that matches `name`.
*
* The builder functions that can be decorated are listed below. Though not all
* necessarily have a good use case for decoration, that is up to you to decide.
*
* In addition, users can attach custom decorators, which will generate new
* properties within the state's internal definition. There is currently no clear
* use-case for this beyond accessing internal states (i.e. $state.$current),
* however, expect this to become increasingly relevant as we introduce additional
* meta-programming features.
*
* **Warning**: Decorators should not be interdependent because the order of
* execution of the builder functions in non-deterministic. Builder functions
* should only be dependent on the state definition object and super function.
*
*
* Existing builder functions and current return values:
*
* - **parent** `{object}` - returns the parent state object.
* - **data** `{object}` - returns state data, including any inherited data that is not
* overridden by own values (if any).
* - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
* or `null`.
* - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
* navigable).
* - **params** `{object}` - returns an array of state params that are ensured to
* be a super-set of parent's params.
* - **views** `{object}` - returns a views object where each key is an absolute view
* name (i.e. "viewName@stateName") and each value is the config object
* (template, controller) for the view. Even when you don't use the views object
* explicitly on a state config, one is still created for you internally.
* So by decorating this builder function you have access to decorating template
* and controller properties.
* - **ownParams** `{object}` - returns an array of params that belong to the state,
* not including any params defined by ancestor states.
* - **path** `{string}` - returns the full path from the root down to this state.
* Needed for state activation.
* - **includes** `{object}` - returns an object that includes every state that
* would pass a `$state.includes()` test.
*
* #### Example:
* Override the internal 'views' builder with a function that takes the state
* definition, and a reference to the internal function being overridden:
* ```js
* $stateProvider.decorator('views', function (state, parent) {
* let result = {},
* views = parent(state);
*
* angular.forEach(views, function (config, name) {
* let autoName = (state.name + '.' + name).replace('.', '/');
* config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
* result[name] = config;
* });
* return result;
* });
*
* $stateProvider.state('home', {
* views: {
* 'contact.list': { controller: 'ListController' },
* 'contact.item': { controller: 'ItemController' }
* }
* });
* ```
*
*
* ```js
* // Auto-populates list and item views with /partials/home/contact/list.html,
* // and /partials/home/contact/item.html, respectively.
* $state.go('home');
* ```
*
* @param {string} name The name of the builder function to decorate.
* @param {object} func A function that is responsible for decorating the original
* builder function. The function receives two parameters:
*
* - `{object}` - state - The state config object.
* - `{object}` - super - The original builder function.
*
* @return {object} $stateProvider - $stateProvider instance
*/
decorator(name: string, func: BuilderFunction): Function | this | BuilderFunction[];
/**
* Registers a state
*
* ### This is a passthrough to [[StateRegistry.register]].
*
* Registers a state configuration under a given state name.
* The stateConfig object has the following acceptable properties.
*
* <a id='template'></a>
*
* - **`template`** - {string|function=} - html template as a string or a function that returns
* an html template as a string which should be used by the uiView directives. This property
* takes precedence over templateUrl.
*
* If `template` is a function, it will be called with the following parameters:
*
* - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <a id='templateUrl'></a>
*
* - **`templateUrl`** - {string|function=} - path or function that returns a path to an html
* template that should be used by uiView.
*
* If `templateUrl` is a function, it will be called with the following parameters:
*
* - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <a id='templateProvider'></a>
*
* - **`templateProvider`** - {function=} - Provider function that returns HTML content
* string.
*
* <a id='controller'></a>
*
* - **`controller`** - {string|function=} - Controller fn that should be associated with newly
* related scope or the name of a registered controller if passed as a string.
*
* <a id='controllerProvider'></a>
*
* - **`controllerProvider`** - {function=} - Injectable provider function that returns
* the actual controller or string.
*
* <a id='controllerAs'></a>
*
* - **`controllerAs`** {string=} A controller alias name. If present the controller will be
* published to scope under the controllerAs name.
*
* <a id='resolve'></a>
*
* - **`resolve`** - {object.&lt;string, function&gt;=} - An optional map of dependencies which
* should be injected into the controller. If any of these dependencies are promises,
* the router will wait for them all to be resolved or one to be rejected before the
* controller is instantiated. If all the promises are resolved successfully, the values
* of the resolved promises are injected and $stateChangeSuccess event is fired. If any
* of the promises are rejected the $stateChangeError event is fired. The map object is:
*
* - key - {string}: name of dependency to be injected into controller
* - factory - {string|function}: If string then it is alias for service. Otherwise if function,
* it is injected and return value it treated as dependency. If result is a promise, it is
* resolved before its value is injected into controller.
*
* <a id='url'></a>
*
* - **`url`** - {string=} - A url with optional parameters. When a state is navigated or
* transitioned to, the `$stateParams` service will be populated with any
* parameters that were passed.
*
* <a id='params'></a>
*
* - **`params`** - {object=} - An array of parameter names or regular expressions. Only
* use this within a state if you are not using url. Otherwise you can specify your
* parameters within the url. When a state is navigated or transitioned to, the
* $stateParams service will be populated with any parameters that were passed.
*
* <a id='views'></a>
*
* - **`views`** - {object=} - Use the views property to set up multiple views or to target views
* manually/explicitly.
*
* <a id='abstract'></a>
*
* - **`abstract`** - {boolean=} - An abstract state will never be directly activated,
* but can provide inherited properties to its common children states.
*
* <a id='onEnter'></a>
*
* - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way
* to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.
*
* <a id='onExit'></a>
*
* - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to
* trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.
*
* <a id='reloadOnSearch'></a>
*
* - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state
* just because a search/query parameter has changed (via $location.search() or $location.hash()).
* Useful for when you'd like to modify $location.search() without triggering a reload.
*
* <a id='data'></a>
*
* - **`data`** - {object=} - Arbitrary data object, useful for custom configuration.
*
* #### Example:
* Some state name examples
* ```js
* // stateName can be a single top-level name (must be unique).
* $stateProvider.state("home", {});
*
* // Or it can be a nested state name. This state is a child of the
* // above "home" state.
* $stateProvider.state("home.newest", {});
*
* // Nest states as deeply as needed.
* $stateProvider.state("home.newest.abc.xyz.inception", {});
*
* // state() returns $stateProvider, so you can chain state declarations.
* $stateProvider
* .state("home", {})
* .state("about", {})
* .state("contacts", {});
* ```
*
* @param {string} name A unique state name, e.g. "home", "about", "contacts".
* To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
* @param {object} definition State configuration object.
*/
state(name: string, definition: Ng1StateDeclaration): StateProvider;
state(definition: Ng1StateDeclaration): StateProvider;
/**
* Registers an invalid state handler
*
* This is a passthrough to [[StateService.onInvalid]] for ng1.
*/
onInvalid(callback: OnInvalidCallback): Function;
}

View file

@ -0,0 +1,140 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/** @module ng1 */ /** for typedoc */
var core_1 = require("@uirouter/core");
/**
* The Angular 1 `StateProvider`
*
* The `$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.
*/
var StateProvider = /** @class */ (function () {
function StateProvider(stateRegistry, stateService) {
this.stateRegistry = stateRegistry;
this.stateService = stateService;
core_1.createProxyFunctions(core_1.val(StateProvider.prototype), this, core_1.val(this));
}
/**
* Decorates states when they are registered
*
* Allows you to extend (carefully) or override (at your own peril) the
* `stateBuilder` object used internally by [[StateRegistry]].
* This can be used to add custom functionality to ui-router,
* for example inferring templateUrl based on the state name.
*
* When passing only a name, it returns the current (original or decorated) builder
* function that matches `name`.
*
* The builder functions that can be decorated are listed below. Though not all
* necessarily have a good use case for decoration, that is up to you to decide.
*
* In addition, users can attach custom decorators, which will generate new
* properties within the state's internal definition. There is currently no clear
* use-case for this beyond accessing internal states (i.e. $state.$current),
* however, expect this to become increasingly relevant as we introduce additional
* meta-programming features.
*
* **Warning**: Decorators should not be interdependent because the order of
* execution of the builder functions in non-deterministic. Builder functions
* should only be dependent on the state definition object and super function.
*
*
* Existing builder functions and current return values:
*
* - **parent** `{object}` - returns the parent state object.
* - **data** `{object}` - returns state data, including any inherited data that is not
* overridden by own values (if any).
* - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
* or `null`.
* - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
* navigable).
* - **params** `{object}` - returns an array of state params that are ensured to
* be a super-set of parent's params.
* - **views** `{object}` - returns a views object where each key is an absolute view
* name (i.e. "viewName@stateName") and each value is the config object
* (template, controller) for the view. Even when you don't use the views object
* explicitly on a state config, one is still created for you internally.
* So by decorating this builder function you have access to decorating template
* and controller properties.
* - **ownParams** `{object}` - returns an array of params that belong to the state,
* not including any params defined by ancestor states.
* - **path** `{string}` - returns the full path from the root down to this state.
* Needed for state activation.
* - **includes** `{object}` - returns an object that includes every state that
* would pass a `$state.includes()` test.
*
* #### Example:
* Override the internal 'views' builder with a function that takes the state
* definition, and a reference to the internal function being overridden:
* ```js
* $stateProvider.decorator('views', function (state, parent) {
* let result = {},
* views = parent(state);
*
* angular.forEach(views, function (config, name) {
* let autoName = (state.name + '.' + name).replace('.', '/');
* config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
* result[name] = config;
* });
* return result;
* });
*
* $stateProvider.state('home', {
* views: {
* 'contact.list': { controller: 'ListController' },
* 'contact.item': { controller: 'ItemController' }
* }
* });
* ```
*
*
* ```js
* // Auto-populates list and item views with /partials/home/contact/list.html,
* // and /partials/home/contact/item.html, respectively.
* $state.go('home');
* ```
*
* @param {string} name The name of the builder function to decorate.
* @param {object} func A function that is responsible for decorating the original
* builder function. The function receives two parameters:
*
* - `{object}` - state - The state config object.
* - `{object}` - super - The original builder function.
*
* @return {object} $stateProvider - $stateProvider instance
*/
StateProvider.prototype.decorator = function (name, func) {
return this.stateRegistry.decorator(name, func) || this;
};
StateProvider.prototype.state = function (name, definition) {
if (core_1.isObject(name)) {
definition = name;
}
else {
definition.name = name;
}
this.stateRegistry.register(definition);
return this;
};
/**
* Registers an invalid state handler
*
* This is a passthrough to [[StateService.onInvalid]] for ng1.
*/
StateProvider.prototype.onInvalid = function (callback) {
return this.stateService.onInvalid(callback);
};
return StateProvider;
}());
exports.StateProvider = StateProvider;
//# sourceMappingURL=stateProvider.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,10 @@
/** @module ng1 */ /** */
import { StateObject, TransitionStateHookFn, BuilderFunction } from "@uirouter/core";
/**
* This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`,
* `onRetain` callback hooks on a [[Ng1StateDeclaration]].
*
* When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder
* ensures that those hooks are injectable for @uirouter/angularjs (ng1).
*/
export declare const getStateHookBuilder: (hookName: "onEnter" | "onExit" | "onRetain") => (state: StateObject, parentFn: BuilderFunction) => TransitionStateHookFn;

View file

@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/** @module ng1 */ /** */
var core_1 = require("@uirouter/core");
var services_1 = require("../services");
/**
* This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`,
* `onRetain` callback hooks on a [[Ng1StateDeclaration]].
*
* When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder
* ensures that those hooks are injectable for @uirouter/angularjs (ng1).
*/
exports.getStateHookBuilder = function (hookName) {
return function stateHookBuilder(state, parentFn) {
var hook = state[hookName];
var pathname = hookName === 'onExit' ? 'from' : 'to';
function decoratedNg1Hook(trans, state) {
var resolveContext = new core_1.ResolveContext(trans.treeChanges(pathname));
var locals = core_1.extend(services_1.getLocals(resolveContext), { $state$: state, $transition$: trans });
return core_1.services.$injector.invoke(hook, this, locals);
}
return hook ? decoratedNg1Hook : undefined;
};
};
//# sourceMappingURL=onEnterExitRetain.js.map

Some files were not shown because too many files have changed in this diff Show more